]>
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 "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 char name
[18]; /* Name (surrounded by parentheses). */
70 /* Pipe used to signal child termination. */
74 static struct ovs_list all_processes
= OVS_LIST_INITIALIZER(&all_processes
);
76 static void sigchld_handler(int signr OVS_UNUSED
);
78 /* Initializes the process subsystem (if it is not already initialized). Calls
79 * exit() if initialization fails.
81 * This function may not be called after creating any additional threads.
83 * Calling this function is optional; it will be called automatically by
84 * process_start() if necessary. Calling it explicitly allows the client to
85 * prevent the process from exiting at an unexpected time. */
93 assert_single_threaded();
99 /* Create notification pipe. */
100 xpipe_nonblocking(fds
);
102 /* Set up child termination signal handler. */
103 memset(&sa
, 0, sizeof sa
);
104 sa
.sa_handler
= sigchld_handler
;
105 sigemptyset(&sa
.sa_mask
);
106 sa
.sa_flags
= SA_NOCLDSTOP
| SA_RESTART
;
107 xsigaction(SIGCHLD
, &sa
, NULL
);
112 process_escape_args(char **argv
)
114 struct ds ds
= DS_EMPTY_INITIALIZER
;
116 for (argp
= argv
; *argp
; argp
++) {
117 const char *arg
= *argp
;
120 ds_put_char(&ds
, ' ');
122 if (arg
[strcspn(arg
, " \t\r\n\v\\\'\"")]) {
123 ds_put_char(&ds
, '"');
124 for (p
= arg
; *p
; p
++) {
125 if (*p
== '\\' || *p
== '\"') {
126 ds_put_char(&ds
, '\\');
128 ds_put_char(&ds
, *p
);
130 ds_put_char(&ds
, '"');
132 ds_put_cstr(&ds
, arg
);
138 /* Prepare to start a process whose command-line arguments are given by the
139 * null-terminated 'argv' array. Returns 0 if successful, otherwise a
140 * positive errno value. */
142 process_prestart(char **argv
)
148 /* Log the process to be started. */
149 if (VLOG_IS_DBG_ENABLED()) {
150 char *args
= process_escape_args(argv
);
151 VLOG_DBG("starting subprocess: %s", args
);
155 /* execvp() will search PATH too, but the error in that case is more
156 * obscure, since it is only reported post-fork. */
157 binary
= process_search_path(argv
[0]);
159 VLOG_ERR("%s not found in PATH", argv
[0]);
167 /* Creates and returns a new struct process with the specified 'name' and
169 static struct process
*
170 process_register(const char *name
, pid_t pid
)
175 p
= xzalloc(sizeof *p
);
177 slash
= strrchr(name
, '/');
178 p
->name
= xstrdup(slash
? slash
+ 1 : name
);
181 ovs_list_push_back(&all_processes
, &p
->node
);
188 rlim_is_finite(rlim_t limit
)
190 if (limit
== RLIM_INFINITY
) {
194 #ifdef RLIM_SAVED_CUR /* FreeBSD 8.0 lacks RLIM_SAVED_CUR. */
195 if (limit
== RLIM_SAVED_CUR
) {
200 #ifdef RLIM_SAVED_MAX /* FreeBSD 8.0 lacks RLIM_SAVED_MAX. */
201 if (limit
== RLIM_SAVED_MAX
) {
209 /* Returns the maximum valid FD value, plus 1. */
217 if (!getrlimit(RLIMIT_NOFILE
, &r
) && rlim_is_finite(r
.rlim_cur
)) {
218 max_fds
= r
.rlim_cur
;
220 VLOG_WARN("failed to obtain fd limit, defaulting to 1024");
229 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
230 * argv[0] is used as the name of the process. Searches the PATH environment
231 * variable to find the program to execute.
233 * This function may not be called after creating any additional threads.
235 * All file descriptors are closed before executing the subprocess, except for
238 * Returns 0 if successful, otherwise a positive errno value indicating the
239 * error. If successful, '*pp' is assigned a new struct process that may be
240 * used to query the process's status. On failure, '*pp' is set to NULL. */
242 process_start(char **argv
, struct process
**pp
)
249 assert_single_threaded();
252 COVERAGE_INC(process_start
);
253 error
= process_prestart(argv
);
258 fatal_signal_block(&prev_mask
);
261 VLOG_WARN("fork failed: %s", ovs_strerror(errno
));
264 /* Running in parent process. */
265 *pp
= process_register(argv
[0], pid
);
268 /* Running in child process. */
269 int fd_max
= get_max_fds();
273 for (fd
= 3; fd
< fd_max
; fd
++) {
276 xpthread_sigmask(SIG_SETMASK
, &prev_mask
, NULL
);
277 execvp(argv
[0], argv
);
278 fprintf(stderr
, "execvp(\"%s\") failed: %s\n",
279 argv
[0], ovs_strerror(errno
));
282 xpthread_sigmask(SIG_SETMASK
, &prev_mask
, NULL
);
290 /* Destroys process 'p'. */
292 process_destroy(struct process
*p
)
295 ovs_list_remove(&p
->node
);
301 /* Sends signal 'signr' to process 'p'. Returns 0 if successful, otherwise a
302 * positive errno value. */
304 process_kill(const struct process
*p
, int signr
)
307 return (p
->exited
? ESRCH
308 : !kill(p
->pid
, signr
) ? 0
315 /* Returns the pid of process 'p'. */
317 process_pid(const struct process
*p
)
322 /* Returns the name of process 'p' (the name passed to process_start() with any
323 * leading directories stripped). */
325 process_name(const struct process
*p
)
330 /* Returns true if process 'p' has exited, false otherwise. */
332 process_exited(struct process
*p
)
337 /* Returns process 'p''s exit status, as reported by waitpid(2).
338 * process_status(p) may be called only after process_exited(p) has returned
341 process_status(const struct process
*p
)
343 ovs_assert(p
->exited
);
348 count_crashes(pid_t pid
)
358 sprintf(file_name
, "/proc/%lu/cmdline", (unsigned long int) pid
);
359 stream
= fopen(file_name
, "r");
361 VLOG_WARN_ONCE("%s: open failed (%s)", file_name
, ovs_strerror(errno
));
365 if (!fgets(line
, sizeof line
, stream
)) {
366 VLOG_WARN_ONCE("%s: read failed (%s)", file_name
,
367 feof(stream
) ? "end of file" : ovs_strerror(errno
));
371 paren
= strchr(line
, '(');
374 if (ovs_scan(paren
+ 1, "%d", &x
)) {
385 static unsigned long long int
386 ticks_to_ms(unsigned long long int ticks
)
394 #if USER_HZ == 100 /* Common case. */
395 return ticks
* (1000 / USER_HZ
);
396 #else /* Alpha and some other architectures. */
397 double factor
= 1000.0 / USER_HZ
;
398 return ticks
* factor
+ 0.5;
403 get_raw_process_info(pid_t pid
, struct raw_process_info
*raw
)
405 unsigned long long int vsize
, rss
, start_time
, utime
, stime
;
406 long long int start_msec
;
414 sprintf(file_name
, "/proc/%lu/stat", (unsigned long int) pid
);
415 stream
= fopen(file_name
, "r");
417 VLOG_ERR_ONCE("%s: open failed (%s)",
418 file_name
, ovs_strerror(errno
));
423 "%*d " /* (1. pid) */
424 "%17s " /* 2. process name */
425 "%*c " /* (3. state) */
427 "%*d " /* (5. pgid) */
428 "%*d " /* (6. sid) */
429 "%*d " /* (7. tty_nr) */
430 "%*d " /* (8. tty_pgrp) */
431 "%*u " /* (9. flags) */
432 "%*u " /* (10. min_flt) */
433 "%*u " /* (11. cmin_flt) */
434 "%*u " /* (12. maj_flt) */
435 "%*u " /* (13. cmaj_flt) */
436 "%llu " /* 14. utime */
437 "%llu " /* 15. stime */
438 "%*d " /* (16. cutime) */
439 "%*d " /* (17. cstime) */
440 "%*d " /* (18. priority) */
441 "%*d " /* (19. nice) */
442 "%*d " /* (20. num_threads) */
443 "%*d " /* (21. always 0) */
444 "%llu " /* 22. start_time */
445 "%llu " /* 23. vsize */
446 "%llu " /* 24. rss */
448 /* These are here for documentation but #if'd out to save
449 * actually parsing them from the stream for no benefit. */
450 "%*lu " /* (25. rsslim) */
451 "%*lu " /* (26. start_code) */
452 "%*lu " /* (27. end_code) */
453 "%*lu " /* (28. start_stack) */
454 "%*lu " /* (29. esp) */
455 "%*lu " /* (30. eip) */
456 "%*lu " /* (31. pending signals) */
457 "%*lu " /* (32. blocked signals) */
458 "%*lu " /* (33. ignored signals) */
459 "%*lu " /* (34. caught signals) */
460 "%*lu " /* (35. whcan) */
461 "%*lu " /* (36. always 0) */
462 "%*lu " /* (37. always 0) */
463 "%*d " /* (38. exit_signal) */
464 "%*d " /* (39. task_cpu) */
465 "%*u " /* (40. rt_priority) */
466 "%*u " /* (41. policy) */
467 "%*llu " /* (42. blkio_ticks) */
468 "%*lu " /* (43. gtime) */
469 "%*ld" /* (44. cgtime) */
471 , raw
->name
, &ppid
, &utime
, &stime
, &start_time
, &vsize
, &rss
);
474 VLOG_ERR_ONCE("%s: fscanf failed", file_name
);
478 start_msec
= get_boot_time() + ticks_to_ms(start_time
);
480 raw
->vsz
= vsize
/ 1024;
481 raw
->rss
= rss
* (get_page_size() / 1024);
482 raw
->uptime
= time_wall_msec() - start_msec
;
483 raw
->cputime
= ticks_to_ms(utime
+ stime
);
490 get_process_info(pid_t pid
, struct process_info
*pinfo
)
492 struct raw_process_info child
;
495 if (!get_raw_process_info(pid
, &child
)) {
499 pinfo
->vsz
= child
.vsz
;
500 pinfo
->rss
= child
.rss
;
501 pinfo
->booted
= child
.uptime
;
503 pinfo
->uptime
= child
.uptime
;
504 pinfo
->cputime
= child
.cputime
;
507 struct raw_process_info parent
;
509 get_raw_process_info(child
.ppid
, &parent
);
510 if (!strcmp(child
.name
, parent
.name
)) {
511 pinfo
->booted
= parent
.uptime
;
512 pinfo
->crashes
= count_crashes(child
.ppid
);
519 /* Given 'status', which is a process status in the form reported by waitpid(2)
520 * and returned by process_status(), returns a string describing how the
521 * process terminated. The caller is responsible for freeing the string when
522 * it is no longer needed. */
524 process_status_msg(int status
)
526 struct ds ds
= DS_EMPTY_INITIALIZER
;
528 if (WIFEXITED(status
)) {
529 ds_put_format(&ds
, "exit status %d", WEXITSTATUS(status
));
530 } else if (WIFSIGNALED(status
)) {
531 char namebuf
[SIGNAL_NAME_BUFSIZE
];
533 ds_put_format(&ds
, "killed (%s)",
534 signal_name(WTERMSIG(status
), namebuf
, sizeof namebuf
));
535 } else if (WIFSTOPPED(status
)) {
536 char namebuf
[SIGNAL_NAME_BUFSIZE
];
538 ds_put_format(&ds
, "stopped (%s)",
539 signal_name(WSTOPSIG(status
), namebuf
, sizeof namebuf
));
541 ds_put_format(&ds
, "terminated abnormally (%x)", status
);
543 if (WCOREDUMP(status
)) {
544 ds_put_cstr(&ds
, ", core dumped");
547 ds_put_cstr(&ds
, "function not supported.");
552 /* Executes periodic maintenance activities required by the process module. */
557 char buf
[_POSIX_PIPE_BUF
];
559 if (!ovs_list_is_empty(&all_processes
) && read(fds
[0], buf
, sizeof buf
) > 0) {
562 LIST_FOR_EACH (p
, node
, &all_processes
) {
566 retval
= waitpid(p
->pid
, &status
, WNOHANG
);
567 } while (retval
== -1 && errno
== EINTR
);
568 if (retval
== p
->pid
) {
571 } else if (retval
< 0) {
572 VLOG_WARN("waitpid: %s", ovs_strerror(errno
));
583 /* Causes the next call to poll_block() to wake up when process 'p' has
586 process_wait(struct process
*p
)
590 poll_immediate_wake();
592 poll_fd_wait(fds
[0], POLLIN
);
600 process_search_path(const char *name
)
602 char *save_ptr
= NULL
;
606 if (strchr(name
, '/') || !getenv("PATH")) {
607 return stat(name
, &s
) == 0 ? xstrdup(name
) : NULL
;
610 path
= xstrdup(getenv("PATH"));
611 for (dir
= strtok_r(path
, ":", &save_ptr
); dir
;
612 dir
= strtok_r(NULL
, ":", &save_ptr
)) {
613 char *file
= xasprintf("%s/%s", dir
, name
);
614 if (stat(file
, &s
) == 0) {
625 sigchld_handler(int signr OVS_UNUSED
)
627 ignore(write(fds
[1], "", 1));