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