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