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