4 #include <sys/select.h>
8 #include <sys/signalfd.h>
9 #include <sys/resource.h>
14 static int child_count;
15 static int parent_count;
16 static int job_request_fd[2];
17 static int job_get_permission_fd[2];
19 static unsigned int max_jobs;
20 static unsigned int job_count;
21 static unsigned int jobs_pending;
23 int get_child_count(void)
28 int get_parent_count(void)
33 static int handle_signals(struct event_handler *h)
35 struct signalfd_siginfo siginfo;
38 ret = read(h->fd, &siginfo, sizeof(siginfo));
39 if (ret < sizeof(siginfo)) {
40 pr_err("Expected %zd from read, got %d: %m\n",
41 sizeof(siginfo), ret);
45 if (siginfo.ssi_signo != SIGCHLD) {
46 pr_err("Unexpected signal %d, ignoring\n", siginfo.ssi_signo);
50 harvest_zombies(siginfo.ssi_pid);
55 static int grant_new_job(void)
61 pr_info("Granting new job. %d jobs currently and %d pending\n",
62 job_count, jobs_pending);
64 ret = write(job_get_permission_fd[1], &byte, 1);
66 pr_err("Failed to write 1 byte: %m\n");
73 static int handle_job_request(struct event_handler *h)
77 ret = read(job_request_fd[0], &pid, sizeof(pid));
79 pr_err("Failed to read: %m\n");
84 pr_info("Read zero bytes\n");
89 if (job_count >= max_jobs) {
92 ret = grant_new_job();
96 if (job_count > max_jobs)
97 pr_err("BUG: Job %u jobs exceeded limit %u\n",
100 pr_info("Job %d finished\n", -pid);
104 ret = grant_new_job();
112 struct event_handler signal_handler = {
113 .handle_event = handle_signals,
118 struct event_handler job_request_handler = {
119 .handle_event = handle_job_request,
121 .name = "job_request",
125 * Initialize the jobcontrol.
127 * Create the pipes that are used to grant children execution
128 * permissions. If max_jobs is zero, count the number of CPUs from
129 * /proc/cpuinfo and use that.
131 int init_jobcontrol(int max_jobs_requested)
139 if (pipe2(job_request_fd, O_NONBLOCK | O_CLOEXEC)) {
140 pr_err("Failed to create pipe: %m\n");
144 if (pipe2(job_get_permission_fd, O_CLOEXEC)) {
145 pr_err("Failed to create pipe: %m\n");
149 epoll_fd = epoll_create(1);
150 if (epoll_fd == -1) {
151 pr_err("Failed to epoll_create(): %m\n");
155 job_request_handler.fd = job_request_fd[0];
156 register_event_handler(&job_request_handler);
158 sigemptyset(&sigmask);
159 sigaddset(&sigmask, SIGCHLD);
161 /* Block SIGCHLD so that it becomes readable via signalfd */
162 ret = sigprocmask(SIG_BLOCK, &sigmask, NULL);
164 pr_err("Failed to sigprocmask: %m\n");
167 signal_handler.fd = signalfd(-1, &sigmask, SFD_CLOEXEC);
168 if (job_request_handler.fd < 0) {
169 pr_err("Failed to create signal_fd: %m\n");
173 register_event_handler(&signal_handler);
175 if (max_jobs_requested > 0) {
176 max_jobs = max_jobs_requested;
181 file = fopen("/proc/cpuinfo", "ro");
183 pr_err("Failed to open /proc/cpuinfo: %m\n");
188 * The CPU count algorithm simply reads the first 8 bytes from
189 * the /proc/cpuinfo and then expects that line to be there as
190 * many times as there are CPUs.
192 ret = fread(match, 1, sizeof(match), file);
193 if (ret < sizeof(match)) {
194 pr_err("read %d bytes when expecting %zd %m\n",
199 while(fgets(buf, sizeof(buf), file)) {
200 if (!strncmp(buf, match, sizeof(match)))
209 pr_info("Set maximum number of parallel jobs to %d\n", max_jobs);
214 int poll_job_requests(int timeout)
216 struct epoll_event event;
217 struct event_handler *job_handler;
220 /* Convert positive seconds to milliseconds */
221 timeout = timeout > 0 ? 1000 * timeout : timeout;
223 ret = epoll_wait(epoll_fd, &event, 1, timeout);
226 if (errno != EINTR) {
227 pr_err("epoll_wait: %m\n");
232 * If epoll_wait() was interrupted, better start
233 * everything again from the beginning
239 pr_info("Timed out\n");
243 job_handler = event.data.ptr;
245 if (!job_handler || !job_handler->handle_event) {
246 pr_err("Corrupted event handler for fd %d\n",
251 pr_info("Running handler %s to handle events from fd %d\n",
252 job_handler->name, job_handler->fd);
253 job_handler->handle_event(job_handler);
256 pr_info("Jobs active: %u, pending: %u\n", job_count, jobs_pending);
261 * Per process flag indicating whether this child has requested fork
262 * limiting. If it has, it must also tell the master parent when it
263 * has died so that the parent can give next pending job permission to
266 static int is_limited_fork;
273 pr_err("fork() failed: %m\n");
279 pr_info("Fork %d, child %d\n", child_count, child);
284 * Also do not notify the master parent the death of this
285 * child. Only childs that have been created with
286 * do_fork_limited() can have this flag set.
291 * Close unused ends of the job control pipes. Only the parent
292 * which controls the jobs may have the write end open of the
293 * job_get_permission_fd and the read end of the
294 * job_request_fd. Failing to close the pipe ends properly
295 * will cause the childs to wait forever for the run
296 * permission in case parent dies prematurely.
298 * Note! The file descriptor must be closed once and only
299 * once. They are marked to -1 to make it impossible for
300 * subseqent do_fork() calls from closing them again (in which
301 * case some other file descriptor might already be reserved
302 * for the same number) and prevent accidentally closing some
303 * innocent file descriptors that are still in use.
305 if (job_get_permission_fd[1] >= 0) {
306 close(job_get_permission_fd[1]);
307 job_get_permission_fd[1] = -1;
309 if (job_request_fd[0] >= 0) {
310 close(job_request_fd[0]);
311 job_request_fd[0] = -1;
314 /* reset child's child count */
320 static int request_fork(int request)
324 pid = request > 0 ? pid : -pid;
326 return write(job_request_fd[1], &pid, sizeof(pid));
329 static void limited_fork_exit_handler(void)
336 * Like do_fork(), but allow the child continue only after the global
337 * job count is low enough.
339 * We allow the parent to continue other more important activities but
340 * child respects the limit of global active processes.
342 int do_fork_limited(void)
351 /* Remember to notify the parent when we are done */
352 atexit(limited_fork_exit_handler);
355 pr_info("Requesting permission to go\n");
357 /* Signal the parent that we are here, waiting to go */
361 * The parent will tell us when we can continue. If there were
362 * multiple children waiting for their turn to run only one
363 * will be reading the content byte from the pipe and getting
364 * the permission to run.
366 ret = read(job_get_permission_fd[0], &byte, sizeof(byte));
368 pr_err("Error requesting run, did the parent die?\n");
371 pr_err("Job control request failure: %m\n");
373 pr_info("Continuing\n");
377 int harvest_zombies(int pid)
380 struct rusage rusage;
381 char *status_str = NULL;
384 if (child_count == 0)
388 pr_info("Waiting on pid %d, children left: %d\n", pid,
392 pid = wait4(pid, &status, 0, &rusage);
394 pr_err("Error on waitid(): %m\n");
397 /* Wait until the child has become a zombie */
398 } while (!WIFEXITED(status) && !WIFSIGNALED(status));
401 if (WIFEXITED(status)) {
402 status_str = "exited with status";
403 code = WEXITSTATUS(status);
404 } else if (WIFSIGNALED(status)) {
405 status_str = "killed by signal";
406 code = WTERMSIG(status);
408 pr_info("pid %d: %s %d. Children left: %d\n", pid,
409 status_str, code, child_count);
410 pr_info("pid %d: User time: %ld.%03lds, System %ld.%03lds\n", pid,
411 (long)rusage.ru_utime.tv_sec, rusage.ru_utime.tv_usec / 1000,
412 (long)rusage.ru_stime.tv_sec, rusage.ru_stime.tv_usec / 1000);
418 * Runs a command cmd with params argv, connects stdin and stdout to
421 * Returns the pid of the executed process
423 int run_piped(const char *cmd, char *const argv[],
424 int *stdinfd, int *stdoutfd, int *stderrfd)
426 int ifd[2], ofd[2], efd[2], pid;
428 pr_info("Running command %s\n", cmd);
430 if (stdinfd && pipe(ifd)) {
431 pr_err("pipe() failed: %m\n");
435 if (stdoutfd && pipe(ofd)) {
436 pr_err("pipe() failed: %m\n");
440 if (stderrfd && pipe(efd)) {
441 pr_err("pipe() failed: %m\n");
446 if (pid) { /* Parent side */
467 dup2(ifd[0], STDIN_FILENO);
472 dup2(ofd[1], STDOUT_FILENO);
477 dup2(efd[1], STDERR_FILENO);
480 /* Now we have redirected standard streams to parent process */
482 pr_err("Failed to execv command %s: %m\n", cmd);
489 * Runs a command cmd with params argv, connects stdin and stdout to
492 * Returns the pid of the executed process
494 int run_piped_stream(const char *cmd, char *const argv[],
495 FILE **stdinf, FILE **stdoutf, FILE **stderrf)
497 int ifd, ofd, efd, pid;
513 pid = run_piped(cmd, argv, i, o, e);
516 *stdinf = fdopen(ifd, "r");
517 if (*stdinf == NULL) {
518 pr_err("Error opening file stream for fd %d: %m\n",
525 *stdoutf = fdopen(ofd, "r");
526 if (*stdoutf == NULL) {
527 pr_err("Error opening file stream for fd %d: %m\n",
534 *stderrf = fdopen(efd, "r");
535 if (*stderrf == NULL) {
536 pr_err("Error opening file stream for fd %d: %m\n",
546 * Forks a child and executes a command to run on parallel
549 #define max(a,b) (a) < (b) ? (b) : (a)
550 #define BUF_SIZE (128*1024)
551 int run(const char *cmd, char *const argv[])
559 if ((child = do_fork()))
562 child = run_piped(cmd, argv, NULL, &ofd, &efd);
574 maxfd = max(ofd, efd);
575 error = select(maxfd, &rfds, NULL, NULL, NULL);
578 pr_err("Error with select: %m\n");
582 if (FD_ISSET(ofd, &rfds)) {
583 bytes = read(ofd, rbuf, BUF_SIZE);
587 if (FD_ISSET(efd, &rfds)) {
589 bytes = read(efd, rbuf, BUF_SIZE);
593 pr_err("select() returned unknown fd\n");
598 pr_err("read() failed: %m\n");
603 * Workaround: When a process had die and it has only
604 * written to stderr, select() doesn't indicate that
605 * there might be something to read in stderr fd. To
606 * work around this issue, we try to read stderr just
607 * in case in order to ensure everything gets read.
610 bytes = read(efd, rbuf, BUF_SIZE);
620 pr_err("%s: stderr: %s\n",
623 pr_info("%s: stdout: %s\n",
634 harvest_zombies(child);
640 int register_event_handler(struct event_handler *handler)
642 struct epoll_event ev;
645 if (handler->fd <= 0) {
646 pr_err("Invalid file descriptor of %d\n", handler->fd);
650 if (!handler->handle_event) {
651 pr_err("Handler callback missing\n");
655 pr_info("Registering handler for %s, fd %d\n",
656 handler->name, handler->fd);
658 ev.data.fd = handler->fd;
659 ev.data.ptr = handler;
660 ev.events = handler->events;
661 ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, handler->fd, &ev);
663 pr_err("Failed to add epoll_fd: %m\n");