]> arthur.barton.de Git - netdata.git/blob - src/apps_plugin.c
support for space in apps_groups.conf using a backslash as escape
[netdata.git] / src / apps_plugin.c
1 // TODO
2 //
3 // 1. disable RESET_OR_OVERFLOW check in charts
4
5 #ifdef HAVE_CONFIG_H
6 #include <config.h>
7 #endif
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <time.h>
12 #include <unistd.h>
13 #include <sys/types.h>
14 #include <sys/time.h>
15 #include <sys/wait.h>
16
17 #include <sys/resource.h>
18 #include <sys/stat.h>
19
20 #include <errno.h>
21 #include <stdarg.h>
22 #include <locale.h>
23 #include <ctype.h>
24 #include <fcntl.h>
25
26 #include <malloc.h>
27 #include <dirent.h>
28 #include <arpa/inet.h>
29
30 #include "common.h"
31 #include "log.h"
32 #include "avl.h"
33 #include "procfile.h"
34
35 #define MAX_COMPARE_NAME 15
36 #define MAX_NAME 100
37
38 unsigned long long Hertz = 1;
39
40 long processors = 1;
41 long pid_max = 32768;
42 int debug = 0;
43
44 int update_every = 1;
45 unsigned long long file_counter = 0;
46
47 char *host_prefix = "";
48
49 // ----------------------------------------------------------------------------
50 // memory debugger
51
52 struct allocations {
53         size_t allocations;
54         size_t allocated;
55         size_t allocated_max;
56 } allocations = { 0, 0, 0 };
57
58 #define MALLOC_MARK (uint32_t)(0x0BADCAFE)
59 #define MALLOC_PREFIX (sizeof(uint32_t) * 2)
60 #define MALLOC_SUFFIX (sizeof(uint32_t))
61 #define MALLOC_OVERHEAD (MALLOC_PREFIX + MALLOC_SUFFIX)
62
63 void *mark_allocation(void *allocated_ptr, size_t size_without_overheads) {
64         uint32_t *real_ptr = (uint32_t *)allocated_ptr;
65         real_ptr[0] = MALLOC_MARK;
66         real_ptr[1] = (uint32_t) size_without_overheads;
67
68         uint32_t *end_ptr = (uint32_t *)(allocated_ptr + MALLOC_PREFIX + size_without_overheads);
69         end_ptr[0] = MALLOC_MARK;
70
71         // fprintf(stderr, "MEMORY_POINTER: Allocated at %p, returning %p.\n", allocated_ptr, (void *)(allocated_ptr + MALLOC_PREFIX));
72
73         return allocated_ptr + MALLOC_PREFIX;
74 }
75
76 void *check_allocation(const char *file, int line, const char *function, void *marked_ptr, size_t *size_without_overheads_ptr) {
77         uint32_t *real_ptr = (uint32_t *)(marked_ptr - MALLOC_PREFIX);
78
79         // fprintf(stderr, "MEMORY_POINTER: Checking pointer at %p, real %p for %s/%u@%s.\n", marked_ptr, (void *)(marked_ptr - MALLOC_PREFIX), function, line, file);
80
81         if(real_ptr[0] != MALLOC_MARK) fatal("MEMORY: prefix MARK is not valid for %s/%u@%s.", function, line, file);
82
83         size_t size = real_ptr[1];
84
85         uint32_t *end_ptr = (uint32_t *)(marked_ptr + size);
86         if(end_ptr[0] != MALLOC_MARK) fatal("MEMORY: suffix MARK of allocation with size %zu is not valid for %s/%u@%s.", size, function, line, file);
87
88         if(size_without_overheads_ptr) *size_without_overheads_ptr = size;
89
90         return real_ptr;
91 }
92
93 void *malloc_debug(const char *file, int line, const char *function, size_t size) {
94         void *ptr = malloc(size + MALLOC_OVERHEAD);
95         if(!ptr) fatal("MEMORY: Cannot allocate %zu bytes for %s/%u@%s.", size, function, line, file);
96
97         allocations.allocated += size;
98         allocations.allocations++;
99
100         debug(D_MEMORY, "MEMORY: Allocated %zu bytes for %s/%u@%s."
101                 " Status: allocated %zu in %zu allocs."
102                 , size
103                 , function, line, file
104                 , allocations.allocated
105                 , allocations.allocations
106         );
107
108         if(allocations.allocated > allocations.allocated_max) {
109                 debug(D_MEMORY, "MEMORY: total allocation peak increased from %zu to %zu", allocations.allocated_max, allocations.allocated);
110                 allocations.allocated_max = allocations.allocated;
111         }
112
113         size_t csize;
114         check_allocation(file, line, function, mark_allocation(ptr, size), &csize);
115         if(size != csize) {
116                 fatal("Invalid size.");
117         }
118
119         return mark_allocation(ptr, size);
120 }
121
122 void *calloc_debug(const char *file, int line, const char *function, size_t nmemb, size_t size) {
123         void *ptr = malloc_debug(file, line, function, (nmemb * size));
124         bzero(ptr, nmemb * size);
125         return ptr;
126 }
127
128 void free_debug(const char *file, int line, const char *function, void *ptr) {
129         size_t size;
130         void *real_ptr = check_allocation(file, line, function, ptr, &size);
131
132         bzero(real_ptr, size + MALLOC_OVERHEAD);
133
134         free(real_ptr);
135         allocations.allocated -= size;
136         allocations.allocations--;
137
138         debug(D_MEMORY, "MEMORY: freed %zu bytes for %s/%u@%s."
139                 " Status: allocated %zu in %zu allocs."
140                 , size
141                 , function, line, file
142                 , allocations.allocated
143                 , allocations.allocations
144         );
145 }
146
147 void *realloc_debug(const char *file, int line, const char *function, void *ptr, size_t size) {
148         if(!ptr) return malloc_debug(file, line, function, size);
149         if(!size) { free_debug(file, line, function, ptr); return NULL; }
150
151         size_t old_size;
152         void *real_ptr = check_allocation(file, line, function, ptr, &old_size);
153
154         void *new_ptr = realloc(real_ptr, size + MALLOC_OVERHEAD);
155         if(!new_ptr) fatal("MEMORY: Cannot allocate %zu bytes for %s/%u@%s.", size, function, line, file);
156
157         allocations.allocated += size;
158         allocations.allocated -= old_size;
159
160         debug(D_MEMORY, "MEMORY: Re-allocated from %zu to %zu bytes for %s/%u@%s."
161                 " Status: allocated %z in %zu allocs."
162                 , old_size, size
163                 , function, line, file
164                 , allocations.allocated
165                 , allocations.allocations
166         );
167
168         if(allocations.allocated > allocations.allocated_max) {
169                 debug(D_MEMORY, "MEMORY: total allocation peak increased from %zu to %zu", allocations.allocated_max, allocations.allocated);
170                 allocations.allocated_max = allocations.allocated;
171         }
172
173         return mark_allocation(new_ptr, size);
174 }
175
176 char *strdup_debug(const char *file, int line, const char *function, const char *ptr) {
177         size_t size = 0;
178         const char *s = ptr;
179
180         while(*s++) size++;
181         size++;
182
183         char *p = malloc_debug(file, line, function, size);
184         if(!p) fatal("Cannot allocate %zu bytes.", size);
185
186         memcpy(p, ptr, size);
187         return p;
188 }
189
190 #define malloc(size) malloc_debug(__FILE__, __LINE__, __FUNCTION__, (size))
191 #define calloc(nmemb, size) calloc_debug(__FILE__, __LINE__, __FUNCTION__, (nmemb), (size))
192 #define realloc(ptr, size) realloc_debug(__FILE__, __LINE__, __FUNCTION__, (ptr), (size))
193 #define free(ptr) free_debug(__FILE__, __LINE__, __FUNCTION__, (ptr))
194
195 #ifdef strdup
196 #undef strdup
197 #endif
198 #define strdup(ptr) strdup_debug(__FILE__, __LINE__, __FUNCTION__, (ptr))
199
200 // ----------------------------------------------------------------------------
201 // helper functions
202
203 procfile *ff = NULL;
204
205 long get_processors(void) {
206         int processors = 0;
207
208         char filename[FILENAME_MAX + 1];
209         snprintf(filename, FILENAME_MAX, "%s/proc/stat", host_prefix);
210
211         ff = procfile_reopen(ff, filename, "", PROCFILE_FLAG_DEFAULT);
212         if(!ff) return 1;
213
214         ff = procfile_readall(ff);
215         if(!ff) {
216                 // procfile_close(ff);
217                 return 1;
218         }
219
220         unsigned int i;
221         for(i = 0; i < procfile_lines(ff); i++) {
222                 if(!procfile_linewords(ff, i)) continue;
223
224                 if(strncmp(procfile_lineword(ff, i, 0), "cpu", 3) == 0) processors++;
225         }
226         processors--;
227         if(processors < 1) processors = 1;
228
229         // procfile_close(ff);
230         return processors;
231 }
232
233 long get_pid_max(void) {
234         long mpid = 32768;
235
236         char filename[FILENAME_MAX + 1];
237         snprintf(filename, FILENAME_MAX, "%s/proc/sys/kernel/pid_max", host_prefix);
238         ff = procfile_reopen(ff, filename, "", PROCFILE_FLAG_DEFAULT);
239         if(!ff) return mpid;
240
241         ff = procfile_readall(ff);
242         if(!ff) {
243                 // procfile_close(ff);
244                 return mpid;
245         }
246
247         mpid = atol(procfile_lineword(ff, 0, 0));
248         if(!mpid) mpid = 32768;
249
250         // procfile_close(ff);
251         return mpid;
252 }
253
254 unsigned long long get_hertz(void)
255 {
256         unsigned long long myhz = 1;
257
258 #ifdef _SC_CLK_TCK
259         if((myhz = (unsigned long long int) sysconf(_SC_CLK_TCK)) > 0) {
260                 return myhz;
261         }
262 #endif
263
264 #ifdef HZ
265         myhz = HZ;    /* <asm/param.h> */
266 #else
267         /* If 32-bit or big-endian (not Alpha or ia64), assume HZ is 100. */
268         hz = (sizeof(long)==sizeof(int) || htons(999)==999) ? 100UL : 1024UL;
269 #endif
270
271         error("Unknown HZ value. Assuming %llu.", myhz);
272         return myhz;
273 }
274
275
276 // ----------------------------------------------------------------------------
277 // target
278 // target is the point to aggregate a process tree values
279
280 struct target {
281         char compare[MAX_COMPARE_NAME + 1];
282         char id[MAX_NAME + 1];
283         char name[MAX_NAME + 1];
284
285         unsigned long long minflt;
286         unsigned long long cminflt;
287         unsigned long long majflt;
288         unsigned long long cmajflt;
289         unsigned long long utime;
290         unsigned long long stime;
291         unsigned long long cutime;
292         unsigned long long cstime;
293         unsigned long long num_threads;
294         unsigned long long rss;
295
296         unsigned long long fix_minflt;
297         unsigned long long fix_cminflt;
298         unsigned long long fix_majflt;
299         unsigned long long fix_cmajflt;
300         unsigned long long fix_utime;
301         unsigned long long fix_stime;
302         unsigned long long fix_cutime;
303         unsigned long long fix_cstime;
304
305         unsigned long long statm_size;
306         unsigned long long statm_resident;
307         unsigned long long statm_share;
308         unsigned long long statm_text;
309         unsigned long long statm_lib;
310         unsigned long long statm_data;
311         unsigned long long statm_dirty;
312
313         unsigned long long io_logical_bytes_read;
314         unsigned long long io_logical_bytes_written;
315         unsigned long long io_read_calls;
316         unsigned long long io_write_calls;
317         unsigned long long io_storage_bytes_read;
318         unsigned long long io_storage_bytes_written;
319         unsigned long long io_cancelled_write_bytes;
320
321         unsigned long long fix_io_logical_bytes_read;
322         unsigned long long fix_io_logical_bytes_written;
323         unsigned long long fix_io_read_calls;
324         unsigned long long fix_io_write_calls;
325         unsigned long long fix_io_storage_bytes_read;
326         unsigned long long fix_io_storage_bytes_written;
327         unsigned long long fix_io_cancelled_write_bytes;
328
329         int *fds;
330         unsigned long long openfiles;
331         unsigned long long openpipes;
332         unsigned long long opensockets;
333         unsigned long long openinotifies;
334         unsigned long long openeventfds;
335         unsigned long long opentimerfds;
336         unsigned long long opensignalfds;
337         unsigned long long openeventpolls;
338         unsigned long long openother;
339
340         unsigned long processes;        // how many processes have been merged to this
341         int exposed;                            // if set, we have sent this to netdata
342         int hidden;                                     // if set, we set the hidden flag on the dimension
343         int debug;
344
345         struct target *target;  // the one that will be reported to netdata
346         struct target *next;
347 } *target_root = NULL, *default_target = NULL;
348
349 long targets = 0;
350
351 // find or create a target
352 // there are targets that are just agregated to other target (the second argument)
353 struct target *get_target(const char *id, struct target *target)
354 {
355         const char *nid = id;
356         if(nid[0] == '-') nid++;
357
358         struct target *w;
359         for(w = target_root ; w ; w = w->next)
360                 if(strncmp(nid, w->id, MAX_NAME) == 0) return w;
361
362         w = calloc(sizeof(struct target), 1);
363         if(!w) {
364                 error("Cannot allocate %lu bytes of memory", (unsigned long)sizeof(struct target));
365                 return NULL;
366         }
367
368         strncpy(w->id, nid, MAX_NAME);
369         strncpy(w->name, nid, MAX_NAME);
370         strncpy(w->compare, nid, MAX_COMPARE_NAME);
371         if(id[0] == '-') w->hidden = 1;
372
373         w->target = target;
374
375         w->next = target_root;
376         target_root = w;
377
378         if(debug) fprintf(stderr, "apps.plugin: adding hook for process '%s', compare '%s' on target '%s'\n", w->id, w->compare, w->target?w->target->id:"");
379
380         return w;
381 }
382
383 // read the process groups file
384 int read_process_groups(const char *name)
385 {
386         char buffer[4096+1];
387         char filename[FILENAME_MAX + 1];
388
389         snprintf(filename, FILENAME_MAX, "%s/apps_%s.conf", CONFIG_DIR, name);
390
391         if(debug) fprintf(stderr, "apps.plugin: process groups file: '%s'\n", filename);
392         FILE *fp = fopen(filename, "r");
393         if(!fp) {
394                 error("Cannot open file '%s'", filename);
395                 return 1;
396         }
397
398         long line = 0;
399         while(fgets(buffer, 4096, fp) != NULL) {
400                 int whidden = 0, wdebug = 0;
401                 line++;
402
403                 // if(debug) fprintf(stderr, "apps.plugin: \tread %s\n", buffer);
404
405                 char *s = buffer, *t, *p;
406                 s = trim(s);
407                 if(!s || !*s || *s == '#') continue;
408
409                 if(debug) fprintf(stderr, "apps.plugin: \tread %s\n", s);
410
411                 // the target name
412                 t = strsep(&s, ":");
413                 if(t) t = trim(t);
414                 if(!t || !*t) continue;
415
416                 while(t[0]) {
417                         int stop = 1;
418
419                         switch(t[0]) {
420                                 case '-':
421                                         stop = 0;
422                                         whidden = 1;
423                                         t++;
424                                         break;
425
426                                 case '+':
427                                         stop = 0;
428                                         wdebug = 1;
429                                         t++;
430                                         break;
431                         }
432
433                         if(stop) break;
434                 }
435
436                 if(debug) fprintf(stderr, "apps.plugin: \t\ttarget %s\n", t);
437
438                 struct target *w = NULL;
439                 long count = 0;
440                 int blen = 0;
441                 char buffer[4097] = "";
442                 buffer[4096] = '\0';
443
444                 // the process names
445                 while((p = strsep(&s, " "))) {
446                         p = trim(p);
447                         if(!p || !*p) continue;
448
449                         strncpy(&buffer[blen], p, 4096 - blen);
450                         blen = strlen(buffer);
451
452                         while(buffer[blen - 1] == '\\') {
453                                 buffer[blen - 1] = ' ';
454
455                                 if((p = strsep(&s, " ")))
456                                         p = trim(p);
457
458                                 if(!p || !*p) p = " ";
459                                 strncpy(&buffer[blen], p, 4096 - blen);
460                                 blen = strlen(buffer);
461                         }
462
463                         struct target *n = get_target(buffer, w);
464                         n->hidden = whidden;
465                         n->debug = wdebug;
466                         if(!w) w = n;
467
468                         buffer[0] = '\0';
469                         blen = 0;
470
471                         count++;
472                 }
473
474                 if(w) strncpy(w->name, t, MAX_NAME);
475                 if(!count) error("The line %ld on file '%s', for group '%s' does not state any process names.", line, filename, t);
476         }
477         fclose(fp);
478
479         default_target = get_target("+p!o@w#e$i^r&7*5(-i)l-o_", NULL); // match nothing
480         strncpy(default_target->name, "other", MAX_NAME);
481
482         return 0;
483 }
484
485
486 // ----------------------------------------------------------------------------
487 // data to store for each pid
488 // see: man proc
489
490 struct pid_stat {
491         int32_t pid;
492         char comm[MAX_COMPARE_NAME + 1];
493         // char state;
494         int32_t ppid;
495         // int32_t pgrp;
496         // int32_t session;
497         // int32_t tty_nr;
498         // int32_t tpgid;
499         // uint64_t flags;
500         unsigned long long minflt;
501         unsigned long long cminflt;
502         unsigned long long majflt;
503         unsigned long long cmajflt;
504         unsigned long long utime;
505         unsigned long long stime;
506         unsigned long long cutime;
507         unsigned long long cstime;
508         // int64_t priority;
509         // int64_t nice;
510         int32_t num_threads;
511         // int64_t itrealvalue;
512         // unsigned long long starttime;
513         // unsigned long long vsize;
514         unsigned long long rss;
515         // unsigned long long rsslim;
516         // unsigned long long starcode;
517         // unsigned long long endcode;
518         // unsigned long long startstack;
519         // unsigned long long kstkesp;
520         // unsigned long long kstkeip;
521         // uint64_t signal;
522         // uint64_t blocked;
523         // uint64_t sigignore;
524         // uint64_t sigcatch;
525         // uint64_t wchan;
526         // uint64_t nswap;
527         // uint64_t cnswap;
528         // int32_t exit_signal;
529         // int32_t processor;
530         // uint32_t rt_priority;
531         // uint32_t policy;
532         // unsigned long long delayacct_blkio_ticks;
533         // uint64_t guest_time;
534         // int64_t cguest_time;
535
536         unsigned long long statm_size;
537         unsigned long long statm_resident;
538         unsigned long long statm_share;
539         unsigned long long statm_text;
540         unsigned long long statm_lib;
541         unsigned long long statm_data;
542         unsigned long long statm_dirty;
543
544         unsigned long long io_logical_bytes_read;
545         unsigned long long io_logical_bytes_written;
546         unsigned long long io_read_calls;
547         unsigned long long io_write_calls;
548         unsigned long long io_storage_bytes_read;
549         unsigned long long io_storage_bytes_written;
550         unsigned long long io_cancelled_write_bytes;
551
552 #ifdef INCLUDE_CHILDS
553         unsigned long long old_utime;
554         unsigned long long old_stime;
555         unsigned long long old_minflt;
556         unsigned long long old_majflt;
557
558         unsigned long long old_cutime;
559         unsigned long long old_cstime;
560         unsigned long long old_cminflt;
561         unsigned long long old_cmajflt;
562
563         unsigned long long fix_cutime;
564         unsigned long long fix_cstime;
565         unsigned long long fix_cminflt;
566         unsigned long long fix_cmajflt;
567
568         unsigned long long diff_cutime;
569         unsigned long long diff_cstime;
570         unsigned long long diff_cminflt;
571         unsigned long long diff_cmajflt;
572 #endif
573
574         int *fds;                                       // array of fds it uses
575         int fds_size;                           // the size of the fds array
576
577         int childs;                                     // number of processes directly referencing this
578         int updated;                            // 1 when update
579         int merged;                                     // 1 when it has been merged to its parent
580         int new_entry;
581         struct target *target;
582         struct pid_stat *parent;
583         struct pid_stat *prev;
584         struct pid_stat *next;
585 } *root_of_pids = NULL, **all_pids;
586
587 long all_pids_count = 0;
588
589 struct pid_stat *get_pid_entry(pid_t pid)
590 {
591         if(all_pids[pid]) {
592                 all_pids[pid]->new_entry = 0;
593                 return all_pids[pid];
594         }
595
596         all_pids[pid] = calloc(sizeof(struct pid_stat), 1);
597         if(!all_pids[pid]) {
598                 error("Cannot allocate %lu bytes of memory", (unsigned long)sizeof(struct pid_stat));
599                 return NULL;
600         }
601
602         all_pids[pid]->fds = calloc(sizeof(int), 100);
603         if(!all_pids[pid]->fds)
604                 error("Cannot allocate %ld bytes of memory", (unsigned long)(sizeof(int) * 100));
605         else all_pids[pid]->fds_size = 100;
606
607         if(root_of_pids) root_of_pids->prev = all_pids[pid];
608         all_pids[pid]->next = root_of_pids;
609         root_of_pids = all_pids[pid];
610
611         all_pids[pid]->pid = pid;
612         all_pids[pid]->new_entry = 1;
613
614         return all_pids[pid];
615 }
616
617 void del_pid_entry(pid_t pid)
618 {
619         if(!all_pids[pid]) return;
620
621         if(debug) fprintf(stderr, "apps.plugin: process %d %s exited, deleting it.\n", pid, all_pids[pid]->comm);
622
623         if(root_of_pids == all_pids[pid]) root_of_pids = all_pids[pid]->next;
624         if(all_pids[pid]->next) all_pids[pid]->next->prev = all_pids[pid]->prev;
625         if(all_pids[pid]->prev) all_pids[pid]->prev->next = all_pids[pid]->next;
626
627         if(all_pids[pid]->fds) free(all_pids[pid]->fds);
628         free(all_pids[pid]);
629         all_pids[pid] = NULL;
630 }
631
632
633 // ----------------------------------------------------------------------------
634 // update pids from proc
635
636 int read_proc_pid_stat(struct pid_stat *p) {
637         char filename[FILENAME_MAX + 1];
638
639         snprintf(filename, FILENAME_MAX, "%s/proc/%d/stat", host_prefix, p->pid);
640
641         ff = procfile_reopen(ff, filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
642         if(!ff) return 1;
643
644         ff = procfile_readall(ff);
645         if(!ff) {
646                 // procfile_close(ff);
647                 return 1;
648         }
649
650         file_counter++;
651
652         p->comm[0] = '\0';
653         p->comm[MAX_COMPARE_NAME] = '\0';
654         size_t blen = 0;
655
656         char *s = procfile_lineword(ff, 0, 1);
657         if(*s == '(') s++;
658         size_t len = strlen(s);
659         unsigned int i = 0;
660         while(len && s[len - 1] != ')') {
661                 if(blen < MAX_COMPARE_NAME) {
662                         strncpy(&p->comm[blen], s, MAX_COMPARE_NAME - blen);
663                         blen = strlen(p->comm);
664                 }
665
666                 i++;
667                 s = procfile_lineword(ff, 0, 1+i);
668                 len = strlen(s);
669         }
670         if(len && s[len - 1] == ')') s[len - 1] = '\0';
671         if(blen < MAX_COMPARE_NAME)
672                 strncpy(&p->comm[blen], s, MAX_COMPARE_NAME - blen);
673
674         // p->pid                       = atol(procfile_lineword(ff, 0, 0+i));
675         // comm is at 1
676         // p->state                     = *(procfile_lineword(ff, 0, 2+i));
677         p->ppid                         = (int32_t) atol(procfile_lineword(ff, 0, 3 + i));
678         // p->pgrp                      = atol(procfile_lineword(ff, 0, 4+i));
679         // p->session           = atol(procfile_lineword(ff, 0, 5+i));
680         // p->tty_nr            = atol(procfile_lineword(ff, 0, 6+i));
681         // p->tpgid                     = atol(procfile_lineword(ff, 0, 7+i));
682         // p->flags                     = strtoull(procfile_lineword(ff, 0, 8+i), NULL, 10);
683         p->minflt                       = strtoull(procfile_lineword(ff, 0, 9+i), NULL, 10);
684         p->cminflt                      = strtoull(procfile_lineword(ff, 0, 10+i), NULL, 10);
685         p->majflt                       = strtoull(procfile_lineword(ff, 0, 11+i), NULL, 10);
686         p->cmajflt                      = strtoull(procfile_lineword(ff, 0, 12+i), NULL, 10);
687         p->utime                        = strtoull(procfile_lineword(ff, 0, 13+i), NULL, 10);
688         p->stime                        = strtoull(procfile_lineword(ff, 0, 14+i), NULL, 10);
689         p->cutime                       = strtoull(procfile_lineword(ff, 0, 15+i), NULL, 10);
690         p->cstime                       = strtoull(procfile_lineword(ff, 0, 16+i), NULL, 10);
691         // p->priority          = strtoull(procfile_lineword(ff, 0, 17+i), NULL, 10);
692         // p->nice                      = strtoull(procfile_lineword(ff, 0, 18+i), NULL, 10);
693         p->num_threads          = (int32_t) atol(procfile_lineword(ff, 0, 19 + i));
694         // p->itrealvalue       = strtoull(procfile_lineword(ff, 0, 20+i), NULL, 10);
695         // p->starttime         = strtoull(procfile_lineword(ff, 0, 21+i), NULL, 10);
696         // p->vsize                     = strtoull(procfile_lineword(ff, 0, 22+i), NULL, 10);
697         p->rss                          = strtoull(procfile_lineword(ff, 0, 23+i), NULL, 10);
698         // p->rsslim            = strtoull(procfile_lineword(ff, 0, 24+i), NULL, 10);
699         // p->starcode          = strtoull(procfile_lineword(ff, 0, 25+i), NULL, 10);
700         // p->endcode           = strtoull(procfile_lineword(ff, 0, 26+i), NULL, 10);
701         // p->startstack        = strtoull(procfile_lineword(ff, 0, 27+i), NULL, 10);
702         // p->kstkesp           = strtoull(procfile_lineword(ff, 0, 28+i), NULL, 10);
703         // p->kstkeip           = strtoull(procfile_lineword(ff, 0, 29+i), NULL, 10);
704         // p->signal            = strtoull(procfile_lineword(ff, 0, 30+i), NULL, 10);
705         // p->blocked           = strtoull(procfile_lineword(ff, 0, 31+i), NULL, 10);
706         // p->sigignore         = strtoull(procfile_lineword(ff, 0, 32+i), NULL, 10);
707         // p->sigcatch          = strtoull(procfile_lineword(ff, 0, 33+i), NULL, 10);
708         // p->wchan                     = strtoull(procfile_lineword(ff, 0, 34+i), NULL, 10);
709         // p->nswap                     = strtoull(procfile_lineword(ff, 0, 35+i), NULL, 10);
710         // p->cnswap            = strtoull(procfile_lineword(ff, 0, 36+i), NULL, 10);
711         // p->exit_signal       = atol(procfile_lineword(ff, 0, 37+i));
712         // p->processor         = atol(procfile_lineword(ff, 0, 38+i));
713         // p->rt_priority       = strtoul(procfile_lineword(ff, 0, 39+i), NULL, 10);
714         // p->policy            = strtoul(procfile_lineword(ff, 0, 40+i), NULL, 10);
715         // p->delayacct_blkio_ticks             = strtoull(procfile_lineword(ff, 0, 41+i), NULL, 10);
716         // p->guest_time        = strtoull(procfile_lineword(ff, 0, 42+i), NULL, 10);
717         // p->cguest_time       = strtoull(procfile_lineword(ff, 0, 43), NULL, 10);
718
719         if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: VALUES: %s utime=%llu, stime=%llu, cutime=%llu, cstime=%llu, minflt=%llu, majflt=%llu, cminflt=%llu, cmajflt=%llu, threads=%d\n", p->comm, p->utime, p->stime, p->cutime, p->cstime, p->minflt, p->majflt, p->cminflt, p->cmajflt, p->num_threads);
720
721         // procfile_close(ff);
722         return 0;
723 }
724
725 int read_proc_pid_statm(struct pid_stat *p) {
726         char filename[FILENAME_MAX + 1];
727
728         snprintf(filename, FILENAME_MAX, "%s/proc/%d/statm", host_prefix, p->pid);
729
730         ff = procfile_reopen(ff, filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
731         if(!ff) return 1;
732
733         ff = procfile_readall(ff);
734         if(!ff) {
735                 // procfile_close(ff);
736                 return 1;
737         }
738
739         file_counter++;
740
741         p->statm_size                   = strtoull(procfile_lineword(ff, 0, 0), NULL, 10);
742         p->statm_resident               = strtoull(procfile_lineword(ff, 0, 1), NULL, 10);
743         p->statm_share                  = strtoull(procfile_lineword(ff, 0, 2), NULL, 10);
744         p->statm_text                   = strtoull(procfile_lineword(ff, 0, 3), NULL, 10);
745         p->statm_lib                    = strtoull(procfile_lineword(ff, 0, 4), NULL, 10);
746         p->statm_data                   = strtoull(procfile_lineword(ff, 0, 5), NULL, 10);
747         p->statm_dirty                  = strtoull(procfile_lineword(ff, 0, 6), NULL, 10);
748
749         // procfile_close(ff);
750         return 0;
751 }
752
753 int read_proc_pid_io(struct pid_stat *p) {
754         char filename[FILENAME_MAX + 1];
755
756         snprintf(filename, FILENAME_MAX, "%s/proc/%d/io", host_prefix, p->pid);
757
758         ff = procfile_reopen(ff, filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
759         if(!ff) return 1;
760
761         ff = procfile_readall(ff);
762         if(!ff) {
763                 // procfile_close(ff);
764                 return 1;
765         }
766
767         file_counter++;
768
769         p->io_logical_bytes_read                = strtoull(procfile_lineword(ff, 0, 1), NULL, 10);
770         p->io_logical_bytes_written     = strtoull(procfile_lineword(ff, 1, 1), NULL, 10);
771         p->io_read_calls                                = strtoull(procfile_lineword(ff, 2, 1), NULL, 10);
772         p->io_write_calls                               = strtoull(procfile_lineword(ff, 3, 1), NULL, 10);
773         p->io_storage_bytes_read                = strtoull(procfile_lineword(ff, 4, 1), NULL, 10);
774         p->io_storage_bytes_written     = strtoull(procfile_lineword(ff, 5, 1), NULL, 10);
775         p->io_cancelled_write_bytes             = strtoull(procfile_lineword(ff, 6, 1), NULL, 10);
776
777         // procfile_close(ff);
778         return 0;
779 }
780
781
782 // ----------------------------------------------------------------------------
783
784 #ifdef INCLUDE_CHILDS
785 // print a tree view of all processes
786 int walk_down(pid_t pid, int level) {
787         struct pid_stat *p = NULL;
788         char b[level+3];
789         int i, ret = 0;
790
791         for(i = 0; i < level; i++) b[i] = '\t';
792         b[level] = '|';
793         b[level+1] = '-';
794         b[level+2] = '\0';
795
796         for(p = root_of_pids; p ; p = p->next) {
797                 if(p->ppid == pid) {
798                         ret += walk_down(p->pid, level+1);
799                 }
800         }
801
802         p = all_pids[pid];
803         if(p) {
804                 if(!p->updated) ret += 1;
805                 if(ret) fprintf(stderr, "%s %s %d [%s, %s] c=%d u=%llu+%llu, s=%llu+%llu, cu=%llu+%llu, cs=%llu+%llu, n=%llu+%llu, j=%llu+%llu, cn=%llu+%llu, cj=%llu+%llu\n"
806                         , b, p->comm, p->pid, p->updated?"OK":"KILLED", p->target->name, p->childs
807                         , p->utime, p->utime - p->old_utime
808                         , p->stime, p->stime - p->old_stime
809                         , p->cutime, p->cutime - p->old_cutime
810                         , p->cstime, p->cstime - p->old_cstime
811                         , p->minflt, p->minflt - p->old_minflt
812                         , p->majflt, p->majflt - p->old_majflt
813                         , p->cminflt, p->cminflt - p->old_cminflt
814                         , p->cmajflt, p->cmajflt - p->old_cmajflt
815                         );
816         }
817
818         return ret;
819 }
820 #endif
821
822
823 // ----------------------------------------------------------------------------
824 // file descriptor
825 // this is used to keep a global list of all open files of the system
826 // it is needed in order to figure out the unique files a process tree has open
827
828 #define FILE_DESCRIPTORS_INCREASE_STEP 100
829
830 struct file_descriptor {
831         avl avl;
832         uint32_t magic;
833         uint32_t hash;
834         const char *name;
835         int type;
836         int count;
837         int pos;
838 } *all_files = NULL;
839
840 int all_files_len = 0;
841 int all_files_size = 0;
842
843 int file_descriptor_compare(void* a, void* b) {
844         if(((struct file_descriptor *)a)->magic != 0x0BADCAFE || ((struct file_descriptor *)b)->magic != 0x0BADCAFE)
845                 error("Corrupted index data detected. Please report this.");
846
847         if(((struct file_descriptor *)a)->hash < ((struct file_descriptor *)b)->hash)
848                 return -1;
849         else if(((struct file_descriptor *)a)->hash > ((struct file_descriptor *)b)->hash)
850                 return 1;
851         else return strcmp(((struct file_descriptor *)a)->name, ((struct file_descriptor *)b)->name);
852 }
853 int file_descriptor_iterator(avl *a) { if(a) {}; return 0; }
854
855 avl_tree all_files_index = {
856                 NULL,
857                 file_descriptor_compare,
858 #ifdef AVL_LOCK_WITH_MUTEX
859                 PTHREAD_MUTEX_INITIALIZER
860 #else
861                 PTHREAD_RWLOCK_INITIALIZER
862 #endif
863 };
864
865 static struct file_descriptor *file_descriptor_find(const char *name, uint32_t hash) {
866         struct file_descriptor *result = NULL, tmp;
867         tmp.hash = (hash)?hash:simple_hash(name);
868         tmp.name = name;
869         tmp.count = 0;
870         tmp.pos = 0;
871         tmp.magic = 0x0BADCAFE;
872
873         avl_search(&all_files_index, (avl *)&tmp, file_descriptor_iterator, (avl **)&result);
874         return result;
875 }
876
877 #define file_descriptor_add(fd) avl_insert(&all_files_index, (avl *)(fd))
878 #define file_descriptor_remove(fd) avl_remove(&all_files_index, (avl *)(fd))
879
880 #define FILETYPE_OTHER 0
881 #define FILETYPE_FILE 1
882 #define FILETYPE_PIPE 2
883 #define FILETYPE_SOCKET 3
884 #define FILETYPE_INOTIFY 4
885 #define FILETYPE_EVENTFD 5
886 #define FILETYPE_EVENTPOLL 6
887 #define FILETYPE_TIMERFD 7
888 #define FILETYPE_SIGNALFD 8
889
890 void file_descriptor_not_used(int id)
891 {
892         if(id > 0 && id < all_files_size) {
893                 if(all_files[id].magic != 0x0BADCAFE) {
894                         error("Ignoring request to remove empty file id %d.", id);
895                         return;
896                 }
897
898                 if(debug) fprintf(stderr, "apps.plugin: decreasing slot %d (count = %d).\n", id, all_files[id].count);
899
900                 if(all_files[id].count > 0) {
901                         all_files[id].count--;
902
903                         if(!all_files[id].count) {
904                                 if(debug) fprintf(stderr, "apps.plugin:   >> slot %d is empty.\n", id);
905                                 file_descriptor_remove(&all_files[id]);
906                                 all_files[id].magic = 0x00000000;
907                                 all_files_len--;
908                         }
909                 }
910                 else
911                         error("Request to decrease counter of fd %d (%s), while the use counter is 0", id, all_files[id].name);
912         }
913         else    error("Request to decrease counter of fd %d, which is outside the array size (1 to %d)", id, all_files_size);
914 }
915
916 int file_descriptor_find_or_add(const char *name)
917 {
918         static int last_pos = 0;
919         uint32_t hash = simple_hash(name);
920
921         if(debug) fprintf(stderr, "apps.plugin: adding or finding name '%s' with hash %u\n", name, hash);
922
923         struct file_descriptor *fd = file_descriptor_find(name, hash);
924         if(fd) {
925                 // found
926                 if(debug) fprintf(stderr, "apps.plugin:   >> found on slot %d\n", fd->pos);
927                 fd->count++;
928                 return fd->pos;
929         }
930         // not found
931
932         // check we have enough memory to add it
933         if(!all_files || all_files_len == all_files_size) {
934                 void *old = all_files;
935                 int i;
936
937                 // there is no empty slot
938                 if(debug) fprintf(stderr, "apps.plugin: extending fd array to %d entries\n", all_files_size + FILE_DESCRIPTORS_INCREASE_STEP);
939                 all_files = realloc(all_files, (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP) * sizeof(struct file_descriptor));
940
941                 // if the address changed, we have to rebuild the index
942                 // since all pointers are now invalid
943                 if(old && old != (void *)all_files) {
944                         if(debug) fprintf(stderr, "apps.plugin:   >> re-indexing.\n");
945                         all_files_index.root = NULL;
946                         for(i = 0; i < all_files_size; i++) {
947                                 if(!all_files[i].count) continue;
948                                 file_descriptor_add(&all_files[i]);
949                         }
950                         if(debug) fprintf(stderr, "apps.plugin:   >> re-indexing done.\n");
951                 }
952
953                 for(i = all_files_size; i < (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP); i++) {
954                         all_files[i].count = 0;
955                         all_files[i].name = NULL;
956                         all_files[i].magic = 0x00000000;
957                         all_files[i].pos = i;
958                 }
959
960                 if(!all_files_size) all_files_len = 1;
961                 all_files_size += FILE_DESCRIPTORS_INCREASE_STEP;
962         }
963
964         if(debug) fprintf(stderr, "apps.plugin:   >> searching for empty slot.\n");
965
966         // search for an empty slot
967         int i, c;
968         for(i = 0, c = last_pos ; i < all_files_size ; i++, c++) {
969                 if(c >= all_files_size) c = 0;
970                 if(c == 0) continue;
971
972                 if(!all_files[c].count) {
973                         if(debug) fprintf(stderr, "apps.plugin:   >> Examining slot %d.\n", c);
974
975                         if(all_files[c].magic == 0x0BADCAFE && all_files[c].name && file_descriptor_find(all_files[c].name, all_files[c].hash))
976                                 error("fd on position %d is not cleared properly. It still has %s in it.\n", c, all_files[c].name);
977
978                         if(debug) fprintf(stderr, "apps.plugin:   >> %s fd position %d for %s (last name: %s)\n", all_files[c].name?"re-using":"using", c, name, all_files[c].name);
979                         if(all_files[c].name) free((void *)all_files[c].name);
980                         all_files[c].name = NULL;
981                         last_pos = c;
982                         break;
983                 }
984         }
985         if(i == all_files_size) {
986                 fatal("We should find an empty slot, but there isn't any");
987                 exit(1);
988         }
989         if(debug) fprintf(stderr, "apps.plugin:   >> updating slot %d.\n", c);
990
991         all_files_len++;
992
993         // else we have an empty slot in 'c'
994
995         int type;
996         if(name[0] == '/') type = FILETYPE_FILE;
997         else if(strncmp(name, "pipe:", 5) == 0) type = FILETYPE_PIPE;
998         else if(strncmp(name, "socket:", 7) == 0) type = FILETYPE_SOCKET;
999         else if(strcmp(name, "anon_inode:inotify") == 0 || strcmp(name, "inotify") == 0) type = FILETYPE_INOTIFY;
1000         else if(strcmp(name, "anon_inode:[eventfd]") == 0) type = FILETYPE_EVENTFD;
1001         else if(strcmp(name, "anon_inode:[eventpoll]") == 0) type = FILETYPE_EVENTPOLL;
1002         else if(strcmp(name, "anon_inode:[timerfd]") == 0) type = FILETYPE_TIMERFD;
1003         else if(strcmp(name, "anon_inode:[signalfd]") == 0) type = FILETYPE_SIGNALFD;
1004         else if(strncmp(name, "anon_inode:", 11) == 0) {
1005                 if(debug) fprintf(stderr, "apps.plugin: FIXME: unknown anonymous inode: %s\n", name);
1006                 type = FILETYPE_OTHER;
1007         }
1008         else {
1009                 if(debug) fprintf(stderr, "apps.plugin: FIXME: cannot understand linkname: %s\n", name);
1010                 type = FILETYPE_OTHER;
1011         }
1012
1013         all_files[c].name = strdup(name);
1014         all_files[c].hash = hash;
1015         all_files[c].type = type;
1016         all_files[c].pos  = c;
1017         all_files[c].count = 1;
1018         all_files[c].magic = 0x0BADCAFE;
1019
1020         file_descriptor_add(&all_files[c]);
1021
1022         if(debug) fprintf(stderr, "apps.plugin: using fd position %d (name: %s)\n", c, all_files[c].name);
1023
1024         return c;
1025 }
1026
1027
1028 // 1. read all files in /proc
1029 // 2. for each numeric directory:
1030 //    i.   read /proc/pid/stat
1031 //    ii.  read /proc/pid/statm
1032 //    iii. read /proc/pid/io (requires root access)
1033 //    iii. read the entries in directory /proc/pid/fd (requires root access)
1034 //         for each entry:
1035 //         a. find or create a struct file_descriptor
1036 //         b. cleanup any old/unused file_descriptors
1037
1038 // after all these, some pids may be linked to targets, while others may not
1039
1040 // in case of errors, only 1 every 1000 errors is printed
1041 // to avoid filling up all disk space
1042 // if debug is enabled, all errors are printed
1043
1044 int update_from_proc(void)
1045 {
1046         static long count_errors = 0;
1047
1048         char filename[FILENAME_MAX+1];
1049         char dirname[FILENAME_MAX + 1];
1050
1051         snprintf(dirname, FILENAME_MAX, "%s/proc", host_prefix);
1052         DIR *dir = opendir(dirname);
1053         if(!dir) return 0;
1054
1055         struct dirent *file = NULL;
1056         struct pid_stat *p = NULL;
1057
1058         // mark them all as un-updated
1059         all_pids_count = 0;
1060         for(p = root_of_pids; p ; p = p->next) {
1061                 all_pids_count++;
1062                 p->parent = NULL;
1063                 p->updated = 0;
1064                 p->childs = 0;
1065                 p->merged = 0;
1066                 p->new_entry = 0;
1067         }
1068
1069         while((file = readdir(dir))) {
1070                 char *endptr = file->d_name;
1071                 pid_t pid = (pid_t) strtoul(file->d_name, &endptr, 10);
1072                 if(pid <= 0 || pid > pid_max || endptr == file->d_name || *endptr != '\0') continue;
1073
1074                 p = get_pid_entry(pid);
1075                 if(!p) continue;
1076
1077                 // --------------------------------------------------------------------
1078                 // /proc/<pid>/stat
1079
1080                 if(read_proc_pid_stat(p)) {
1081                         if(!count_errors++ || debug || (p->target && p->target->debug))
1082                                 error("Cannot process %s/proc/%d/stat", host_prefix, pid);
1083
1084                         continue;
1085                 }
1086                 if(p->ppid < 0 || p->ppid > pid_max) p->ppid = 0;
1087
1088
1089                 // --------------------------------------------------------------------
1090                 // /proc/<pid>/statm
1091
1092                 if(read_proc_pid_statm(p)) {
1093                         if(!count_errors++ || debug || (p->target && p->target->debug))
1094                                 error("Cannot process %s/proc/%d/statm", host_prefix, pid);
1095
1096                         continue;
1097                 }
1098
1099
1100                 // --------------------------------------------------------------------
1101                 // /proc/<pid>/io
1102
1103                 if(read_proc_pid_io(p)) {
1104                         if(!count_errors++ || debug || (p->target && p->target->debug))
1105                                 error("Cannot process %s/proc/%d/io", host_prefix, pid);
1106
1107                         continue;
1108                 }
1109
1110                 // --------------------------------------------------------------------
1111                 // link it
1112
1113                 // check if it is target
1114                 // we do this only once, the first time this pid is loaded
1115                 if(p->new_entry) {
1116                         if(debug) fprintf(stderr, "apps.plugin: \tJust added %s\n", p->comm);
1117
1118                         struct target *w;
1119                         for(w = target_root; w ; w = w->next) {
1120                                 // if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \t\tcomparing '%s' with '%s'\n", w->compare, p->comm);
1121
1122                                 if(strcmp(w->compare, p->comm) == 0) {
1123                                         if(w->target) p->target = w->target;
1124                                         else p->target = w;
1125
1126                                         if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \t\t%s linked to target %s\n", p->comm, p->target->name);
1127                                 }
1128                         }
1129                 }
1130
1131                 // --------------------------------------------------------------------
1132                 // /proc/<pid>/fd
1133
1134                 snprintf(filename, FILENAME_MAX, "%s/proc/%s/fd", host_prefix, file->d_name);
1135                 DIR *fds = opendir(filename);
1136                 if(fds) {
1137                         int c;
1138                         struct dirent *de;
1139                         char fdname[FILENAME_MAX + 1];
1140                         char linkname[FILENAME_MAX + 1];
1141
1142                         // make the array negative
1143                         for(c = 0 ; c < p->fds_size ; c++) p->fds[c] = -p->fds[c];
1144
1145                         while((de = readdir(fds))) {
1146                                 if(strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) continue;
1147
1148                                 // check if the fds array is small
1149                                 int fdid = atoi(de->d_name);
1150                                 if(fdid < 0) continue;
1151                                 if(fdid >= p->fds_size) {
1152                                         // it is small, extend it
1153                                         if(debug) fprintf(stderr, "apps.plugin: extending fd memory slots for %s from %d to %d\n", p->comm, p->fds_size, fdid + 100);
1154                                         p->fds = realloc(p->fds, (fdid + 100) * sizeof(int));
1155                                         if(!p->fds) {
1156                                                 error("Cannot re-allocate fds for %s", p->comm);
1157                                                 break;
1158                                         }
1159
1160                                         // and initialize it
1161                                         for(c = p->fds_size ; c < (fdid + 100) ; c++) p->fds[c] = 0;
1162                                         p->fds_size = fdid + 100;
1163                                 }
1164
1165                                 if(p->fds[fdid] == 0) {
1166                                         // we don't know this fd, get it
1167
1168                                         sprintf(fdname, "%s/proc/%s/fd/%s", host_prefix, file->d_name, de->d_name);
1169                                         ssize_t l = readlink(fdname, linkname, FILENAME_MAX);
1170                                         if(l == -1) {
1171                                                 if(debug || (p->target && p->target->debug)) {
1172                                                         if(!count_errors++ || debug || (p->target && p->target->debug))
1173                                                                 error("Cannot read link %s", fdname);
1174                                                 }
1175                                                 continue;
1176                                         }
1177                                         linkname[l] = '\0';
1178                                         file_counter++;
1179
1180                                         // if another process already has this, we will get
1181                                         // the same id
1182                                         p->fds[fdid] = file_descriptor_find_or_add(linkname);
1183                                 }
1184
1185                                 // else make it positive again, we need it
1186                                 // of course, the actual file may have changed, but we don't care so much
1187                                 // FIXME: we could compare the inode as returned by readdir direct structure
1188                                 else p->fds[fdid] = -p->fds[fdid];
1189                         }
1190                         closedir(fds);
1191
1192                         // remove all the negative file descriptors
1193                         for(c = 0 ; c < p->fds_size ; c++) if(p->fds[c] < 0) {
1194                                 file_descriptor_not_used(-p->fds[c]);
1195                                 p->fds[c] = 0;
1196                         }
1197                 }
1198
1199                 // --------------------------------------------------------------------
1200                 // done!
1201
1202                 // mark it as updated
1203                 p->updated = 1;
1204         }
1205         if(count_errors > 1000) {
1206                 error("%ld more errors encountered\n", count_errors - 1);
1207                 count_errors = 0;
1208         }
1209
1210         closedir(dir);
1211
1212         return 1;
1213 }
1214
1215
1216 // ----------------------------------------------------------------------------
1217 // update statistics on the targets
1218
1219 // 1. link all childs to their parents
1220 // 2. go from bottom to top, marking as merged all childs to their parents
1221 //    this step links all parents without a target to the child target, if any
1222 // 3. link all top level processes (the ones not merged) to the default target
1223 // 4. go from top to bottom, linking all childs without a target, to their parent target
1224 //    after this step, all processes have a target
1225 // [5. for each killed pid (updated = 0), remove its usage from its target]
1226 // 6. zero all targets
1227 // 7. concentrate all values on the targets
1228 // 8. remove all killed processes
1229 // 9. find the unique file count for each target
1230
1231 void update_statistics(void)
1232 {
1233         int c;
1234         struct pid_stat *p = NULL;
1235
1236         // link all parents and update childs count
1237         for(p = root_of_pids; p ; p = p->next) {
1238                 if(p->ppid > 0 && p->ppid <= pid_max && all_pids[p->ppid]) {
1239                         if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \tparent of %d %s is %d %s\n", p->pid, p->comm, p->ppid, all_pids[p->ppid]->comm);
1240
1241                         p->parent = all_pids[p->ppid];
1242                         p->parent->childs++;
1243                 }
1244                 else if(p->ppid != 0) error("pid %d %s states parent %d, but the later does not exist.", p->pid, p->comm, p->ppid);
1245         }
1246
1247         // find all the procs with 0 childs and merge them to their parents
1248         // repeat, until nothing more can be done.
1249         int found = 1;
1250         while(found) {
1251                 found = 0;
1252                 for(p = root_of_pids; p ; p = p->next) {
1253                         // if this process does not have any childs, and
1254                         // is not already merged, and
1255                         // its parent has childs waiting to be merged, and
1256                         // the target of this process and its parent is the same, or the parent does not have a target, or this process does not have a parent
1257                         // and its parent is not init
1258                         // then... merge them!
1259                         if(!p->childs && !p->merged && p->parent && p->parent->childs && (p->target == p->parent->target || !p->parent->target || !p->target) && p->ppid != 1) {
1260                                 p->parent->childs--;
1261                                 p->merged = 1;
1262
1263                                 // the parent inherits the child's target, if it does not have a target itself
1264                                 if(p->target && !p->parent->target) {
1265                                         p->parent->target = p->target;
1266                                         if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \t\ttarget %s is inherited by %d %s from its child %d %s.\n", p->target->name, p->parent->pid, p->parent->comm, p->pid, p->comm);
1267                                 }
1268
1269                                 found++;
1270                         }
1271                 }
1272                 if(debug) fprintf(stderr, "apps.plugin: merged %d processes\n", found);
1273         }
1274
1275         // give a default target on all top level processes
1276         // init goes always to default target
1277         if(all_pids[1]) all_pids[1]->target = default_target;
1278
1279         for(p = root_of_pids; p ; p = p->next) {
1280                 // if the process is not merged itself
1281                 // then is is a top level process
1282                 if(!p->merged && !p->target) p->target = default_target;
1283
1284 #ifdef INCLUDE_CHILDS
1285                 // by the way, update the diffs
1286                 // will be used later for substracting killed process times
1287                 p->diff_cutime = p->utime - p->cutime;
1288                 p->diff_cstime = p->stime - p->cstime;
1289                 p->diff_cminflt = p->minflt - p->cminflt;
1290                 p->diff_cmajflt = p->majflt - p->cmajflt;
1291 #endif
1292         }
1293
1294         // give a target to all merged child processes
1295         found = 1;
1296         while(found) {
1297                 found = 0;
1298                 for(p = root_of_pids; p ; p = p->next) {
1299                         if(!p->target && p->merged && p->parent && p->parent->target) {
1300                                 p->target = p->parent->target;
1301                                 found++;
1302                         }
1303                 }
1304         }
1305
1306 #ifdef INCLUDE_CHILDS
1307         // for each killed process, remove its values from the parents
1308         // sums (we had already added them in a previous loop)
1309         for(p = root_of_pids; p ; p = p->next) {
1310                 if(p->updated) continue;
1311
1312                 if(debug) fprintf(stderr, "apps.plugin: UNMERGING %d %s\n", p->pid, p->comm);
1313
1314                 unsigned long long diff_utime = p->utime + p->cutime + p->fix_cutime;
1315                 unsigned long long diff_stime = p->stime + p->cstime + p->fix_cstime;
1316                 unsigned long long diff_minflt = p->minflt + p->cminflt + p->fix_cminflt;
1317                 unsigned long long diff_majflt = p->majflt + p->cmajflt + p->fix_cmajflt;
1318
1319                 struct pid_stat *t = p;
1320                 while((t = t->parent)) {
1321                         if(!t->updated) continue;
1322
1323                         unsigned long long x;
1324                         if(diff_utime && t->diff_cutime) {
1325                                 x = (t->diff_cutime < diff_utime)?t->diff_cutime:diff_utime;
1326                                 diff_utime -= x;
1327                                 t->diff_cutime -= x;
1328                                 t->fix_cutime += x;
1329                                 if(debug) fprintf(stderr, "apps.plugin: \t cutime %llu from %d %s %s\n", x, t->pid, t->comm, t->target->name);
1330                         }
1331                         if(diff_stime && t->diff_cstime) {
1332                                 x = (t->diff_cstime < diff_stime)?t->diff_cstime:diff_stime;
1333                                 diff_stime -= x;
1334                                 t->diff_cstime -= x;
1335                                 t->fix_cstime += x;
1336                                 if(debug) fprintf(stderr, "apps.plugin: \t cstime %llu from %d %s %s\n", x, t->pid, t->comm, t->target->name);
1337                         }
1338                         if(diff_minflt && t->diff_cminflt) {
1339                                 x = (t->diff_cminflt < diff_minflt)?t->diff_cminflt:diff_minflt;
1340                                 diff_minflt -= x;
1341                                 t->diff_cminflt -= x;
1342                                 t->fix_cminflt += x;
1343                                 if(debug) fprintf(stderr, "apps.plugin: \t cminflt %llu from %d %s %s\n", x, t->pid, t->comm, t->target->name);
1344                         }
1345                         if(diff_majflt && t->diff_cmajflt) {
1346                                 x = (t->diff_cmajflt < diff_majflt)?t->diff_cmajflt:diff_majflt;
1347                                 diff_majflt -= x;
1348                                 t->diff_cmajflt -= x;
1349                                 t->fix_cmajflt += x;
1350                                 if(debug) fprintf(stderr, "apps.plugin: \t cmajflt %llu from %d %s %s\n", x, t->pid, t->comm, t->target->name);
1351                         }
1352                 }
1353
1354                 if(diff_utime) error("Cannot fix up utime %llu", diff_utime);
1355                 if(diff_stime) error("Cannot fix up stime %llu", diff_stime);
1356                 if(diff_minflt) error("Cannot fix up minflt %llu", diff_minflt);
1357                 if(diff_majflt) error("Cannot fix up majflt %llu", diff_majflt);
1358         }
1359 #endif
1360
1361         // zero all the targets
1362         targets = 0;
1363         struct target *w;
1364         for (w = target_root; w ; w = w->next) {
1365                 targets++;
1366
1367                 w->fds = calloc(sizeof(int), (size_t) all_files_size);
1368                 if(!w->fds)
1369                         error("Cannot allocate memory for fds in %s", w->name);
1370
1371                 w->minflt = 0;
1372                 w->majflt = 0;
1373                 w->utime = 0;
1374                 w->stime = 0;
1375                 w->cminflt = 0;
1376                 w->cmajflt = 0;
1377                 w->cutime = 0;
1378                 w->cstime = 0;
1379                 w->num_threads = 0;
1380                 w->rss = 0;
1381                 w->processes = 0;
1382
1383                 w->statm_size = 0;
1384                 w->statm_resident = 0;
1385                 w->statm_share = 0;
1386                 w->statm_text = 0;
1387                 w->statm_lib = 0;
1388                 w->statm_data = 0;
1389                 w->statm_dirty = 0;
1390
1391                 w->io_logical_bytes_read = 0;
1392                 w->io_logical_bytes_written = 0;
1393                 w->io_read_calls = 0;
1394                 w->io_write_calls = 0;
1395                 w->io_storage_bytes_read = 0;
1396                 w->io_storage_bytes_written = 0;
1397                 w->io_cancelled_write_bytes = 0;
1398         }
1399
1400 #ifdef INCLUDE_CHILDS
1401         if(debug) walk_down(0, 1);
1402 #endif
1403
1404         // concentrate everything on the targets
1405         for(p = root_of_pids; p ; p = p->next) {
1406                 if(!p->target) {
1407                         error("pid %d %s was left without a target!", p->pid, p->comm);
1408                         continue;
1409                 }
1410
1411                 if(p->updated) {
1412                         p->target->cutime += p->cutime; // - p->fix_cutime;
1413                         p->target->cstime += p->cstime; // - p->fix_cstime;
1414                         p->target->cminflt += p->cminflt; // - p->fix_cminflt;
1415                         p->target->cmajflt += p->cmajflt; // - p->fix_cmajflt;
1416
1417                         p->target->utime += p->utime; //+ (p->pid != 1)?(p->cutime - p->fix_cutime):0;
1418                         p->target->stime += p->stime; //+ (p->pid != 1)?(p->cstime - p->fix_cstime):0;
1419                         p->target->minflt += p->minflt; //+ (p->pid != 1)?(p->cminflt - p->fix_cminflt):0;
1420                         p->target->majflt += p->majflt; //+ (p->pid != 1)?(p->cmajflt - p->fix_cmajflt):0;
1421
1422                         //if(p->num_threads < 0)
1423                         //      error("Negative threads number for pid '%s' (%d): %d", p->comm, p->pid, p->num_threads);
1424
1425                         //if(p->num_threads > 10000)
1426                         //      error("Excessive threads number for pid '%s' (%d): %d", p->comm, p->pid, p->num_threads);
1427
1428                         p->target->num_threads += p->num_threads;
1429                         p->target->rss += p->rss;
1430
1431                         p->target->statm_size += p->statm_size;
1432                         p->target->statm_resident += p->statm_resident;
1433                         p->target->statm_share += p->statm_share;
1434                         p->target->statm_text += p->statm_text;
1435                         p->target->statm_lib += p->statm_lib;
1436                         p->target->statm_data += p->statm_data;
1437                         p->target->statm_dirty += p->statm_dirty;
1438
1439                         p->target->io_logical_bytes_read += p->io_logical_bytes_read;
1440                         p->target->io_logical_bytes_written += p->io_logical_bytes_written;
1441                         p->target->io_read_calls += p->io_read_calls;
1442                         p->target->io_write_calls += p->io_write_calls;
1443                         p->target->io_storage_bytes_read += p->io_storage_bytes_read;
1444                         p->target->io_storage_bytes_written += p->io_storage_bytes_written;
1445                         p->target->io_cancelled_write_bytes += p->io_cancelled_write_bytes;
1446
1447                         p->target->processes++;
1448
1449                         for(c = 0; c < p->fds_size ;c++) {
1450                                 if(p->fds[c] == 0) continue;
1451                                 if(p->fds[c] < all_files_size) {
1452                                         if(p->target->fds) p->target->fds[p->fds[c]]++;
1453                                 }
1454                                 else
1455                                         error("Invalid fd number %d", p->fds[c]);
1456                         }
1457
1458                         if(debug || p->target->debug) fprintf(stderr, "apps.plugin: \tAgregating %s pid %d on %s utime=%llu, stime=%llu, cutime=%llu, cstime=%llu, minflt=%llu, majflt=%llu, cminflt=%llu, cmajflt=%llu\n", p->comm, p->pid, p->target->name, p->utime, p->stime, p->cutime, p->cstime, p->minflt, p->majflt, p->cminflt, p->cmajflt);
1459
1460 /*                      if(p->utime - p->old_utime > 100) fprintf(stderr, "BIG CHANGE: %d %s utime increased by %llu from %llu to %llu\n", p->pid, p->comm, p->utime - p->old_utime, p->old_utime, p->utime);
1461                         if(p->cutime - p->old_cutime > 100) fprintf(stderr, "BIG CHANGE: %d %s cutime increased by %llu from %llu to %llu\n", p->pid, p->comm, p->cutime - p->old_cutime, p->old_cutime, p->cutime);
1462                         if(p->stime - p->old_stime > 100) fprintf(stderr, "BIG CHANGE: %d %s stime increased by %llu from %llu to %llu\n", p->pid, p->comm, p->stime - p->old_stime, p->old_stime, p->stime);
1463                         if(p->cstime - p->old_cstime > 100) fprintf(stderr, "BIG CHANGE: %d %s cstime increased by %llu from %llu to %llu\n", p->pid, p->comm, p->cstime - p->old_cstime, p->old_cstime, p->cstime);
1464                         if(p->minflt - p->old_minflt > 5000) fprintf(stderr, "BIG CHANGE: %d %s minflt increased by %llu from %llu to %llu\n", p->pid, p->comm, p->minflt - p->old_minflt, p->old_minflt, p->minflt);
1465                         if(p->majflt - p->old_majflt > 5000) fprintf(stderr, "BIG CHANGE: %d %s majflt increased by %llu from %llu to %llu\n", p->pid, p->comm, p->majflt - p->old_majflt, p->old_majflt, p->majflt);
1466                         if(p->cminflt - p->old_cminflt > 15000) fprintf(stderr, "BIG CHANGE: %d %s cminflt increased by %llu from %llu to %llu\n", p->pid, p->comm, p->cminflt - p->old_cminflt, p->old_cminflt, p->cminflt);
1467                         if(p->cmajflt - p->old_cmajflt > 15000) fprintf(stderr, "BIG CHANGE: %d %s cmajflt increased by %llu from %llu to %llu\n", p->pid, p->comm, p->cmajflt - p->old_cmajflt, p->old_cmajflt, p->cmajflt);
1468 */
1469 #ifdef INCLUDE_CHILDS
1470                         p->old_utime = p->utime;
1471                         p->old_cutime = p->cutime;
1472                         p->old_stime = p->stime;
1473                         p->old_cstime = p->cstime;
1474                         p->old_minflt = p->minflt;
1475                         p->old_majflt = p->majflt;
1476                         p->old_cminflt = p->cminflt;
1477                         p->old_cmajflt = p->cmajflt;
1478 #endif
1479                 }
1480                 else {
1481                         // since the process has exited, the user
1482                         // will see a drop in our charts, because the incremental
1483                         // values of this process will not be there
1484
1485                         // add them to the fix_* values and they will be added to
1486                         // the reported values, so that the report goes steady
1487                         p->target->fix_minflt += p->minflt;
1488                         p->target->fix_majflt += p->majflt;
1489                         p->target->fix_utime += p->utime;
1490                         p->target->fix_stime += p->stime;
1491                         p->target->fix_cminflt += p->cminflt;
1492                         p->target->fix_cmajflt += p->cmajflt;
1493                         p->target->fix_cutime += p->cutime;
1494                         p->target->fix_cstime += p->cstime;
1495
1496                         p->target->fix_io_logical_bytes_read += p->io_logical_bytes_read;
1497                         p->target->fix_io_logical_bytes_written += p->io_logical_bytes_written;
1498                         p->target->fix_io_read_calls += p->io_read_calls;
1499                         p->target->fix_io_write_calls += p->io_write_calls;
1500                         p->target->fix_io_storage_bytes_read += p->io_storage_bytes_read;
1501                         p->target->fix_io_storage_bytes_written += p->io_storage_bytes_written;
1502                         p->target->fix_io_cancelled_write_bytes += p->io_cancelled_write_bytes;
1503                 }
1504         }
1505
1506 //      fprintf(stderr, "\n");
1507         // cleanup all un-updated processed (exited, killed, etc)
1508         for(p = root_of_pids; p ;) {
1509                 if(!p->updated) {
1510 //                      fprintf(stderr, "\tEXITED %d %s [parent %d %s, target %s] utime=%llu, stime=%llu, cutime=%llu, cstime=%llu, minflt=%llu, majflt=%llu, cminflt=%llu, cmajflt=%llu\n", p->pid, p->comm, p->parent->pid, p->parent->comm, p->target->name,  p->utime, p->stime, p->cutime, p->cstime, p->minflt, p->majflt, p->cminflt, p->cmajflt);
1511
1512                         for(c = 0 ; c < p->fds_size ; c++) if(p->fds[c] > 0) {
1513                                 file_descriptor_not_used(p->fds[c]);
1514                                 p->fds[c] = 0;
1515                         }
1516
1517                         pid_t r = p->pid;
1518                         p = p->next;
1519                         del_pid_entry(r);
1520                 }
1521                 else p = p->next;
1522         }
1523
1524         for (w = target_root; w ; w = w->next) {
1525                 w->openfiles = 0;
1526                 w->openpipes = 0;
1527                 w->opensockets = 0;
1528                 w->openinotifies = 0;
1529                 w->openeventfds = 0;
1530                 w->opentimerfds = 0;
1531                 w->opensignalfds = 0;
1532                 w->openeventpolls = 0;
1533                 w->openother = 0;
1534
1535                 for(c = 1; c < all_files_size ;c++) {
1536                         if(w->fds && w->fds[c] > 0) switch(all_files[c].type) {
1537                                 case FILETYPE_FILE:
1538                                         w->openfiles++;
1539                                         break;
1540
1541                                 case FILETYPE_PIPE:
1542                                         w->openpipes++;
1543                                         break;
1544
1545                                 case FILETYPE_SOCKET:
1546                                         w->opensockets++;
1547                                         break;
1548
1549                                 case FILETYPE_INOTIFY:
1550                                         w->openinotifies++;
1551                                         break;
1552
1553                                 case FILETYPE_EVENTFD:
1554                                         w->openeventfds++;
1555                                         break;
1556
1557                                 case FILETYPE_TIMERFD:
1558                                         w->opentimerfds++;
1559                                         break;
1560
1561                                 case FILETYPE_SIGNALFD:
1562                                         w->opensignalfds++;
1563                                         break;
1564
1565                                 case FILETYPE_EVENTPOLL:
1566                                         w->openeventpolls++;
1567                                         break;
1568
1569                                 default:
1570                                         w->openother++;
1571                         }
1572                 }
1573
1574                 free(w->fds);
1575                 w->fds = NULL;
1576         }
1577 }
1578
1579 // ----------------------------------------------------------------------------
1580 // update chart dimensions
1581
1582 void show_dimensions(void)
1583 {
1584         static struct timeval last = { 0, 0 };
1585         static struct rusage me_last;
1586
1587         struct target *w;
1588         struct timeval now;
1589         struct rusage me;
1590
1591         unsigned long long usec;
1592         unsigned long long cpuuser;
1593         unsigned long long cpusyst;
1594
1595         if(!last.tv_sec) {
1596                 gettimeofday(&last, NULL);
1597                 getrusage(RUSAGE_SELF, &me_last);
1598
1599                 // the first time, give a zero to allow
1600                 // netdata calibrate to the current time
1601                 // usec = update_every * 1000000ULL;
1602                 usec = 0ULL;
1603                 cpuuser = 0;
1604                 cpusyst = 0;
1605         }
1606         else {
1607                 gettimeofday(&now, NULL);
1608                 getrusage(RUSAGE_SELF, &me);
1609
1610                 usec = usecdiff(&now, &last);
1611                 cpuuser = me.ru_utime.tv_sec * 1000000ULL + me.ru_utime.tv_usec;
1612                 cpusyst = me.ru_stime.tv_sec * 1000000ULL + me.ru_stime.tv_usec;
1613
1614                 bcopy(&now, &last, sizeof(struct timeval));
1615                 bcopy(&me, &me_last, sizeof(struct rusage));
1616         }
1617
1618         fprintf(stdout, "BEGIN apps.cpu %llu\n", usec);
1619         for (w = target_root; w ; w = w->next) {
1620                 if(w->target || (!w->processes && !w->exposed)) continue;
1621
1622                 fprintf(stdout, "SET %s = %llu\n", w->name, w->utime + w->stime + w->fix_utime + w->fix_stime);
1623         }
1624         fprintf(stdout, "END\n");
1625
1626         fprintf(stdout, "BEGIN apps.cpu_user %llu\n", usec);
1627         for (w = target_root; w ; w = w->next) {
1628                 if(w->target || (!w->processes && !w->exposed)) continue;
1629
1630                 fprintf(stdout, "SET %s = %llu\n", w->name, w->utime + w->fix_utime);
1631         }
1632         fprintf(stdout, "END\n");
1633
1634         fprintf(stdout, "BEGIN apps.cpu_system %llu\n", usec);
1635         for (w = target_root; w ; w = w->next) {
1636                 if(w->target || (!w->processes && !w->exposed)) continue;
1637
1638                 fprintf(stdout, "SET %s = %llu\n", w->name, w->stime + w->fix_stime);
1639         }
1640         fprintf(stdout, "END\n");
1641
1642         fprintf(stdout, "BEGIN apps.threads %llu\n", usec);
1643         for (w = target_root; w ; w = w->next) {
1644                 if(w->target || (!w->processes && !w->exposed)) continue;
1645
1646                 fprintf(stdout, "SET %s = %llu\n", w->name, w->num_threads);
1647         }
1648         fprintf(stdout, "END\n");
1649
1650         fprintf(stdout, "BEGIN apps.processes %llu\n", usec);
1651         for (w = target_root; w ; w = w->next) {
1652                 if(w->target || (!w->processes && !w->exposed)) continue;
1653
1654                 fprintf(stdout, "SET %s = %lu\n", w->name, w->processes);
1655         }
1656         fprintf(stdout, "END\n");
1657
1658         fprintf(stdout, "BEGIN apps.mem %llu\n", usec);
1659         for (w = target_root; w ; w = w->next) {
1660                 if(w->target || (!w->processes && !w->exposed)) continue;
1661
1662                 fprintf(stdout, "SET %s = %lld\n", w->name, (long long)w->statm_resident - (long long)w->statm_share);
1663         }
1664         fprintf(stdout, "END\n");
1665
1666         fprintf(stdout, "BEGIN apps.minor_faults %llu\n", usec);
1667         for (w = target_root; w ; w = w->next) {
1668                 if(w->target || (!w->processes && !w->exposed)) continue;
1669
1670                 fprintf(stdout, "SET %s = %llu\n", w->name, w->minflt + w->fix_minflt);
1671         }
1672         fprintf(stdout, "END\n");
1673
1674         fprintf(stdout, "BEGIN apps.major_faults %llu\n", usec);
1675         for (w = target_root; w ; w = w->next) {
1676                 if(w->target || (!w->processes && !w->exposed)) continue;
1677
1678                 fprintf(stdout, "SET %s = %llu\n", w->name, w->majflt + w->fix_majflt);
1679         }
1680         fprintf(stdout, "END\n");
1681
1682         fprintf(stdout, "BEGIN apps.lreads %llu\n", usec);
1683         for (w = target_root; w ; w = w->next) {
1684                 if(w->target || (!w->processes && !w->exposed)) continue;
1685
1686                 fprintf(stdout, "SET %s = %llu\n", w->name, w->io_logical_bytes_read);
1687         }
1688         fprintf(stdout, "END\n");
1689
1690         fprintf(stdout, "BEGIN apps.lwrites %llu\n", usec);
1691         for (w = target_root; w ; w = w->next) {
1692                 if(w->target || (!w->processes && !w->exposed)) continue;
1693
1694                 fprintf(stdout, "SET %s = %llu\n", w->name, w->io_logical_bytes_written);
1695         }
1696         fprintf(stdout, "END\n");
1697
1698         fprintf(stdout, "BEGIN apps.preads %llu\n", usec);
1699         for (w = target_root; w ; w = w->next) {
1700                 if(w->target || (!w->processes && !w->exposed)) continue;
1701
1702                 fprintf(stdout, "SET %s = %llu\n", w->name, w->io_storage_bytes_read);
1703         }
1704         fprintf(stdout, "END\n");
1705
1706         fprintf(stdout, "BEGIN apps.pwrites %llu\n", usec);
1707         for (w = target_root; w ; w = w->next) {
1708                 if(w->target || (!w->processes && !w->exposed)) continue;
1709
1710                 fprintf(stdout, "SET %s = %llu\n", w->name, w->io_storage_bytes_written);
1711         }
1712         fprintf(stdout, "END\n");
1713
1714         fprintf(stdout, "BEGIN apps.files %llu\n", usec);
1715         for (w = target_root; w ; w = w->next) {
1716                 if(w->target || (!w->processes && !w->exposed)) continue;
1717
1718                 fprintf(stdout, "SET %s = %llu\n", w->name, w->openfiles);
1719         }
1720         fprintf(stdout, "END\n");
1721
1722         fprintf(stdout, "BEGIN apps.sockets %llu\n", usec);
1723         for (w = target_root; w ; w = w->next) {
1724                 if(w->target || (!w->processes && !w->exposed)) continue;
1725
1726                 fprintf(stdout, "SET %s = %llu\n", w->name, w->opensockets);
1727         }
1728         fprintf(stdout, "END\n");
1729
1730         fprintf(stdout, "BEGIN apps.pipes %llu\n", usec);
1731         for (w = target_root; w ; w = w->next) {
1732                 if(w->target || (!w->processes && !w->exposed)) continue;
1733
1734                 fprintf(stdout, "SET %s = %llu\n", w->name, w->openpipes);
1735         }
1736         fprintf(stdout, "END\n");
1737
1738         fprintf(stdout, "BEGIN netdata.apps_cpu %llu\n", usec);
1739         fprintf(stdout, "SET user = %llu\n", cpuuser);
1740         fprintf(stdout, "SET system = %llu\n", cpusyst);
1741         fprintf(stdout, "END\n");
1742
1743         fprintf(stdout, "BEGIN netdata.apps_files %llu\n", usec);
1744         fprintf(stdout, "SET files = %llu\n", file_counter);
1745         fprintf(stdout, "SET pids = %ld\n", all_pids_count);
1746         fprintf(stdout, "SET fds = %d\n", all_files_len);
1747         fprintf(stdout, "SET targets = %ld\n", targets);
1748         fprintf(stdout, "END\n");
1749
1750         fflush(stdout);
1751 }
1752
1753
1754 // ----------------------------------------------------------------------------
1755 // generate the charts
1756
1757 void show_charts(void)
1758 {
1759         struct target *w;
1760         int newly_added = 0;
1761
1762         for(w = target_root ; w ; w = w->next)
1763                 if(!w->exposed && w->processes) {
1764                         newly_added++;
1765                         w->exposed = 1;
1766                         if(debug || w->debug) fprintf(stderr, "apps.plugin: %s just added - regenerating charts.\n", w->name);
1767                 }
1768
1769         // nothing more to show
1770         if(!newly_added) return;
1771
1772         // we have something new to show
1773         // update the charts
1774         fprintf(stdout, "CHART apps.cpu '' 'Apps CPU Time (%ld%% = %ld core%s)' 'cpu time %%' cpu apps.cpu stacked 20001 %d\n", (processors * 100), processors, (processors>1)?"s":"", update_every);
1775         for (w = target_root; w ; w = w->next) {
1776                 if(w->target || (!w->processes && !w->exposed)) continue;
1777
1778                 fprintf(stdout, "DIMENSION %s '' incremental 100 %llu %s\n", w->name, Hertz, w->hidden ? "hidden,noreset" : "noreset");
1779         }
1780
1781         fprintf(stdout, "CHART apps.mem '' 'Apps Dedicated Memory (w/o shared)' 'MB' mem apps.mem stacked 20003 %d\n", update_every);
1782         for (w = target_root; w ; w = w->next) {
1783                 if(w->target || (!w->processes && !w->exposed)) continue;
1784
1785                 fprintf(stdout, "DIMENSION %s '' absolute %ld %ld noreset\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
1786         }
1787
1788         fprintf(stdout, "CHART apps.threads '' 'Apps Threads' 'threads' processes apps.threads stacked 20005 %d\n", update_every);
1789         for (w = target_root; w ; w = w->next) {
1790                 if(w->target || (!w->processes && !w->exposed)) continue;
1791
1792                 fprintf(stdout, "DIMENSION %s '' absolute 1 1 noreset\n", w->name);
1793         }
1794
1795         fprintf(stdout, "CHART apps.processes '' 'Apps Processes' 'processes' processes apps.processes stacked 20004 %d\n", update_every);
1796         for (w = target_root; w ; w = w->next) {
1797                 if(w->target || (!w->processes && !w->exposed)) continue;
1798
1799                 fprintf(stdout, "DIMENSION %s '' absolute 1 1 noreset\n", w->name);
1800         }
1801
1802         fprintf(stdout, "CHART apps.cpu_user '' 'Apps CPU User Time (%ld%% = %ld core%s)' 'cpu time %%' cpu apps.cpu_user stacked 20020 %d\n", (processors * 100), processors, (processors>1)?"s":"", update_every);
1803         for (w = target_root; w ; w = w->next) {
1804                 if(w->target || (!w->processes && !w->exposed)) continue;
1805
1806                 fprintf(stdout, "DIMENSION %s '' incremental 100 %llu noreset\n", w->name, Hertz * processors);
1807         }
1808
1809         fprintf(stdout, "CHART apps.cpu_system '' 'Apps CPU System Time (%ld%% = %ld core%s)' 'cpu time %%' cpu apps.cpu_system stacked 20021 %d\n", (processors * 100), processors, (processors>1)?"s":"", update_every);
1810         for (w = target_root; w ; w = w->next) {
1811                 if(w->target || (!w->processes && !w->exposed)) continue;
1812
1813                 fprintf(stdout, "DIMENSION %s '' incremental 100 %llu noreset\n", w->name, Hertz * processors);
1814         }
1815
1816         fprintf(stdout, "CHART apps.major_faults '' 'Apps Major Page Faults (swap read)' 'page faults/s' swap apps.major_faults stacked 20010 %d\n", update_every);
1817         for (w = target_root; w ; w = w->next) {
1818                 if(w->target || (!w->processes && !w->exposed)) continue;
1819
1820                 fprintf(stdout, "DIMENSION %s '' incremental 1 1 noreset\n", w->name);
1821         }
1822
1823         fprintf(stdout, "CHART apps.minor_faults '' 'Apps Minor Page Faults' 'page faults/s' mem apps.minor_faults stacked 20011 %d\n", update_every);
1824         for (w = target_root; w ; w = w->next) {
1825                 if(w->target || (!w->processes && !w->exposed)) continue;
1826
1827                 fprintf(stdout, "DIMENSION %s '' incremental 1 1 noreset\n", w->name);
1828         }
1829
1830         fprintf(stdout, "CHART apps.lreads '' 'Apps Disk Logical Reads' 'kilobytes/s' disk apps.lreads stacked 20042 %d\n", update_every);
1831         for (w = target_root; w ; w = w->next) {
1832                 if(w->target || (!w->processes && !w->exposed)) continue;
1833
1834                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d noreset\n", w->name, 1024);
1835         }
1836
1837         fprintf(stdout, "CHART apps.lwrites '' 'Apps I/O Logical Writes' 'kilobytes/s' disk apps.lwrites stacked 20042 %d\n", update_every);
1838         for (w = target_root; w ; w = w->next) {
1839                 if(w->target || (!w->processes && !w->exposed)) continue;
1840
1841                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d noreset\n", w->name, 1024);
1842         }
1843
1844         fprintf(stdout, "CHART apps.preads '' 'Apps Disk Reads' 'kilobytes/s' disk apps.preads stacked 20002 %d\n", update_every);
1845         for (w = target_root; w ; w = w->next) {
1846                 if(w->target || (!w->processes && !w->exposed)) continue;
1847
1848                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d noreset\n", w->name, 1024);
1849         }
1850
1851         fprintf(stdout, "CHART apps.pwrites '' 'Apps Disk Writes' 'kilobytes/s' disk apps.pwrites stacked 20002 %d\n", update_every);
1852         for (w = target_root; w ; w = w->next) {
1853                 if(w->target || (!w->processes && !w->exposed)) continue;
1854
1855                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d noreset\n", w->name, 1024);
1856         }
1857
1858         fprintf(stdout, "CHART apps.files '' 'Apps Open Files' 'open files' disk apps.files stacked 20050 %d\n", update_every);
1859         for (w = target_root; w ; w = w->next) {
1860                 if(w->target || (!w->processes && !w->exposed)) continue;
1861
1862                 fprintf(stdout, "DIMENSION %s '' absolute 1 1 noreset\n", w->name);
1863         }
1864
1865         fprintf(stdout, "CHART apps.sockets '' 'Apps Open Sockets' 'open sockets' net apps.sockets stacked 20051 %d\n", update_every);
1866         for (w = target_root; w ; w = w->next) {
1867                 if(w->target || (!w->processes && !w->exposed)) continue;
1868
1869                 fprintf(stdout, "DIMENSION %s '' absolute 1 1 noreset\n", w->name);
1870         }
1871
1872         fprintf(stdout, "CHART apps.pipes '' 'Apps Pipes' 'open pipes' processes apps.pipes stacked 20053 %d\n", update_every);
1873         for (w = target_root; w ; w = w->next) {
1874                 if(w->target || (!w->processes && !w->exposed)) continue;
1875
1876                 fprintf(stdout, "DIMENSION %s '' absolute 1 1 noreset\n", w->name);
1877         }
1878
1879         fprintf(stdout, "CHART netdata.apps_cpu '' 'Apps Plugin CPU' 'milliseconds/s' apps.plugin netdata.apps_cpu stacked 140000 %d\n", update_every);
1880         fprintf(stdout, "DIMENSION user '' incremental 1 %d\n", 1000);
1881         fprintf(stdout, "DIMENSION system '' incremental 1 %d\n", 1000);
1882
1883         fprintf(stdout, "CHART netdata.apps_files '' 'Apps Plugin Files' 'files/s' apps.plugin netdata.apps_files line 140001 %d\n", update_every);
1884         fprintf(stdout, "DIMENSION files '' incremental 1 1\n");
1885         fprintf(stdout, "DIMENSION pids '' absolute 1 1\n");
1886         fprintf(stdout, "DIMENSION fds '' absolute 1 1\n");
1887         fprintf(stdout, "DIMENSION targets '' absolute 1 1\n");
1888
1889         fflush(stdout);
1890 }
1891
1892
1893 // ----------------------------------------------------------------------------
1894 // parse command line arguments
1895
1896 void parse_args(int argc, char **argv)
1897 {
1898         int i, freq = 0;
1899         char *name = NULL;
1900
1901         for(i = 1; i < argc; i++) {
1902                 if(!freq) {
1903                         int n = atoi(argv[i]);
1904                         if(n > 0) {
1905                                 freq = n;
1906                                 continue;
1907                         }
1908                 }
1909
1910                 if(strcmp("debug", argv[i]) == 0) {
1911                         debug = 1;
1912                         debug_flags = 0xffffffff;
1913                         continue;
1914                 }
1915
1916                 if(!name) {
1917                         name = argv[i];
1918                         continue;
1919                 }
1920
1921                 error("Cannot understand option %s", argv[i]);
1922                 exit(1);
1923         }
1924
1925         if(freq > 0) update_every = freq;
1926         if(!name) name = "groups";
1927
1928         if(read_process_groups(name)) {
1929                 error("Cannot read process groups %s", name);
1930                 exit(1);
1931         }
1932 }
1933
1934 int main(int argc, char **argv)
1935 {
1936         // debug_flags = D_PROCFILE;
1937
1938         // set the name for logging
1939         program_name = "apps.plugin";
1940
1941         host_prefix = getenv("NETDATA_HOST_PREFIX");
1942         if(host_prefix == NULL) {
1943                 info("NETDATA_HOST_PREFIX is not passed from netdata");
1944                 host_prefix = "";
1945         }
1946         else info("Found NETDATA_HOST_PREFIX='%s'", host_prefix);
1947
1948         info("starting...");
1949
1950         procfile_adaptive_initial_allocation = 1;
1951
1952         time_t started_t = time(NULL);
1953         time_t current_t;
1954         Hertz = get_hertz();
1955         pid_max = get_pid_max();
1956         processors = get_processors();
1957
1958         parse_args(argc, argv);
1959
1960         all_pids = calloc(sizeof(struct pid_stat *), (size_t) pid_max);
1961         if(!all_pids) {
1962                 error("Cannot allocate %lu bytes of memory.", sizeof(struct pid_stat *) * pid_max);
1963                 printf("DISABLE\n");
1964                 exit(1);
1965         }
1966
1967         unsigned long long counter = 1;
1968         unsigned long long usec = 0, susec = 0;
1969         struct timeval last, now;
1970         gettimeofday(&last, NULL);
1971
1972         for(;1; counter++) {
1973                 if(!update_from_proc()) {
1974                         error("Cannot allocate %lu bytes of memory.", sizeof(struct pid_stat *) * pid_max);
1975                         printf("DISABLE\n");
1976                         exit(1);
1977                 }
1978
1979                 update_statistics();
1980                 show_charts();          // this is smart enough to show only newly added apps, when needed
1981                 show_dimensions();
1982
1983                 if(debug) fprintf(stderr, "apps.plugin: done Loop No %llu\n", counter);
1984                 fflush(NULL);
1985
1986                 gettimeofday(&now, NULL);
1987                 usec = usecdiff(&now, &last) - susec;
1988                 if(debug) fprintf(stderr, "apps.plugin: last loop took %llu usec (worked for %llu, sleeped for %llu).\n", usec + susec, usec, susec);
1989
1990                 // if the last loop took less than half the time
1991                 // wait the rest of the time
1992                 if(usec < (update_every * 1000000ULL / 2)) susec = (update_every * 1000000ULL) - usec;
1993                 else susec = update_every * 1000000ULL / 2;
1994
1995                 usleep((__useconds_t) susec);
1996                 bcopy(&now, &last, sizeof(struct timeval));
1997
1998                 // restart once per day (14400 seconds)
1999                 current_t = time(NULL);
2000                 if(current_t - started_t > 14400) exit(0);
2001         }
2002 }