]>
Commit | Line | Data |
---|---|---|
064af421 | 1 | /* |
e0edde6f | 2 | * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc. |
064af421 | 3 | * |
a14bc59f BP |
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: | |
064af421 | 7 | * |
a14bc59f BP |
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. | |
064af421 BP |
15 | */ |
16 | ||
17 | #include <config.h> | |
18 | #include "daemon.h" | |
7d0c5973 | 19 | #include <assert.h> |
064af421 BP |
20 | #include <errno.h> |
21 | #include <fcntl.h> | |
3762274e | 22 | #include <signal.h> |
064af421 BP |
23 | #include <stdlib.h> |
24 | #include <string.h> | |
3762274e | 25 | #include <sys/resource.h> |
95440284 | 26 | #include <sys/wait.h> |
309eaa2b | 27 | #include <sys/stat.h> |
064af421 | 28 | #include <unistd.h> |
40f0707c | 29 | #include "command-line.h" |
064af421 BP |
30 | #include "fatal-signal.h" |
31 | #include "dirs.h" | |
ac718c9d | 32 | #include "lockfile.h" |
ff8decf1 | 33 | #include "process.h" |
b8781ff0 | 34 | #include "socket-util.h" |
03fbffbd | 35 | #include "timeval.h" |
064af421 | 36 | #include "util.h" |
064af421 BP |
37 | #include "vlog.h" |
38 | ||
d98e6007 | 39 | VLOG_DEFINE_THIS_MODULE(daemon); |
5136ce49 | 40 | |
d4db8309 | 41 | /* --detach: Should we run in the background? */ |
e8087a87 BP |
42 | static bool detach; /* Was --detach specified? */ |
43 | static bool detached; /* Have we already detached? */ | |
064af421 | 44 | |
d4db8309 | 45 | /* --pidfile: Name of pidfile (null if none). */ |
064af421 BP |
46 | static char *pidfile; |
47 | ||
e4bd5e2a BP |
48 | /* Device and inode of pidfile, so we can avoid reopening it. */ |
49 | static dev_t pidfile_dev; | |
50 | static ino_t pidfile_ino; | |
51 | ||
d4db8309 BP |
52 | /* --overwrite-pidfile: Create pidfile even if one already exists and is |
53 | locked? */ | |
e7bd7d78 | 54 | static bool overwrite_pidfile; |
064af421 | 55 | |
d4db8309 | 56 | /* --no-chdir: Should we chdir to "/"? */ |
91a1e24d JP |
57 | static bool chdir_ = true; |
58 | ||
7943cd51 BP |
59 | /* File descriptor used by daemonize_start() and daemonize_complete(). */ |
60 | static int daemonize_fd = -1; | |
95440284 | 61 | |
ff8decf1 BP |
62 | /* --monitor: Should a supervisory process monitor the daemon and restart it if |
63 | * it dies due to an error signal? */ | |
64 | static bool monitor; | |
65 | ||
7d0c5973 BP |
66 | /* For each of the standard file descriptors, whether to replace it by |
67 | * /dev/null (if false) or keep it for the daemon to use (if true). */ | |
68 | static bool save_fds[3]; | |
69 | ||
aacea8ba BP |
70 | static void check_already_running(void); |
71 | static int lock_pidfile(FILE *, int command); | |
72 | ||
064af421 BP |
73 | /* Returns the file name that would be used for a pidfile if 'name' were |
74 | * provided to set_pidfile(). The caller must free the returned string. */ | |
75 | char * | |
d295e8e9 | 76 | make_pidfile_name(const char *name) |
064af421 | 77 | { |
daf03c53 | 78 | return (!name |
b43c6fe2 BP |
79 | ? xasprintf("%s/%s.pid", ovs_rundir(), program_name) |
80 | : abs_file_name(ovs_rundir(), name)); | |
064af421 BP |
81 | } |
82 | ||
83 | /* Sets up a following call to daemonize() to create a pidfile named 'name'. | |
84 | * If 'name' begins with '/', then it is treated as an absolute path. | |
85 | * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by | |
86 | * default. | |
87 | * | |
88 | * If 'name' is null, then program_name followed by ".pid" is used. */ | |
89 | void | |
90 | set_pidfile(const char *name) | |
91 | { | |
92 | free(pidfile); | |
93 | pidfile = make_pidfile_name(name); | |
94 | } | |
95 | ||
96 | /* Returns an absolute path to the configured pidfile, or a null pointer if no | |
97 | * pidfile is configured. The caller must not modify or free the returned | |
98 | * string. */ | |
99 | const char * | |
100 | get_pidfile(void) | |
101 | { | |
102 | return pidfile; | |
103 | } | |
104 | ||
91a1e24d JP |
105 | /* Sets that we do not chdir to "/". */ |
106 | void | |
107 | set_no_chdir(void) | |
108 | { | |
109 | chdir_ = false; | |
110 | } | |
111 | ||
eb077b26 BP |
112 | /* Will we chdir to "/" as part of daemonizing? */ |
113 | bool | |
114 | is_chdir_enabled(void) | |
115 | { | |
116 | return chdir_; | |
117 | } | |
118 | ||
00c08589 BP |
119 | /* Normally, daemonize() or damonize_start() will terminate the program with a |
120 | * message if a locked pidfile already exists. If this function is called, an | |
121 | * existing pidfile will be replaced, with a warning. */ | |
064af421 BP |
122 | void |
123 | ignore_existing_pidfile(void) | |
124 | { | |
e7bd7d78 | 125 | overwrite_pidfile = true; |
064af421 BP |
126 | } |
127 | ||
128 | /* Sets up a following call to daemonize() to detach from the foreground | |
129 | * session, running this process in the background. */ | |
130 | void | |
131 | set_detach(void) | |
132 | { | |
133 | detach = true; | |
134 | } | |
135 | ||
eb077b26 BP |
136 | /* Will daemonize() really detach? */ |
137 | bool | |
138 | get_detach(void) | |
139 | { | |
140 | return detach; | |
141 | } | |
142 | ||
ff8decf1 BP |
143 | /* Sets up a following call to daemonize() to fork a supervisory process to |
144 | * monitor the daemon and restart it if it dies due to an error signal. */ | |
145 | void | |
146 | daemon_set_monitor(void) | |
147 | { | |
148 | monitor = true; | |
149 | } | |
150 | ||
7d0c5973 BP |
151 | /* A daemon doesn't normally have any use for the file descriptors for stdin, |
152 | * stdout, and stderr after it detaches. To keep these file descriptors from | |
153 | * e.g. holding an SSH session open, by default detaching replaces each of | |
154 | * these file descriptors by /dev/null. But a few daemons expect the user to | |
155 | * redirect stdout or stderr to a file, in which case it is desirable to keep | |
156 | * these file descriptors. This function, therefore, disables replacing 'fd' | |
157 | * by /dev/null when the daemon detaches. */ | |
158 | void | |
159 | daemon_save_fd(int fd) | |
160 | { | |
161 | assert(fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO); | |
162 | save_fds[fd] = true; | |
163 | } | |
164 | ||
d4db8309 BP |
165 | /* If a pidfile has been configured, creates it and stores the running |
166 | * process's pid in it. Ensures that the pidfile will be deleted when the | |
167 | * process exits. */ | |
064af421 BP |
168 | static void |
169 | make_pidfile(void) | |
170 | { | |
aacea8ba BP |
171 | long int pid = getpid(); |
172 | struct stat s; | |
173 | char *tmpfile; | |
174 | FILE *file; | |
175 | int error; | |
176 | ||
177 | /* Create a temporary pidfile. */ | |
2388a783 EJ |
178 | if (overwrite_pidfile) { |
179 | tmpfile = xasprintf("%s.tmp%ld", pidfile, pid); | |
180 | fatal_signal_add_file_to_unlink(tmpfile); | |
181 | } else { | |
182 | /* Everyone shares the same file which will be treated as a lock. To | |
183 | * avoid some uncomfortable race conditions, we can't set up the fatal | |
184 | * signal unlink until we've acquired it. */ | |
185 | tmpfile = xasprintf("%s.tmp", pidfile); | |
186 | } | |
187 | ||
188 | file = fopen(tmpfile, "a+"); | |
aacea8ba BP |
189 | if (!file) { |
190 | VLOG_FATAL("%s: create failed (%s)", tmpfile, strerror(errno)); | |
191 | } | |
192 | ||
2388a783 EJ |
193 | error = lock_pidfile(file, F_SETLK); |
194 | if (error) { | |
195 | /* Looks like we failed to acquire the lock. Note that, if we failed | |
196 | * for some other reason (and '!overwrite_pidfile'), we will have | |
197 | * left 'tmpfile' as garbage in the file system. */ | |
198 | VLOG_FATAL("%s: fcntl(F_SETLK) failed (%s)", tmpfile, strerror(error)); | |
199 | } | |
200 | ||
201 | if (!overwrite_pidfile) { | |
202 | /* We acquired the lock. Make sure to clean up on exit, and verify | |
203 | * that we're allowed to create the actual pidfile. */ | |
204 | fatal_signal_add_file_to_unlink(tmpfile); | |
205 | check_already_running(); | |
206 | } | |
207 | ||
aacea8ba BP |
208 | if (fstat(fileno(file), &s) == -1) { |
209 | VLOG_FATAL("%s: fstat failed (%s)", tmpfile, strerror(errno)); | |
210 | } | |
211 | ||
2388a783 EJ |
212 | if (ftruncate(fileno(file), 0) == -1) { |
213 | VLOG_FATAL("%s: truncate failed (%s)", tmpfile, strerror(errno)); | |
214 | } | |
215 | ||
aacea8ba BP |
216 | fprintf(file, "%ld\n", pid); |
217 | if (fflush(file) == EOF) { | |
218 | VLOG_FATAL("%s: write failed (%s)", tmpfile, strerror(errno)); | |
219 | } | |
220 | ||
2388a783 | 221 | error = rename(tmpfile, pidfile); |
aacea8ba | 222 | |
2388a783 EJ |
223 | /* Due to a race, 'tmpfile' may be owned by a different process, so we |
224 | * shouldn't delete it on exit. */ | |
225 | fatal_signal_remove_file_to_unlink(tmpfile); | |
226 | ||
227 | if (error < 0) { | |
228 | VLOG_FATAL("failed to rename \"%s\" to \"%s\" (%s)", | |
229 | tmpfile, pidfile, strerror(errno)); | |
aacea8ba BP |
230 | } |
231 | ||
232 | /* Ensure that the pidfile will get deleted on exit. */ | |
233 | fatal_signal_add_file_to_unlink(pidfile); | |
234 | ||
aacea8ba BP |
235 | /* Clean up. |
236 | * | |
237 | * We don't close 'file' because its file descriptor must remain open to | |
238 | * hold the lock. */ | |
239 | pidfile_dev = s.st_dev; | |
240 | pidfile_ino = s.st_ino; | |
241 | free(tmpfile); | |
064af421 BP |
242 | free(pidfile); |
243 | pidfile = NULL; | |
244 | } | |
245 | ||
246 | /* If configured with set_pidfile() or set_detach(), creates the pid file and | |
247 | * detaches from the foreground session. */ | |
248 | void | |
249 | daemonize(void) | |
95440284 BP |
250 | { |
251 | daemonize_start(); | |
252 | daemonize_complete(); | |
253 | } | |
254 | ||
8aee05cc BP |
255 | /* Calls fork() and on success returns its return value. On failure, logs an |
256 | * error and exits unsuccessfully. | |
257 | * | |
258 | * Post-fork, but before returning, this function calls a few other functions | |
259 | * that are generally useful if the child isn't planning to exec a new | |
260 | * process. */ | |
261 | pid_t | |
262 | fork_and_clean_up(void) | |
263 | { | |
264 | pid_t pid; | |
265 | ||
266 | pid = fork(); | |
267 | if (pid > 0) { | |
268 | /* Running in parent process. */ | |
269 | fatal_signal_fork(); | |
270 | } else if (!pid) { | |
271 | /* Running in child process. */ | |
272 | time_postfork(); | |
273 | lockfile_postfork(); | |
274 | } else { | |
275 | VLOG_FATAL("fork failed (%s)", strerror(errno)); | |
276 | } | |
277 | ||
278 | return pid; | |
279 | } | |
280 | ||
e6c5e539 BP |
281 | /* Forks, then: |
282 | * | |
283 | * - In the parent, waits for the child to signal that it has completed its | |
284 | * startup sequence. Then stores -1 in '*fdp' and returns the child's pid. | |
285 | * | |
286 | * - In the child, stores a fd in '*fdp' and returns 0. The caller should | |
287 | * pass the fd to fork_notify_startup() after it finishes its startup | |
288 | * sequence. | |
289 | * | |
290 | * If something goes wrong with the fork, logs a critical error and aborts the | |
291 | * process. */ | |
7943cd51 BP |
292 | static pid_t |
293 | fork_and_wait_for_startup(int *fdp) | |
294 | { | |
295 | int fds[2]; | |
296 | pid_t pid; | |
297 | ||
279c9e03 | 298 | xpipe(fds); |
7943cd51 | 299 | |
8aee05cc | 300 | pid = fork_and_clean_up(); |
7943cd51 BP |
301 | if (pid > 0) { |
302 | /* Running in parent process. */ | |
af9a1442 | 303 | size_t bytes_read; |
7943cd51 BP |
304 | char c; |
305 | ||
306 | close(fds[1]); | |
af9a1442 | 307 | if (read_fully(fds[0], &c, 1, &bytes_read) != 0) { |
7943cd51 BP |
308 | int retval; |
309 | int status; | |
310 | ||
311 | do { | |
312 | retval = waitpid(pid, &status, 0); | |
313 | } while (retval == -1 && errno == EINTR); | |
314 | ||
2c8fcc9c BP |
315 | if (retval == pid) { |
316 | if (WIFEXITED(status) && WEXITSTATUS(status)) { | |
317 | /* Child exited with an error. Convey the same error | |
318 | * to our parent process as a courtesy. */ | |
319 | exit(WEXITSTATUS(status)); | |
320 | } else { | |
321 | char *status_msg = process_status_msg(status); | |
322 | VLOG_FATAL("fork child died before signaling startup (%s)", | |
323 | status_msg); | |
324 | } | |
325 | } else if (retval < 0) { | |
326 | VLOG_FATAL("waitpid failed (%s)", strerror(errno)); | |
327 | } else { | |
328 | NOT_REACHED(); | |
7943cd51 | 329 | } |
7943cd51 BP |
330 | } |
331 | close(fds[0]); | |
332 | *fdp = -1; | |
333 | } else if (!pid) { | |
334 | /* Running in child process. */ | |
335 | close(fds[0]); | |
7943cd51 | 336 | *fdp = fds[1]; |
7943cd51 BP |
337 | } |
338 | ||
339 | return pid; | |
340 | } | |
341 | ||
342 | static void | |
343 | fork_notify_startup(int fd) | |
344 | { | |
345 | if (fd != -1) { | |
346 | size_t bytes_written; | |
347 | int error; | |
348 | ||
349 | error = write_fully(fd, "", 1, &bytes_written); | |
350 | if (error) { | |
279c9e03 | 351 | VLOG_FATAL("pipe write failed (%s)", strerror(error)); |
7943cd51 BP |
352 | } |
353 | ||
354 | close(fd); | |
355 | } | |
356 | } | |
357 | ||
ff8decf1 BP |
358 | static bool |
359 | should_restart(int status) | |
360 | { | |
361 | if (WIFSIGNALED(status)) { | |
362 | static const int error_signals[] = { | |
363 | SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV, | |
364 | SIGXCPU, SIGXFSZ | |
365 | }; | |
366 | ||
367 | size_t i; | |
368 | ||
369 | for (i = 0; i < ARRAY_SIZE(error_signals); i++) { | |
370 | if (error_signals[i] == WTERMSIG(status)) { | |
371 | return true; | |
372 | } | |
373 | } | |
374 | } | |
375 | return false; | |
376 | } | |
377 | ||
378 | static void | |
379 | monitor_daemon(pid_t daemon_pid) | |
380 | { | |
ff8decf1 | 381 | /* XXX Should log daemon's stderr output at startup time. */ |
a9633ada | 382 | time_t last_restart; |
40f0707c | 383 | char *status_msg; |
cbbdf81c | 384 | int crashes; |
ff8decf1 | 385 | |
781dee08 | 386 | subprogram_name = "monitor"; |
40f0707c | 387 | status_msg = xstrdup("healthy"); |
a9633ada | 388 | last_restart = TIME_MIN; |
cbbdf81c | 389 | crashes = 0; |
ff8decf1 BP |
390 | for (;;) { |
391 | int retval; | |
392 | int status; | |
393 | ||
d86a6c09 EM |
394 | proctitle_set("monitoring pid %lu (%s)", |
395 | (unsigned long int) daemon_pid, status_msg); | |
40f0707c | 396 | |
ff8decf1 BP |
397 | do { |
398 | retval = waitpid(daemon_pid, &status, 0); | |
399 | } while (retval == -1 && errno == EINTR); | |
400 | ||
401 | if (retval == -1) { | |
279c9e03 | 402 | VLOG_FATAL("waitpid failed (%s)", strerror(errno)); |
ff8decf1 | 403 | } else if (retval == daemon_pid) { |
40f0707c | 404 | char *s = process_status_msg(status); |
40f0707c | 405 | if (should_restart(status)) { |
2bf9d87a BP |
406 | free(status_msg); |
407 | status_msg = xasprintf("%d crashes: pid %lu died, %s", | |
408 | ++crashes, | |
409 | (unsigned long int) daemon_pid, s); | |
410 | free(s); | |
411 | ||
7c2dd4c6 BP |
412 | if (WCOREDUMP(status)) { |
413 | /* Disable further core dumps to save disk space. */ | |
414 | struct rlimit r; | |
415 | ||
416 | r.rlim_cur = 0; | |
417 | r.rlim_max = 0; | |
418 | if (setrlimit(RLIMIT_CORE, &r) == -1) { | |
419 | VLOG_WARN("failed to disable core dumps: %s", | |
420 | strerror(errno)); | |
421 | } | |
422 | } | |
423 | ||
a9633ada BP |
424 | /* Throttle restarts to no more than once every 10 seconds. */ |
425 | if (time(NULL) < last_restart + 10) { | |
426 | VLOG_WARN("%s, waiting until 10 seconds since last " | |
427 | "restart", status_msg); | |
428 | for (;;) { | |
429 | time_t now = time(NULL); | |
430 | time_t wakeup = last_restart + 10; | |
431 | if (now >= wakeup) { | |
432 | break; | |
433 | } | |
434 | sleep(wakeup - now); | |
435 | } | |
436 | } | |
437 | last_restart = time(NULL); | |
438 | ||
40f0707c | 439 | VLOG_ERR("%s, restarting", status_msg); |
ff8decf1 BP |
440 | daemon_pid = fork_and_wait_for_startup(&daemonize_fd); |
441 | if (!daemon_pid) { | |
442 | break; | |
443 | } | |
444 | } else { | |
2bf9d87a BP |
445 | VLOG_INFO("pid %lu died, %s, exiting", |
446 | (unsigned long int) daemon_pid, s); | |
447 | free(s); | |
ff8decf1 BP |
448 | exit(0); |
449 | } | |
450 | } | |
451 | } | |
b2d06cb8 | 452 | free(status_msg); |
ff8decf1 BP |
453 | |
454 | /* Running in new daemon process. */ | |
40f0707c | 455 | proctitle_restore(); |
781dee08 | 456 | subprogram_name = ""; |
ff8decf1 BP |
457 | } |
458 | ||
7d0c5973 BP |
459 | /* Close standard file descriptors (except any that the client has requested we |
460 | * leave open by calling daemon_save_fd()). If we're started from e.g. an SSH | |
461 | * session, then this keeps us from holding that session open artificially. */ | |
7943cd51 BP |
462 | static void |
463 | close_standard_fds(void) | |
464 | { | |
465 | int null_fd = get_null_fd(); | |
466 | if (null_fd >= 0) { | |
7d0c5973 BP |
467 | int fd; |
468 | ||
469 | for (fd = 0; fd < 3; fd++) { | |
470 | if (!save_fds[fd]) { | |
471 | dup2(null_fd, fd); | |
472 | } | |
473 | } | |
7943cd51 | 474 | } |
d3824212 BP |
475 | |
476 | /* Disable logging to stderr to avoid wasting CPU time. */ | |
c1a543a8 | 477 | vlog_set_levels(NULL, VLF_CONSOLE, VLL_OFF); |
7943cd51 BP |
478 | } |
479 | ||
95440284 BP |
480 | /* If daemonization is configured, then starts daemonization, by forking and |
481 | * returning in the child process. The parent process hangs around until the | |
482 | * child lets it know either that it completed startup successfully (by calling | |
483 | * daemon_complete()) or that it failed to start up (by exiting with a nonzero | |
484 | * exit code). */ | |
485 | void | |
486 | daemonize_start(void) | |
064af421 | 487 | { |
7943cd51 | 488 | daemonize_fd = -1; |
95440284 | 489 | |
7943cd51 BP |
490 | if (detach) { |
491 | if (fork_and_wait_for_startup(&daemonize_fd) > 0) { | |
95440284 | 492 | /* Running in parent process. */ |
064af421 | 493 | exit(0); |
064af421 | 494 | } |
ff8decf1 BP |
495 | /* Running in daemon or monitor process. */ |
496 | } | |
497 | ||
498 | if (monitor) { | |
499 | int saved_daemonize_fd = daemonize_fd; | |
500 | pid_t daemon_pid; | |
501 | ||
502 | daemon_pid = fork_and_wait_for_startup(&daemonize_fd); | |
503 | if (daemon_pid > 0) { | |
504 | /* Running in monitor process. */ | |
505 | fork_notify_startup(saved_daemonize_fd); | |
506 | close_standard_fds(); | |
507 | monitor_daemon(daemon_pid); | |
508 | } | |
7943cd51 | 509 | /* Running in daemon process. */ |
064af421 | 510 | } |
7943cd51 | 511 | |
aacea8ba BP |
512 | if (pidfile) { |
513 | make_pidfile(); | |
514 | } | |
df5d2ed9 BP |
515 | |
516 | /* Make sure that the unixctl commands for vlog get registered in a | |
517 | * daemon, even before the first log message. */ | |
518 | vlog_init(); | |
064af421 BP |
519 | } |
520 | ||
95440284 | 521 | /* If daemonization is configured, then this function notifies the parent |
e8087a87 BP |
522 | * process that the child process has completed startup successfully. It also |
523 | * call daemonize_post_detach(). | |
a7ff9bd7 BP |
524 | * |
525 | * Calling this function more than once has no additional effect. */ | |
95440284 BP |
526 | void |
527 | daemonize_complete(void) | |
528 | { | |
e8087a87 BP |
529 | if (!detached) { |
530 | detached = true; | |
531 | ||
532 | fork_notify_startup(daemonize_fd); | |
533 | daemonize_fd = -1; | |
534 | daemonize_post_detach(); | |
535 | } | |
536 | } | |
95440284 | 537 | |
e8087a87 BP |
538 | /* If daemonization is configured, then this function does traditional Unix |
539 | * daemonization behavior: join a new session, chdir to the root (if not | |
540 | * disabled), and close the standard file descriptors. | |
541 | * | |
542 | * It only makes sense to call this function as part of an implementation of a | |
543 | * special daemon subprocess. A normal daemon should just call | |
544 | * daemonize_complete(). */ | |
545 | void | |
546 | daemonize_post_detach(void) | |
547 | { | |
7943cd51 | 548 | if (detach) { |
95440284 BP |
549 | setsid(); |
550 | if (chdir_) { | |
551 | ignore(chdir("/")); | |
552 | } | |
7943cd51 | 553 | close_standard_fds(); |
95440284 BP |
554 | } |
555 | } | |
556 | ||
064af421 BP |
557 | void |
558 | daemon_usage(void) | |
559 | { | |
560 | printf( | |
561 | "\nDaemon options:\n" | |
e7bd7d78 | 562 | " --detach run in background as daemon\n" |
91a1e24d | 563 | " --no-chdir do not chdir to '/'\n" |
e7bd7d78 JP |
564 | " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n" |
565 | " --overwrite-pidfile with --pidfile, start even if already " | |
566 | "running\n", | |
b43c6fe2 | 567 | ovs_rundir(), program_name); |
064af421 BP |
568 | } |
569 | ||
aacea8ba BP |
570 | static int |
571 | lock_pidfile__(FILE *file, int command, struct flock *lck) | |
572 | { | |
573 | int error; | |
574 | ||
575 | lck->l_type = F_WRLCK; | |
576 | lck->l_whence = SEEK_SET; | |
577 | lck->l_start = 0; | |
578 | lck->l_len = 0; | |
579 | lck->l_pid = 0; | |
580 | ||
581 | do { | |
582 | error = fcntl(fileno(file), command, lck) == -1 ? errno : 0; | |
583 | } while (error == EINTR); | |
584 | return error; | |
585 | } | |
586 | ||
587 | static int | |
588 | lock_pidfile(FILE *file, int command) | |
589 | { | |
590 | struct flock lck; | |
591 | ||
592 | return lock_pidfile__(file, command, &lck); | |
593 | } | |
594 | ||
18e124a2 | 595 | static pid_t |
aacea8ba | 596 | read_pidfile__(const char *pidfile, bool delete_if_stale) |
064af421 | 597 | { |
aacea8ba | 598 | struct stat s, s2; |
064af421 | 599 | struct flock lck; |
aacea8ba | 600 | char line[128]; |
064af421 BP |
601 | FILE *file; |
602 | int error; | |
603 | ||
e4bd5e2a BP |
604 | if ((pidfile_ino || pidfile_dev) |
605 | && !stat(pidfile, &s) | |
606 | && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) { | |
607 | /* It's our own pidfile. We can't afford to open it, because closing | |
608 | * *any* fd for a file that a process has locked also releases all the | |
609 | * locks on that file. | |
610 | * | |
611 | * Fortunately, we know the associated pid anyhow: */ | |
612 | return getpid(); | |
613 | } | |
614 | ||
aacea8ba | 615 | file = fopen(pidfile, "r+"); |
064af421 | 616 | if (!file) { |
aacea8ba | 617 | if (errno == ENOENT && delete_if_stale) { |
18e124a2 BP |
618 | return 0; |
619 | } | |
064af421 BP |
620 | error = errno; |
621 | VLOG_WARN("%s: open: %s", pidfile, strerror(error)); | |
622 | goto error; | |
623 | } | |
624 | ||
aacea8ba BP |
625 | error = lock_pidfile__(file, F_GETLK, &lck); |
626 | if (error) { | |
064af421 BP |
627 | VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error)); |
628 | goto error; | |
629 | } | |
630 | if (lck.l_type == F_UNLCK) { | |
aacea8ba BP |
631 | /* pidfile exists but it isn't locked by anyone. We need to delete it |
632 | * so that a new pidfile can go in its place. But just calling | |
633 | * unlink(pidfile) makes a nasty race: what if someone else unlinks it | |
634 | * before we do and then replaces it by a valid pidfile? We'd unlink | |
635 | * their valid pidfile. We do a little dance to avoid the race, by | |
636 | * locking the invalid pidfile. Only one process can have the invalid | |
637 | * pidfile locked, and only that process has the right to unlink it. */ | |
638 | if (!delete_if_stale) { | |
639 | error = ESRCH; | |
0b376942 | 640 | VLOG_DBG("%s: pid file is stale", pidfile); |
aacea8ba BP |
641 | goto error; |
642 | } | |
643 | ||
644 | /* Get the lock. */ | |
645 | error = lock_pidfile(file, F_SETLK); | |
646 | if (error) { | |
647 | /* We lost a race with someone else doing the same thing. */ | |
648 | VLOG_WARN("%s: lost race to lock pidfile", pidfile); | |
649 | goto error; | |
650 | } | |
651 | ||
652 | /* Is the file we have locked still named 'pidfile'? */ | |
653 | if (stat(pidfile, &s) || fstat(fileno(file), &s2) | |
654 | || s.st_ino != s2.st_ino || s.st_dev != s2.st_dev) { | |
655 | /* No. We lost a race with someone else who got the lock before | |
656 | * us, deleted the pidfile, and closed it (releasing the lock). */ | |
657 | error = EALREADY; | |
658 | VLOG_WARN("%s: lost race to delete pidfile", pidfile); | |
659 | goto error; | |
660 | } | |
661 | ||
662 | /* We won the right to delete the stale pidfile. */ | |
663 | if (unlink(pidfile)) { | |
664 | error = errno; | |
665 | VLOG_WARN("%s: failed to delete stale pidfile (%s)", | |
666 | pidfile, strerror(error)); | |
667 | goto error; | |
668 | } | |
669 | VLOG_DBG("%s: deleted stale pidfile", pidfile); | |
670 | fclose(file); | |
671 | return 0; | |
064af421 BP |
672 | } |
673 | ||
674 | if (!fgets(line, sizeof line, file)) { | |
675 | if (ferror(file)) { | |
676 | error = errno; | |
677 | VLOG_WARN("%s: read: %s", pidfile, strerror(error)); | |
678 | } else { | |
679 | error = ESRCH; | |
680 | VLOG_WARN("%s: read: unexpected end of file", pidfile); | |
681 | } | |
682 | goto error; | |
683 | } | |
684 | ||
685 | if (lck.l_pid != strtoul(line, NULL, 10)) { | |
aacea8ba BP |
686 | /* The process that has the pidfile locked is not the process that |
687 | * created it. It must be stale, with the process that has it locked | |
688 | * preparing to delete it. */ | |
064af421 | 689 | error = ESRCH; |
aacea8ba BP |
690 | VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld", |
691 | pidfile, line, (long int) lck.l_pid); | |
064af421 BP |
692 | goto error; |
693 | } | |
694 | ||
695 | fclose(file); | |
696 | return lck.l_pid; | |
697 | ||
698 | error: | |
699 | if (file) { | |
700 | fclose(file); | |
701 | } | |
702 | return -error; | |
703 | } | |
18e124a2 BP |
704 | |
705 | /* Opens and reads a PID from 'pidfile'. Returns the positive PID if | |
706 | * successful, otherwise a negative errno value. */ | |
707 | pid_t | |
708 | read_pidfile(const char *pidfile) | |
709 | { | |
aacea8ba | 710 | return read_pidfile__(pidfile, false); |
18e124a2 BP |
711 | } |
712 | ||
aacea8ba BP |
713 | /* Checks whether a process with the given 'pidfile' is already running and, |
714 | * if so, aborts. If 'pidfile' is stale, deletes it. */ | |
715 | static void | |
716 | check_already_running(void) | |
18e124a2 | 717 | { |
aacea8ba BP |
718 | long int pid = read_pidfile__(pidfile, true); |
719 | if (pid > 0) { | |
720 | VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile, pid); | |
721 | } else if (pid < 0) { | |
722 | VLOG_FATAL("%s: pidfile check failed (%s), aborting", | |
723 | pidfile, strerror(-pid)); | |
724 | } | |
18e124a2 | 725 | } |