]>
git.proxmox.com Git - mirror_ovs.git/blob - lib/process.c
2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
24 #include <sys/resource.h>
29 #include "openvswitch/dynamic-string.h"
30 #include "fatal-signal.h"
31 #include "openvswitch/list.h"
32 #include "ovs-thread.h"
33 #include "openvswitch/poll-loop.h"
35 #include "socket-util.h"
38 #include "openvswitch/vlog.h"
40 VLOG_DEFINE_THIS_MODULE(process
);
42 COVERAGE_DEFINE(process_start
);
46 #include <asm/param.h>
61 struct raw_process_info
{
62 unsigned long int vsz
; /* Virtual size, in kB. */
63 unsigned long int rss
; /* Resident set size, in kB. */
64 long long int uptime
; /* ms since started. */
65 long long int cputime
; /* ms of CPU used during 'uptime'. */
66 pid_t ppid
; /* Parent. */
67 int core_id
; /* Core id last executed on. */
68 char name
[18]; /* Name. */
71 /* Pipe used to signal child termination. */
75 static struct ovs_list all_processes
= OVS_LIST_INITIALIZER(&all_processes
);
77 static void sigchld_handler(int signr OVS_UNUSED
);
79 /* Initializes the process subsystem (if it is not already initialized). Calls
80 * exit() if initialization fails.
82 * This function may not be called after creating any additional threads.
84 * Calling this function is optional; it will be called automatically by
85 * process_start() if necessary. Calling it explicitly allows the client to
86 * prevent the process from exiting at an unexpected time. */
94 assert_single_threaded();
100 /* Create notification pipe. */
101 xpipe_nonblocking(fds
);
103 /* Set up child termination signal handler. */
104 memset(&sa
, 0, sizeof sa
);
105 sa
.sa_handler
= sigchld_handler
;
106 sigemptyset(&sa
.sa_mask
);
107 sa
.sa_flags
= SA_NOCLDSTOP
| SA_RESTART
;
108 xsigaction(SIGCHLD
, &sa
, NULL
);
113 process_escape_args(char **argv
)
115 struct ds ds
= DS_EMPTY_INITIALIZER
;
117 for (argp
= argv
; *argp
; argp
++) {
118 const char *arg
= *argp
;
121 ds_put_char(&ds
, ' ');
123 if (arg
[strcspn(arg
, " \t\r\n\v\\\'\"")]) {
124 ds_put_char(&ds
, '"');
125 for (p
= arg
; *p
; p
++) {
126 if (*p
== '\\' || *p
== '\"') {
127 ds_put_char(&ds
, '\\');
129 ds_put_char(&ds
, *p
);
131 ds_put_char(&ds
, '"');
133 ds_put_cstr(&ds
, arg
);
139 /* Prepare to start a process whose command-line arguments are given by the
140 * null-terminated 'argv' array. Returns 0 if successful, otherwise a
141 * positive errno value. */
143 process_prestart(char **argv
)
149 /* Log the process to be started. */
150 if (VLOG_IS_DBG_ENABLED()) {
151 char *args
= process_escape_args(argv
);
152 VLOG_DBG("starting subprocess: %s", args
);
156 /* execvp() will search PATH too, but the error in that case is more
157 * obscure, since it is only reported post-fork. */
158 binary
= process_search_path(argv
[0]);
160 VLOG_ERR("%s not found in PATH", argv
[0]);
168 /* Creates and returns a new struct process with the specified 'name' and
170 static struct process
*
171 process_register(const char *name
, pid_t pid
)
176 p
= xzalloc(sizeof *p
);
178 slash
= strrchr(name
, '/');
179 p
->name
= xstrdup(slash
? slash
+ 1 : name
);
182 ovs_list_push_back(&all_processes
, &p
->node
);
189 rlim_is_finite(rlim_t limit
)
191 if (limit
== RLIM_INFINITY
) {
195 #ifdef RLIM_SAVED_CUR /* FreeBSD 8.0 lacks RLIM_SAVED_CUR. */
196 if (limit
== RLIM_SAVED_CUR
) {
201 #ifdef RLIM_SAVED_MAX /* FreeBSD 8.0 lacks RLIM_SAVED_MAX. */
202 if (limit
== RLIM_SAVED_MAX
) {
210 /* Returns the maximum valid FD value, plus 1. */
218 if (!getrlimit(RLIMIT_NOFILE
, &r
) && rlim_is_finite(r
.rlim_cur
)) {
219 max_fds
= r
.rlim_cur
;
221 VLOG_WARN("failed to obtain fd limit, defaulting to 1024");
230 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
231 * argv[0] is used as the name of the process. Searches the PATH environment
232 * variable to find the program to execute.
234 * This function may not be called after creating any additional threads.
236 * All file descriptors are closed before executing the subprocess, except for
239 * Returns 0 if successful, otherwise a positive errno value indicating the
240 * error. If successful, '*pp' is assigned a new struct process that may be
241 * used to query the process's status. On failure, '*pp' is set to NULL. */
243 process_start(char **argv
, struct process
**pp
)
250 assert_single_threaded();
253 COVERAGE_INC(process_start
);
254 error
= process_prestart(argv
);
259 fatal_signal_block(&prev_mask
);
262 VLOG_WARN("fork failed: %s", ovs_strerror(errno
));
265 /* Running in parent process. */
266 *pp
= process_register(argv
[0], pid
);
269 /* Running in child process. */
270 int fd_max
= get_max_fds();
274 for (fd
= 3; fd
< fd_max
; fd
++) {
277 xpthread_sigmask(SIG_SETMASK
, &prev_mask
, NULL
);
278 execvp(argv
[0], argv
);
279 fprintf(stderr
, "execvp(\"%s\") failed: %s\n",
280 argv
[0], ovs_strerror(errno
));
283 xpthread_sigmask(SIG_SETMASK
, &prev_mask
, NULL
);
291 /* Destroys process 'p'. */
293 process_destroy(struct process
*p
)
296 ovs_list_remove(&p
->node
);
302 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
303 * positive errno value. */
305 process_kill(const struct process
*p
, int signr
)
308 return (p
->exited
? ESRCH
309 : !kill(p
->pid
, signr
) ? 0
316 /* Returns the pid of process 'p'. */
318 process_pid(const struct process
*p
)
323 /* Returns the name of process 'p' (the name passed to process_start() with any
324 * leading directories stripped). */
326 process_name(const struct process
*p
)
331 /* Returns true if process 'p' has exited, false otherwise. */
333 process_exited(struct process
*p
)
338 /* Returns process 'p''s exit status, as reported by waitpid(2).
339 * process_status(p) may be called only after process_exited(p) has returned
342 process_status(const struct process
*p
)
344 ovs_assert(p
->exited
);
349 count_crashes(pid_t pid
)
359 sprintf(file_name
, "/proc/%lu/cmdline", (unsigned long int) pid
);
360 stream
= fopen(file_name
, "r");
362 VLOG_WARN_ONCE("%s: open failed (%s)", file_name
, ovs_strerror(errno
));
366 if (!fgets(line
, sizeof line
, stream
)) {
367 VLOG_WARN_ONCE("%s: read failed (%s)", file_name
,
368 feof(stream
) ? "end of file" : ovs_strerror(errno
));
372 paren
= strchr(line
, '(');
375 if (ovs_scan(paren
+ 1, "%d", &x
)) {
386 static unsigned long long int
387 ticks_to_ms(unsigned long long int ticks
)
395 #if USER_HZ == 100 /* Common case. */
396 return ticks
* (1000 / USER_HZ
);
397 #else /* Alpha and some other architectures. */
398 double factor
= 1000.0 / USER_HZ
;
399 return ticks
* factor
+ 0.5;
404 get_raw_process_info(pid_t pid
, struct raw_process_info
*raw
)
406 unsigned long long int vsize
, rss
, start_time
, utime
, stime
;
407 long long int start_msec
;
415 sprintf(file_name
, "/proc/%lu/stat", (unsigned long int) pid
);
416 stream
= fopen(file_name
, "r");
418 VLOG_ERR_ONCE("%s: open failed (%s)",
419 file_name
, ovs_strerror(errno
));
424 "%*d " /* (1. pid) */
425 "(%17[^)]) " /* 2. process name */
426 "%*c " /* (3. state) */
428 "%*d " /* (5. pgid) */
429 "%*d " /* (6. sid) */
430 "%*d " /* (7. tty_nr) */
431 "%*d " /* (8. tty_pgrp) */
432 "%*u " /* (9. flags) */
433 "%*u " /* (10. min_flt) */
434 "%*u " /* (11. cmin_flt) */
435 "%*u " /* (12. maj_flt) */
436 "%*u " /* (13. cmaj_flt) */
437 "%llu " /* 14. utime */
438 "%llu " /* 15. stime */
439 "%*d " /* (16. cutime) */
440 "%*d " /* (17. cstime) */
441 "%*d " /* (18. priority) */
442 "%*d " /* (19. nice) */
443 "%*d " /* (20. num_threads) */
444 "%*d " /* (21. always 0) */
445 "%llu " /* 22. start_time */
446 "%llu " /* 23. vsize */
447 "%llu " /* 24. rss */
448 "%*u " /* (25. rsslim) */
449 "%*u " /* (26. start_code) */
450 "%*u " /* (27. end_code) */
451 "%*u " /* (28. start_stack) */
452 "%*u " /* (29. esp) */
453 "%*u " /* (30. eip) */
454 "%*u " /* (31. pending signals) */
455 "%*u " /* (32. blocked signals) */
456 "%*u " /* (33. ignored signals) */
457 "%*u " /* (34. caught signals) */
458 "%*u " /* (35. whcan) */
459 "%*u " /* (36. always 0) */
460 "%*u " /* (37. always 0) */
461 "%*d " /* (38. exit_signal) */
462 "%d " /* 39. task_cpu */
464 /* These are here for documentation but #if'd out to save
465 * actually parsing them from the stream for no benefit. */
466 "%*u " /* (40. rt_priority) */
467 "%*u " /* (41. policy) */
468 "%*llu " /* (42. blkio_ticks) */
469 "%*lu " /* (43. gtime) */
470 "%*ld" /* (44. cgtime) */
472 , raw
->name
, &ppid
, &utime
, &stime
, &start_time
,
473 &vsize
, &rss
, &raw
->core_id
);
476 VLOG_ERR_ONCE("%s: fscanf failed", file_name
);
480 start_msec
= get_boot_time() + ticks_to_ms(start_time
);
482 raw
->vsz
= vsize
/ 1024;
483 raw
->rss
= rss
* (get_page_size() / 1024);
484 raw
->uptime
= time_wall_msec() - start_msec
;
485 raw
->cputime
= ticks_to_ms(utime
+ stime
);
492 get_process_info(pid_t pid
, struct process_info
*pinfo
)
494 struct raw_process_info child
;
497 if (!get_raw_process_info(pid
, &child
)) {
501 ovs_strlcpy(pinfo
->name
, child
.name
, sizeof pinfo
->name
);
502 pinfo
->vsz
= child
.vsz
;
503 pinfo
->rss
= child
.rss
;
504 pinfo
->booted
= child
.uptime
;
506 pinfo
->uptime
= child
.uptime
;
507 pinfo
->cputime
= child
.cputime
;
508 pinfo
->core_id
= child
.core_id
;
511 struct raw_process_info parent
;
513 get_raw_process_info(child
.ppid
, &parent
);
514 if (!strcmp(child
.name
, parent
.name
)) {
515 pinfo
->booted
= parent
.uptime
;
516 pinfo
->crashes
= count_crashes(child
.ppid
);
523 /* Given 'status', which is a process status in the form reported by waitpid(2)
524 * and returned by process_status(), returns a string describing how the
525 * process terminated. The caller is responsible for freeing the string when
526 * it is no longer needed. */
528 process_status_msg(int status
)
530 struct ds ds
= DS_EMPTY_INITIALIZER
;
532 if (WIFEXITED(status
)) {
533 ds_put_format(&ds
, "exit status %d", WEXITSTATUS(status
));
534 } else if (WIFSIGNALED(status
)) {
535 char namebuf
[SIGNAL_NAME_BUFSIZE
];
537 ds_put_format(&ds
, "killed (%s)",
538 signal_name(WTERMSIG(status
), namebuf
, sizeof namebuf
));
539 } else if (WIFSTOPPED(status
)) {
540 char namebuf
[SIGNAL_NAME_BUFSIZE
];
542 ds_put_format(&ds
, "stopped (%s)",
543 signal_name(WSTOPSIG(status
), namebuf
, sizeof namebuf
));
545 ds_put_format(&ds
, "terminated abnormally (%x)", status
);
547 if (WCOREDUMP(status
)) {
548 ds_put_cstr(&ds
, ", core dumped");
551 ds_put_cstr(&ds
, "function not supported.");
556 /* Executes periodic maintenance activities required by the process module. */
561 char buf
[_POSIX_PIPE_BUF
];
563 if (!ovs_list_is_empty(&all_processes
) && read(fds
[0], buf
, sizeof buf
) > 0) {
566 LIST_FOR_EACH (p
, node
, &all_processes
) {
570 retval
= waitpid(p
->pid
, &status
, WNOHANG
);
571 } while (retval
== -1 && errno
== EINTR
);
572 if (retval
== p
->pid
) {
575 } else if (retval
< 0) {
576 VLOG_WARN("waitpid: %s", ovs_strerror(errno
));
586 /* Causes the next call to poll_block() to wake up when process 'p' has
589 process_wait(struct process
*p
)
593 poll_immediate_wake();
595 poll_fd_wait(fds
[0], POLLIN
);
603 process_search_path(const char *name
)
605 char *save_ptr
= NULL
;
609 if (strchr(name
, '/') || !getenv("PATH")) {
610 return stat(name
, &s
) == 0 ? xstrdup(name
) : NULL
;
613 path
= xstrdup(getenv("PATH"));
614 for (dir
= strtok_r(path
, ":", &save_ptr
); dir
;
615 dir
= strtok_r(NULL
, ":", &save_ptr
)) {
616 char *file
= xasprintf("%s/%s", dir
, name
);
617 if (stat(file
, &s
) == 0) {
628 sigchld_handler(int signr OVS_UNUSED
)
630 ignore(write(fds
[1], "", 1));