]> git.itanic.dy.fi Git - rrdd/blob - process.c
utils.h: min() max() cleanup
[rrdd] / process.c
1 #include <unistd.h>
2 #include <fcntl.h>
3 #include <sys/select.h>
4 #include <sys/epoll.h>
5 #include <stdio.h>
6 #include <sys/wait.h>
7 #include <sys/signalfd.h>
8 #include <sys/resource.h>
9
10 #include "process.h"
11 #include "debug.h"
12 #include "utils.h"
13
14 static int epoll_fd;
15 static unsigned int max_jobs;
16 static unsigned int max_jobs_pending;
17
18 struct work_struct {
19         const char *name;
20         int (*work_fn)(void *);
21         void *arg;
22         struct work_struct *next;
23 };
24
25 struct work_queue {
26         struct work_struct *work;
27         int length;
28         char *name;
29         struct mutex lock;
30 };
31
32 struct work_queue work_queues[WORK_PRIORITIES_NUM] = {
33         {
34                 .name = "high priority",
35                 .lock = {
36                         .name = "high_prio_queue",
37                         .lock = PTHREAD_MUTEX_INITIALIZER,
38                 },
39         },
40         {
41                 .name = "low priority",
42                 .lock = {
43                         .name = "low_prio_queue",
44                         .lock = PTHREAD_MUTEX_INITIALIZER,
45                 },
46         },
47 };
48
49 struct mutex work_stats_mutex = {
50         .name = "work_stats",
51         .lock = PTHREAD_MUTEX_INITIALIZER,
52 };
53 static int workers_active;
54 static int worker_count;
55
56 static int run_work_on_queue(struct work_queue *queue)
57 {
58         struct work_struct *work;
59
60         mutex_lock(&queue->lock);
61
62         if (!queue->work) {
63                 mutex_unlock(&queue->lock);
64                 return 0;
65         }
66
67         /* Take next work */
68         work = queue->work;
69         queue->work = work->next;
70         queue->length--;
71
72         mutex_unlock(&queue->lock);
73
74         pr_info("Executing work %s from queue %s, %d still pending\n",
75                 work->name, queue->name, queue->length);
76
77         work->work_fn(work->arg);
78         pr_info("Work %s done\n", work->name);
79         free(work);
80
81         return 1;
82 }
83
84 static void *worker_thread(void *arg)
85 {
86         int stop_working = 0;
87         int work_done = 0;
88         char name[16];
89
90         mutex_lock(&work_stats_mutex);
91         snprintf(name, sizeof(name), "worker%d", worker_count);
92         worker_count++;
93         mutex_unlock(&work_stats_mutex);
94
95         pthread_setname_np(pthread_self(), name);
96         pthread_detach(pthread_self());
97
98         pr_info("Worker started\n");
99
100         while (!stop_working) {
101                 while (1) {
102                         int prio;
103
104                         /*
105                          * Execute as much work from the high priority
106                          * queue as possible. Once there are no more
107                          * high prio work left, break out the loop and
108                          * see if we still need this many workers.
109                          */
110                         for (prio = 0; prio < WORK_PRIORITIES_NUM; prio++) {
111                                 work_done =
112                                         run_work_on_queue(&work_queues[prio]);
113                                 if (work_done)
114                                         break;
115                         }
116
117                         if (!work_done || prio != WORK_PRIORITY_HIGH)
118                                 break;
119                 }
120
121                 mutex_lock(&work_stats_mutex);
122                 if (workers_active > max_jobs || !work_done) {
123                         workers_active--;
124                         pr_info("Worker exiting, %d left active\n",
125                                 workers_active);
126                         if (!workers_active)
127                                 worker_count = 0;
128                         stop_working = 1;
129                 }
130                 mutex_unlock(&work_stats_mutex);
131         }
132
133         return NULL;
134 }
135
136 int queue_work(unsigned int priority, char *name,
137         int (work_fn)(void *arg), void *arg)
138 {
139         pthread_t *thread;
140         struct work_queue *queue;
141         struct work_struct *work, *last_work;
142
143         if (priority >= WORK_PRIORITIES_NUM) {
144                 pr_err("Invalid priority: %d\n", priority);
145                 return -EINVAL;
146         }
147
148         work = calloc(sizeof(*work), 1);
149
150         work->name = name;
151         work->work_fn = work_fn;
152         work->arg = arg;
153
154         queue = &work_queues[priority];
155
156         /* Insert new work at the end of the work queue */
157         mutex_lock(&queue->lock);
158
159         last_work = queue->work;
160         while (last_work && last_work->next)
161                 last_work = last_work->next;
162
163         if (!last_work)
164                 queue->work = work;
165         else
166                 last_work->next = work;
167
168         pr_info("Inserted work %s in queue %s, with %d pending items\n",
169                 work->name, queue->name, queue->length);
170         queue->length++;
171         mutex_unlock(&queue->lock);
172
173         mutex_lock(&work_stats_mutex);
174         pr_info("workers_active: %d, priority: %d\n", workers_active, priority);
175         if (priority != WORK_PRIORITY_HIGH && workers_active >= max_jobs) {
176                 mutex_unlock(&work_stats_mutex);
177                 return 0;
178         }
179         workers_active++;
180         mutex_unlock(&work_stats_mutex);
181
182         pr_info("Creating new worker thread\n");
183         /* We need a worker thread, create one */
184         thread = calloc(sizeof(*thread), 1);
185         pthread_create(thread, NULL, worker_thread, NULL);
186
187         free(thread);
188
189         return 0;
190 }
191
192 /*
193  * Initialize the jobcontrol.
194  *
195  * Create the pipes that are used to grant children execution
196  * permissions. If max_jobs is zero, count the number of CPUs from
197  * /proc/cpuinfo and use that.
198  */
199 int init_jobcontrol(int max_jobs_requested)
200 {
201         FILE *file;
202         int ret;
203         char buf[256];
204         char match[8];
205
206         epoll_fd = epoll_create(1);
207         if (epoll_fd == -1) {
208                 pr_err("Failed to epoll_create(): %m\n");
209                 return -1;
210         }
211
212         if (max_jobs_requested > 0) {
213                 max_jobs = max_jobs_requested;
214                 goto no_count_cpus;
215         }
216         max_jobs++;
217
218         file = fopen("/proc/cpuinfo", "ro");
219         if (!file) {
220                 pr_err("Failed to open /proc/cpuinfo: %m\n");
221                 goto open_fail;
222         }
223
224         /*
225          * The CPU count algorithm simply reads the first 8 bytes from
226          * the /proc/cpuinfo and then expects that line to be there as
227          * many times as there are CPUs.
228          */
229         ret = fread(match, 1, sizeof(match), file);
230         if (ret < sizeof(match)) {
231                 pr_err("read %d bytes when expecting %zd %m\n",
232                         ret, sizeof(match));
233                 goto read_fail;
234         }
235
236         while(fgets(buf, sizeof(buf), file)) {
237                 if (!strncmp(buf, match, sizeof(match)))
238                         max_jobs++;
239         }
240
241 open_fail:
242 read_fail:
243         fclose(file);
244
245 no_count_cpus:
246         pr_info("Set maximum number of parallel jobs to %d\n", max_jobs);
247
248         max_jobs_pending = max_jobs * 10 + 25;
249         pr_info("Set maximum number of pending jobs to %d\n", max_jobs_pending);
250
251         return 0;
252 }
253
254 int poll_job_requests(int timeout)
255 {
256         struct epoll_event event;
257         struct event_handler *job_handler;
258         int ret;
259
260         /* Convert positive seconds to milliseconds */
261         timeout = timeout > 0 ? 1000 * timeout : timeout;
262
263         ret = epoll_wait(epoll_fd, &event, 1, timeout);
264
265         if (ret == -1) {
266                 if (errno != EINTR) {
267                         pr_err("epoll_wait: %m\n");
268                         return -1;
269                 }
270
271                 /*
272                  * If epoll_wait() was interrupted, better start
273                  * everything again from the beginning
274                  */
275                 return 0;
276         }
277
278         if (ret == 0) {
279                 pr_info("Timed out\n");
280                 goto out;
281         }
282
283         job_handler = event.data.ptr;
284
285         if (!job_handler || !job_handler->handle_event) {
286                 pr_err("Corrupted event handler for fd %d\n",
287                         event.data.fd);
288                 goto out;
289         }
290
291         pr_debug("Running handler %s to handle events from fd %d\n",
292                 job_handler->name, job_handler->fd);
293         job_handler->handle_event(job_handler);
294
295 out:
296         pr_info("Workers active: %u\n", workers_active);
297         return ret;
298 }
299
300 int do_fork(void)
301 {
302         int child;
303         child = fork();
304         if (child < 0) {
305                 pr_err("fork() failed: %m\n");
306                 return -1;
307         }
308
309         if (child) {
310                 pr_debug("Fork child %d\n", child);
311                 return child;
312         }
313
314         return 0;
315 }
316
317 int clear_zombie(int pid)
318 {
319         int status;
320         struct rusage rusage;
321         char *status_str = NULL;
322         int code = 0;
323
324         if (pid)
325                 pr_debug("Waiting on pid %d\n", pid);
326
327         do {
328                 pid = wait4(pid, &status, 0, &rusage);
329                 if (pid < 0) {
330                         pr_err("Error on waitid(): %m\n");
331                         return 0;
332                 }
333                 /* Wait until the child has become a zombie */
334         } while (!WIFEXITED(status) && !WIFSIGNALED(status));
335
336         if (WIFEXITED(status)) {
337                 status_str = "exited with status";
338                 code = WEXITSTATUS(status);
339         } else if (WIFSIGNALED(status)) {
340                 status_str = "killed by signal";
341                 code = WTERMSIG(status);
342         }
343         pr_debug("pid %d: %s %d.\n", pid,
344                 status_str, code);
345         pr_debug("pid %d: User time: %ld.%03lds, System %ld.%03lds\n", pid,
346                 (long)rusage.ru_utime.tv_sec, rusage.ru_utime.tv_usec / 1000,
347                 (long)rusage.ru_stime.tv_sec, rusage.ru_stime.tv_usec / 1000);
348
349         return 1;
350 }
351
352 /*
353  * Runs a command cmd with params argv, connects stdin and stdout to
354  * readfd and writefd
355  *
356  * Returns the pid of the executed process
357  */
358 int run_piped(const char *cmd, char *const argv[],
359               int *stdinfd, int *stdoutfd, int *stderrfd)
360 {
361         int ifd[2], ofd[2], efd[2], pid;
362
363         pr_info("Running command %s\n", cmd);
364
365         if (stdinfd && pipe(ifd)) {
366                 pr_err("pipe() failed: %m\n");
367                 return -1;
368         }
369
370         if (stdoutfd && pipe(ofd)) {
371                 pr_err("pipe() failed: %m\n");
372                 return -1;
373         }
374
375         if (stderrfd && pipe(efd)) {
376                 pr_err("pipe() failed: %m\n");
377                 return -1;
378         }
379
380         pid = do_fork();
381         if (pid) { /* Parent side */
382                 if (stdinfd) {
383                         close(ifd[0]);
384                         *stdinfd = ifd[0];
385                 }
386
387                 if (stdoutfd) {
388                         close(ofd[1]);
389                         *stdoutfd = ofd[0];
390                 }
391
392                 if (stderrfd) {
393                         close(efd[1]);
394                         *stderrfd = efd[0];
395                 }
396
397                 return pid;
398         }
399
400         if (stdinfd) {
401                 close(ifd[1]);
402                 dup2(ifd[0], STDIN_FILENO);
403         }
404
405         if (stdoutfd) {
406                 close(ofd[0]);
407                 dup2(ofd[1], STDOUT_FILENO);
408         }
409
410         if (stderrfd) {
411                 close(efd[0]);
412                 dup2(efd[1], STDERR_FILENO);
413         }
414
415         /* Now we have redirected standard streams to parent process */
416         execvp(cmd, argv);
417         pr_err("Failed to execv command %s: %m\n", cmd);
418         exit(1);
419
420         return 0;
421 }
422
423 /*
424  * Runs a command cmd with params argv, connects stdin and stdout to
425  * readfd and writefd
426  *
427  * Returns the pid of the executed process
428  */
429 int run_piped_stream(const char *cmd, char *const argv[],
430                      FILE **stdinf, FILE **stdoutf, FILE **stderrf)
431 {
432         int ifd, ofd, efd, pid;
433         int *i, *o, *e;
434
435         if (stdinf)
436                 i = &ifd;
437         else
438                 i = 0;
439         if (stdoutf)
440                 o = &ofd;
441         else
442                 o = 0;
443         if (stderrf)
444                 e = &efd;
445         else
446                 e = 0;
447
448         pid = run_piped(cmd, argv, i, o, e);
449
450         if (stdinf) {
451                 *stdinf = fdopen(ifd, "r");
452                 if (*stdinf == NULL) {
453                         pr_err("Error opening file stream for fd %d: %m\n",
454                                ifd);
455                         return -1;
456                 }
457         }
458
459         if (stdoutf) {
460                 *stdoutf = fdopen(ofd, "r");
461                 if (*stdoutf == NULL) {
462                         pr_err("Error opening file stream for fd %d: %m\n",
463                                ofd);
464                         return -1;
465                 }
466         }
467
468         if (stderrf) {
469                 *stderrf = fdopen(efd, "r");
470                 if (*stderrf == NULL) {
471                         pr_err("Error opening file stream for fd %d: %m\n",
472                                efd);
473                         return -1;
474                 }
475         }
476
477         return pid;
478 }
479
480 /*
481  * Forks a child and executes a command to run on parallel
482  */
483
484 #define BUF_SIZE (128*1024)
485 int run(const char *cmd, char *const argv[])
486 {
487         int child, error;
488         int ofd, efd;
489         fd_set rfds;
490         int maxfd;
491         int eof = 0;
492
493         child = run_piped(cmd, argv, NULL, &ofd, &efd);
494
495         FD_ZERO(&rfds);
496         FD_SET(ofd, &rfds);
497         FD_SET(efd, &rfds);
498
499         while (!eof) {
500                 char *sptr , *eptr;
501                 char rbuf[BUF_SIZE];
502                 int bytes;
503                 int is_stderr = 0;
504
505                 maxfd = max(ofd, efd);
506                 error = select(maxfd, &rfds, NULL, NULL, NULL);
507
508                 if (error < 0) {
509                         pr_err("Error with select: %m\n");
510                         break;
511                 }
512
513                 if (FD_ISSET(ofd, &rfds)) {
514                         bytes = read(ofd, rbuf, BUF_SIZE);
515                         goto print;
516                 }
517
518                 if (FD_ISSET(efd, &rfds)) {
519                         is_stderr = 1;
520                         bytes = read(efd, rbuf, BUF_SIZE);
521                         goto print;
522                 }
523
524                 pr_err("select() returned unknown fd\n");
525                 break;
526
527 print:
528                 if (bytes < 0) {
529                         pr_err("read() failed: %m\n");
530                         break;
531                 }
532
533                 /*
534                  * Workaround: When a process had die and it has only
535                  * written to stderr, select() doesn't indicate that
536                  * there might be something to read in stderr fd. To
537                  * work around this issue, we try to read stderr just
538                  * in case in order to ensure everything gets read.
539                  */
540                 if (bytes == 0) {
541                         bytes = read(efd, rbuf, BUF_SIZE);
542                         is_stderr = 1;
543                         eof = 1;
544                 }
545
546                 sptr = eptr = rbuf;
547                 while (bytes--) {
548                         if (*eptr == '\n') {
549                                 *eptr = 0;
550                                 if (is_stderr)
551                                         pr_err("%s: stderr: %s\n",
552                                                 cmd, sptr);
553                                 else
554                                         pr_info("%s: stdout: %s\n",
555                                                 cmd, sptr);
556                                 sptr = eptr + 1;
557                         }
558                         eptr++;
559                 }
560         }
561
562         close(ofd);
563         close(efd);
564
565         clear_zombie(child);
566
567         return 0;
568 }
569
570 int register_event_handler(struct event_handler *handler)
571 {
572         struct epoll_event ev;
573         int ret;
574
575         if (handler->fd <= 0) {
576                 pr_err("Invalid file descriptor of %d\n", handler->fd);
577                 return -1;
578         }
579
580         if (!handler->handle_event) {
581                 pr_err("Handler callback missing\n");
582                 return -1;
583         }
584
585         pr_info("Registering handler for %s, fd %d\n",
586                 handler->name, handler->fd);
587
588         ev.data.fd = handler->fd;
589         ev.data.ptr = handler;
590         ev.events = handler->events;
591         ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, handler->fd, &ev);
592         if (ret) {
593                 pr_err("Failed to add epoll_fd: %m\n");
594                 return -1;
595         }
596
597         return 0;
598 }
599
600 void _mutex_lock_acquired(struct mutex *lock, char *file, int line)
601 {
602         lock->line = line;
603         lock->file = file;
604 }
605
606 int _mutex_lock(struct mutex *lock, char *file, int line)
607 {
608         int ret = 0;
609
610         if (!pthread_mutex_trylock(&lock->lock))
611                 goto out_lock;
612
613         pr_info("Lock contention on lock %s on %s:%d\n",
614                 lock->name, lock->file, lock->line);
615
616         ret = pthread_mutex_lock(&lock->lock);
617         if (ret)
618                 pr_err("Acquirin lock %s failed: %m, acquired %s:%d\n",
619                         lock->name, lock->file, lock->line);
620
621 out_lock:
622         _mutex_lock_acquired(lock, file, line);
623         return ret;
624 }
625
626 int _mutex_unlock(struct mutex *lock)
627 {
628         lock->line = 0;
629         lock->file = NULL;
630         pthread_mutex_unlock(&lock->lock);
631
632         return 0;
633 }