]> arthur.barton.de Git - netdata.git/blob - src/apps_plugin.c
build: migrate to autotools
[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' (%s)", filename, strerror(errno));
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 };
835
836 static struct file_descriptor *file_descriptor_find(const char *name, uint32_t hash) {
837         struct file_descriptor *result = NULL, tmp;
838         tmp.hash = (hash)?hash:simple_hash(name);
839         tmp.name = name;
840         tmp.count = 0;
841         tmp.pos = 0;
842         tmp.magic = 0x0BADCAFE;
843
844         avl_search(&all_files_index, (avl *)&tmp, file_descriptor_iterator, (avl **)&result);
845         return result;
846 }
847
848 #define file_descriptor_add(fd) avl_insert(&all_files_index, (avl *)(fd))
849 #define file_descriptor_remove(fd) avl_remove(&all_files_index, (avl *)(fd))
850
851 #define FILETYPE_OTHER 0
852 #define FILETYPE_FILE 1
853 #define FILETYPE_PIPE 2
854 #define FILETYPE_SOCKET 3
855 #define FILETYPE_INOTIFY 4
856 #define FILETYPE_EVENTFD 5
857 #define FILETYPE_EVENTPOLL 6
858 #define FILETYPE_TIMERFD 7
859 #define FILETYPE_SIGNALFD 8
860
861 void file_descriptor_not_used(int id)
862 {
863         if(id > 0 && id < all_files_size) {
864                 if(all_files[id].magic != 0x0BADCAFE) {
865                         error("Ignoring request to remove empty file id %d.", id);
866                         return;
867                 }
868
869                 if(debug) fprintf(stderr, "apps.plugin: decreasing slot %d (count = %ld).\n", id, all_files[id].count);
870
871                 if(all_files[id].count > 0) {
872                         all_files[id].count--;
873
874                         if(!all_files[id].count) {
875                                 if(debug) fprintf(stderr, "apps.plugin:   >> slot %d is empty.\n", id);
876                                 file_descriptor_remove(&all_files[id]);
877                                 all_files[id].magic = 0x00000000;
878                                 all_files_len--;
879                         }
880                 }
881                 else
882                         error("Request to decrease counter of fd %d (%s), while the use counter is 0", id, all_files[id].name);
883         }
884         else    error("Request to decrease counter of fd %d, which is outside the array size (1 to %d)", id, all_files_size);
885 }
886
887 unsigned long file_descriptor_find_or_add(const char *name)
888 {
889         static int last_pos = 0;
890         uint32_t hash = simple_hash(name);
891
892         if(debug) fprintf(stderr, "apps.plugin: adding or finding name '%s' with hash %u\n", name, hash);
893
894         struct file_descriptor *fd = file_descriptor_find(name, hash);
895         if(fd) {
896                 // found
897                 if(debug) fprintf(stderr, "apps.plugin:   >> found on slot %ld\n", fd->pos);
898                 fd->count++;
899                 return fd->pos;
900         }
901         // not found
902
903         // check we have enough memory to add it
904         if(!all_files || all_files_len == all_files_size) {
905                 void *old = all_files;
906                 int i;
907
908                 // there is no empty slot
909                 if(debug) fprintf(stderr, "apps.plugin: extending fd array to %d entries\n", all_files_size + FILE_DESCRIPTORS_INCREASE_STEP);
910                 all_files = realloc(all_files, (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP) * sizeof(struct file_descriptor));
911
912                 // if the address changed, we have to rebuild the index
913                 // since all pointers are now invalid
914                 if(old && old != (void *)all_files) {
915                         if(debug) fprintf(stderr, "apps.plugin:   >> re-indexing.\n");
916                         all_files_index.root = NULL;
917                         for(i = 0; i < all_files_size; i++) {
918                                 if(!all_files[i].count) continue;
919                                 file_descriptor_add(&all_files[i]);
920                         }
921                         if(debug) fprintf(stderr, "apps.plugin:   >> re-indexing done.\n");
922                 }
923
924                 for(i = all_files_size; i < (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP); i++) {
925                         all_files[i].count = 0;
926                         all_files[i].name = NULL;
927                         all_files[i].magic = 0x00000000;
928                         all_files[i].pos = i;
929                 }
930
931                 if(!all_files_size) all_files_len = 1;
932                 all_files_size += FILE_DESCRIPTORS_INCREASE_STEP;
933         }
934
935         if(debug) fprintf(stderr, "apps.plugin:   >> searching for empty slot.\n");
936
937         // search for an empty slot
938         int i, c;
939         for(i = 0, c = last_pos ; i < all_files_size ; i++, c++) {
940                 if(c >= all_files_size) c = 0;
941                 if(c == 0) continue;
942
943                 if(!all_files[c].count) {
944                         if(debug) fprintf(stderr, "apps.plugin:   >> Examining slot %d.\n", c);
945
946                         if(all_files[c].magic == 0x0BADCAFE && all_files[c].name && file_descriptor_find(all_files[c].name, all_files[c].hash))
947                                 error("fd on position %d is not cleared properly. It still has %s in it.\n", c, all_files[c].name);
948
949                         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);
950                         if(all_files[c].name) free((void *)all_files[c].name);
951                         all_files[c].name = NULL;
952                         last_pos = c;
953                         break;
954                 }
955         }
956         if(i == all_files_size) {
957                 fatal("We should find an empty slot, but there isn't any");
958                 exit(1);
959         }
960         if(debug) fprintf(stderr, "apps.plugin:   >> updating slot %d.\n", c);
961
962         all_files_len++;
963
964         // else we have an empty slot in 'c'
965
966         int type = FILETYPE_OTHER;
967         if(name[0] == '/') type = FILETYPE_FILE;
968         else if(strncmp(name, "pipe:", 5) == 0) type = FILETYPE_PIPE;
969         else if(strncmp(name, "socket:", 7) == 0) type = FILETYPE_SOCKET;
970         else if(strcmp(name, "anon_inode:inotify") == 0 || strcmp(name, "inotify") == 0) type = FILETYPE_INOTIFY;
971         else if(strcmp(name, "anon_inode:[eventfd]") == 0) type = FILETYPE_EVENTFD;
972         else if(strcmp(name, "anon_inode:[eventpoll]") == 0) type = FILETYPE_EVENTPOLL;
973         else if(strcmp(name, "anon_inode:[timerfd]") == 0) type = FILETYPE_TIMERFD;
974         else if(strcmp(name, "anon_inode:[signalfd]") == 0) type = FILETYPE_SIGNALFD;
975         else if(strncmp(name, "anon_inode:", 11) == 0) {
976                 if(debug) fprintf(stderr, "apps.plugin: FIXME: unknown anonymous inode: %s\n", name);
977                 type = FILETYPE_OTHER;
978         }
979         else {
980                 if(debug) fprintf(stderr, "apps.plugin: FIXME: cannot understand linkname: %s\n", name);
981                 type = FILETYPE_OTHER;
982         }
983
984         all_files[c].name = strdup(name);
985         all_files[c].hash = hash;
986         all_files[c].type = type;
987         all_files[c].pos  = c;
988         all_files[c].count = 1;
989         all_files[c].magic = 0x0BADCAFE;
990
991         file_descriptor_add(&all_files[c]);
992
993         if(debug) fprintf(stderr, "apps.plugin: using fd position %d (name: %s)\n", c, all_files[c].name);
994
995         return c;
996 }
997
998
999 // 1. read all files in /proc
1000 // 2. for each numeric directory:
1001 //    i.   read /proc/pid/stat
1002 //    ii.  read /proc/pid/statm
1003 //    iii. read /proc/pid/io (requires root access)
1004 //    iii. read the entries in directory /proc/pid/fd (requires root access)
1005 //         for each entry:
1006 //         a. find or create a struct file_descriptor
1007 //         b. cleanup any old/unused file_descriptors
1008
1009 // after all these, some pids may be linked to targets, while others may not
1010
1011 // in case of errors, only 1 every 1000 errors is printed
1012 // to avoid filling up all disk space
1013 // if debug is enabled, all errors are printed
1014
1015 int update_from_proc(void)
1016 {
1017         static long count_errors = 0;
1018
1019         char filename[FILENAME_MAX+1];
1020         DIR *dir = opendir("/proc");
1021         if(!dir) return 0;
1022
1023         struct dirent *file = NULL;
1024         struct pid_stat *p = NULL;
1025
1026         // mark them all as un-updated
1027         all_pids_count = 0;
1028         for(p = root_of_pids; p ; p = p->next) {
1029                 all_pids_count++;
1030                 p->parent = NULL;
1031                 p->updated = 0;
1032                 p->childs = 0;
1033                 p->merged = 0;
1034                 p->new_entry = 0;
1035         }
1036
1037         while((file = readdir(dir))) {
1038                 char *endptr = file->d_name;
1039                 pid_t pid = strtoul(file->d_name, &endptr, 10);
1040                 if(pid <= 0 || pid > pid_max || endptr == file->d_name || *endptr != '\0') continue;
1041
1042                 p = get_pid_entry(pid);
1043                 if(!p) continue;
1044
1045                 // --------------------------------------------------------------------
1046                 // /proc/<pid>/stat
1047
1048                 if(read_proc_pid_stat(p)) {
1049                         if(!count_errors++ || debug || (p->target && p->target->debug))
1050                                 error("Cannot process /proc/%d/stat", pid);
1051
1052                         continue;
1053                 }
1054                 if(p->ppid < 0 || p->ppid > pid_max) p->ppid = 0;
1055
1056
1057                 // --------------------------------------------------------------------
1058                 // /proc/<pid>/statm
1059
1060                 if(read_proc_pid_statm(p)) {
1061                         if(!count_errors++ || debug || (p->target && p->target->debug))
1062                                 error("Cannot process /proc/%d/statm", pid);
1063
1064                         continue;
1065                 }
1066
1067
1068                 // --------------------------------------------------------------------
1069                 // /proc/<pid>/io
1070
1071                 if(read_proc_pid_io(p)) {
1072                         if(!count_errors++ || debug || (p->target && p->target->debug))
1073                                 error("Cannot process /proc/%d/io", pid);
1074
1075                         continue;
1076                 }
1077
1078                 // --------------------------------------------------------------------
1079                 // link it
1080
1081                 // check if it is target
1082                 // we do this only once, the first time this pid is loaded
1083                 if(p->new_entry) {
1084                         if(debug) fprintf(stderr, "apps.plugin: \tJust added %s\n", p->comm);
1085
1086                         struct target *w;
1087                         for(w = target_root; w ; w = w->next) {
1088                                 // if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \t\tcomparing '%s' with '%s'\n", w->compare, p->comm);
1089
1090                                 if(strcmp(w->compare, p->comm) == 0) {
1091                                         if(w->target) p->target = w->target;
1092                                         else p->target = w;
1093
1094                                         if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \t\t%s linked to target %s\n", p->comm, p->target->name);
1095                                 }
1096                         }
1097                 }
1098
1099                 // --------------------------------------------------------------------
1100                 // /proc/<pid>/fd
1101
1102                 snprintf(filename, FILENAME_MAX, "/proc/%s/fd", file->d_name);
1103                 DIR *fds = opendir(filename);
1104                 if(fds) {
1105                         int c;
1106                         struct dirent *de;
1107                         char fdname[FILENAME_MAX + 1];
1108                         char linkname[FILENAME_MAX + 1];
1109
1110                         // make the array negative
1111                         for(c = 0 ; c < p->fds_size ; c++) p->fds[c] = -p->fds[c];
1112
1113                         while((de = readdir(fds))) {
1114                                 if(strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) continue;
1115
1116                                 // check if the fds array is small
1117                                 int fdid = atol(de->d_name);
1118                                 if(fdid < 0) continue;
1119                                 if(fdid >= p->fds_size) {
1120                                         // it is small, extend it
1121                                         if(debug) fprintf(stderr, "apps.plugin: extending fd memory slots for %s from %d to %d\n", p->comm, p->fds_size, fdid + 100);
1122                                         p->fds = realloc(p->fds, (fdid + 100) * sizeof(int));
1123                                         if(!p->fds) {
1124                                                 error("Cannot re-allocate fds for %s", p->comm);
1125                                                 break;
1126                                         }
1127
1128                                         // and initialize it
1129                                         for(c = p->fds_size ; c < (fdid + 100) ; c++) p->fds[c] = 0;
1130                                         p->fds_size = fdid + 100;
1131                                 }
1132
1133                                 if(p->fds[fdid] == 0) {
1134                                         // we don't know this fd, get it
1135
1136                                         sprintf(fdname, "/proc/%s/fd/%s", file->d_name, de->d_name);
1137                                         int l = readlink(fdname, linkname, FILENAME_MAX);
1138                                         if(l == -1) {
1139                                                 if(debug || (p->target && p->target->debug)) {
1140                                                         if(!count_errors++ || debug || (p->target && p->target->debug))
1141                                                                 error("Cannot read link %s", fdname);
1142                                                 }
1143                                                 continue;
1144                                         }
1145                                         linkname[l] = '\0';
1146                                         file_counter++;
1147
1148                                         // if another process already has this, we will get
1149                                         // the same id
1150                                         p->fds[fdid] = file_descriptor_find_or_add(linkname);
1151                                 }
1152
1153                                 // else make it positive again, we need it
1154                                 // of course, the actual file may have changed, but we don't care so much
1155                                 // FIXME: we could compare the inode as returned by readdir direct structure
1156                                 else p->fds[fdid] = -p->fds[fdid];
1157                         }
1158                         closedir(fds);
1159
1160                         // remove all the negative file descriptors
1161                         for(c = 0 ; c < p->fds_size ; c++) if(p->fds[c] < 0) {
1162                                 file_descriptor_not_used(-p->fds[c]);
1163                                 p->fds[c] = 0;
1164                         }
1165                 }
1166
1167                 // --------------------------------------------------------------------
1168                 // done!
1169
1170                 // mark it as updated
1171                 p->updated = 1;
1172         }
1173         if(count_errors > 1000) {
1174                 error("%ld more errors encountered\n", count_errors - 1);
1175                 count_errors = 0;
1176         }
1177
1178         closedir(dir);
1179
1180         return 1;
1181 }
1182
1183
1184 // ----------------------------------------------------------------------------
1185 // update statistics on the targets
1186
1187 // 1. link all childs to their parents
1188 // 2. go from bottom to top, marking as merged all childs to their parents
1189 //    this step links all parents without a target to the child target, if any
1190 // 3. link all top level processes (the ones not merged) to the default target
1191 // 4. go from top to bottom, linking all childs without a target, to their parent target
1192 //    after this step, all processes have a target
1193 // [5. for each killed pid (updated = 0), remove its usage from its target]
1194 // 6. zero all targets
1195 // 7. concentrate all values on the targets
1196 // 8. remove all killed processes
1197 // 9. find the unique file count for each target
1198
1199 void update_statistics(void)
1200 {
1201         int c;
1202         struct pid_stat *p = NULL;
1203
1204         // link all parents and update childs count
1205         for(p = root_of_pids; p ; p = p->next) {
1206                 if(p->ppid > 0 && p->ppid <= pid_max && all_pids[p->ppid]) {
1207                         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);
1208                         
1209                         p->parent = all_pids[p->ppid];
1210                         p->parent->childs++;
1211                 }
1212                 else if(p->ppid != 0) error("pid %d %s states parent %d, but the later does not exist.", p->pid, p->comm, p->ppid);
1213         }
1214
1215         // find all the procs with 0 childs and merge them to their parents
1216         // repeat, until nothing more can be done.
1217         int found = 1;
1218         while(found) {
1219                 found = 0;
1220                 for(p = root_of_pids; p ; p = p->next) {
1221                         // if this process does not have any childs, and
1222                         // is not already merged, and
1223                         // its parent has childs waiting to be merged, and
1224                         // 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
1225                         // and its parent is not init
1226                         // then... merge them!
1227                         if(!p->childs && !p->merged && p->parent && p->parent->childs && (p->target == p->parent->target || !p->parent->target || !p->target) && p->ppid != 1) {
1228                                 p->parent->childs--;
1229                                 p->merged = 1;
1230
1231                                 // the parent inherits the child's target, if it does not have a target itself
1232                                 if(p->target && !p->parent->target) {
1233                                         p->parent->target = p->target;
1234                                         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);
1235                                 }
1236
1237                                 found++;
1238                         }
1239                 }
1240                 if(debug) fprintf(stderr, "apps.plugin: merged %d processes\n", found);
1241         }
1242
1243         // give a default target on all top level processes
1244         // init goes always to default target
1245         if(all_pids[1]) all_pids[1]->target = default_target;
1246
1247         for(p = root_of_pids; p ; p = p->next) {
1248                 // if the process is not merged itself
1249                 // then is is a top level process
1250                 if(!p->merged && !p->target) p->target = default_target;
1251
1252 #ifdef INCLUDE_CHILDS
1253                 // by the way, update the diffs
1254                 // will be used later for substracting killed process times
1255                 p->diff_cutime = p->utime - p->cutime;
1256                 p->diff_cstime = p->stime - p->cstime;
1257                 p->diff_cminflt = p->minflt - p->cminflt;
1258                 p->diff_cmajflt = p->majflt - p->cmajflt;
1259 #endif
1260         }
1261
1262         // give a target to all merged child processes
1263         found = 1;
1264         while(found) {
1265                 found = 0;
1266                 for(p = root_of_pids; p ; p = p->next) {
1267                         if(!p->target && p->merged && p->parent && p->parent->target) {
1268                                 p->target = p->parent->target;
1269                                 found++;
1270                         }
1271                 }
1272         }
1273
1274 #ifdef INCLUDE_CHILDS
1275         // for each killed process, remove its values from the parents
1276         // sums (we had already added them in a previous loop)
1277         for(p = root_of_pids; p ; p = p->next) {
1278                 if(p->updated) continue;
1279
1280                 if(debug) fprintf(stderr, "apps.plugin: UNMERGING %d %s\n", p->pid, p->comm);
1281
1282                 unsigned long long diff_utime = p->utime + p->cutime + p->fix_cutime;
1283                 unsigned long long diff_stime = p->stime + p->cstime + p->fix_cstime;
1284                 unsigned long long diff_minflt = p->minflt + p->cminflt + p->fix_cminflt;
1285                 unsigned long long diff_majflt = p->majflt + p->cmajflt + p->fix_cmajflt;
1286
1287                 struct pid_stat *t = p;
1288                 while((t = t->parent)) {
1289                         if(!t->updated) continue;
1290
1291                         unsigned long long x;
1292                         if(diff_utime && t->diff_cutime) {
1293                                 x = (t->diff_cutime < diff_utime)?t->diff_cutime:diff_utime;
1294                                 diff_utime -= x;
1295                                 t->diff_cutime -= x;
1296                                 t->fix_cutime += x;
1297                                 if(debug) fprintf(stderr, "apps.plugin: \t cutime %llu from %d %s %s\n", x, t->pid, t->comm, t->target->name);
1298                         }
1299                         if(diff_stime && t->diff_cstime) {
1300                                 x = (t->diff_cstime < diff_stime)?t->diff_cstime:diff_stime;
1301                                 diff_stime -= x;
1302                                 t->diff_cstime -= x;
1303                                 t->fix_cstime += x;
1304                                 if(debug) fprintf(stderr, "apps.plugin: \t cstime %llu from %d %s %s\n", x, t->pid, t->comm, t->target->name);
1305                         }
1306                         if(diff_minflt && t->diff_cminflt) {
1307                                 x = (t->diff_cminflt < diff_minflt)?t->diff_cminflt:diff_minflt;
1308                                 diff_minflt -= x;
1309                                 t->diff_cminflt -= x;
1310                                 t->fix_cminflt += x;
1311                                 if(debug) fprintf(stderr, "apps.plugin: \t cminflt %llu from %d %s %s\n", x, t->pid, t->comm, t->target->name);
1312                         }
1313                         if(diff_majflt && t->diff_cmajflt) {
1314                                 x = (t->diff_cmajflt < diff_majflt)?t->diff_cmajflt:diff_majflt;
1315                                 diff_majflt -= x;
1316                                 t->diff_cmajflt -= x;
1317                                 t->fix_cmajflt += x;
1318                                 if(debug) fprintf(stderr, "apps.plugin: \t cmajflt %llu from %d %s %s\n", x, t->pid, t->comm, t->target->name);
1319                         }
1320                 }
1321
1322                 if(diff_utime) error("Cannot fix up utime %llu", diff_utime);
1323                 if(diff_stime) error("Cannot fix up stime %llu", diff_stime);
1324                 if(diff_minflt) error("Cannot fix up minflt %llu", diff_minflt);
1325                 if(diff_majflt) error("Cannot fix up majflt %llu", diff_majflt);
1326         }
1327 #endif
1328
1329         // zero all the targets
1330         targets = 0;
1331         struct target *w;
1332         for (w = target_root; w ; w = w->next) {
1333                 targets++;
1334
1335                 w->fds = calloc(sizeof(int), all_files_size);
1336                 if(!w->fds)
1337                         error("Cannot allocate memory for fds in %s", w->name);
1338         
1339                 w->minflt = 0;
1340                 w->majflt = 0;
1341                 w->utime = 0;
1342                 w->stime = 0;
1343                 w->cminflt = 0;
1344                 w->cmajflt = 0;
1345                 w->cutime = 0;
1346                 w->cstime = 0;
1347                 w->num_threads = 0;
1348                 w->rss = 0;
1349                 w->processes = 0;
1350
1351                 w->statm_size = 0;
1352                 w->statm_resident = 0;
1353                 w->statm_share = 0;
1354                 w->statm_text = 0;
1355                 w->statm_lib = 0;
1356                 w->statm_data = 0;
1357                 w->statm_dirty = 0;
1358
1359                 w->io_logical_bytes_read = 0;
1360                 w->io_logical_bytes_written = 0;
1361                 w->io_read_calls = 0;
1362                 w->io_write_calls = 0;
1363                 w->io_storage_bytes_read = 0;
1364                 w->io_storage_bytes_written = 0;
1365                 w->io_cancelled_write_bytes = 0;
1366         }
1367
1368 #ifdef INCLUDE_CHILDS
1369         if(debug) walk_down(0, 1);
1370 #endif
1371
1372         // concentrate everything on the targets
1373         for(p = root_of_pids; p ; p = p->next) {
1374                 if(!p->target) {
1375                         error("pid %d %s was left without a target!", p->pid, p->comm);
1376                         continue;
1377                 }
1378
1379                 if(p->updated) {
1380                         p->target->cutime += p->cutime; // - p->fix_cutime;
1381                         p->target->cstime += p->cstime; // - p->fix_cstime;
1382                         p->target->cminflt += p->cminflt; // - p->fix_cminflt;
1383                         p->target->cmajflt += p->cmajflt; // - p->fix_cmajflt;
1384
1385                         p->target->utime += p->utime; //+ (p->pid != 1)?(p->cutime - p->fix_cutime):0;
1386                         p->target->stime += p->stime; //+ (p->pid != 1)?(p->cstime - p->fix_cstime):0;
1387                         p->target->minflt += p->minflt; //+ (p->pid != 1)?(p->cminflt - p->fix_cminflt):0;
1388                         p->target->majflt += p->majflt; //+ (p->pid != 1)?(p->cmajflt - p->fix_cmajflt):0;
1389
1390                         //if(p->num_threads < 0)
1391                         //      error("Negative threads number for pid '%s' (%d): %d", p->comm, p->pid, p->num_threads);
1392
1393                         //if(p->num_threads > 10000)
1394                         //      error("Excessive threads number for pid '%s' (%d): %d", p->comm, p->pid, p->num_threads);
1395
1396                         p->target->num_threads += p->num_threads;
1397                         p->target->rss += p->rss;
1398
1399                         p->target->statm_size += p->statm_size;
1400                         p->target->statm_resident += p->statm_resident;
1401                         p->target->statm_share += p->statm_share;
1402                         p->target->statm_text += p->statm_text;
1403                         p->target->statm_lib += p->statm_lib;
1404                         p->target->statm_data += p->statm_data;
1405                         p->target->statm_dirty += p->statm_dirty;
1406
1407                         p->target->io_logical_bytes_read += p->io_logical_bytes_read;
1408                         p->target->io_logical_bytes_written += p->io_logical_bytes_written;
1409                         p->target->io_read_calls += p->io_read_calls;
1410                         p->target->io_write_calls += p->io_write_calls;
1411                         p->target->io_storage_bytes_read += p->io_storage_bytes_read;
1412                         p->target->io_storage_bytes_written += p->io_storage_bytes_written;
1413                         p->target->io_cancelled_write_bytes += p->io_cancelled_write_bytes;
1414
1415                         p->target->processes++;
1416
1417                         for(c = 0; c < p->fds_size ;c++) {
1418                                 if(p->fds[c] == 0) continue;
1419                                 if(p->fds[c] < all_files_size) {
1420                                         if(p->target->fds) p->target->fds[p->fds[c]]++;
1421                                 }
1422                                 else
1423                                         error("Invalid fd number %d", p->fds[c]);
1424                         }
1425
1426                         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);
1427
1428 /*                      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);
1429                         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);
1430                         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);
1431                         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);
1432                         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);
1433                         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);
1434                         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);
1435                         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);
1436 */
1437 #ifdef INCLUDE_CHILDS
1438                         p->old_utime = p->utime;
1439                         p->old_cutime = p->cutime;
1440                         p->old_stime = p->stime;
1441                         p->old_cstime = p->cstime;
1442                         p->old_minflt = p->minflt;
1443                         p->old_majflt = p->majflt;
1444                         p->old_cminflt = p->cminflt;
1445                         p->old_cmajflt = p->cmajflt;
1446 #endif
1447                 }
1448                 else {
1449                         // since the process has exited, the user
1450                         // will see a drop in our charts, because the incremental
1451                         // values of this process will not be there
1452
1453                         // add them to the fix_* values and they will be added to
1454                         // the reported values, so that the report goes steady
1455                         p->target->fix_minflt += p->minflt;
1456                         p->target->fix_majflt += p->majflt;
1457                         p->target->fix_utime += p->utime;
1458                         p->target->fix_stime += p->stime;
1459                         p->target->fix_cminflt += p->cminflt;
1460                         p->target->fix_cmajflt += p->cmajflt;
1461                         p->target->fix_cutime += p->cutime;
1462                         p->target->fix_cstime += p->cstime;
1463
1464                         p->target->fix_io_logical_bytes_read += p->io_logical_bytes_read;
1465                         p->target->fix_io_logical_bytes_written += p->io_logical_bytes_written;
1466                         p->target->fix_io_read_calls += p->io_read_calls;
1467                         p->target->fix_io_write_calls += p->io_write_calls;
1468                         p->target->fix_io_storage_bytes_read += p->io_storage_bytes_read;
1469                         p->target->fix_io_storage_bytes_written += p->io_storage_bytes_written;
1470                         p->target->fix_io_cancelled_write_bytes += p->io_cancelled_write_bytes;
1471                 }
1472         }
1473
1474 //      fprintf(stderr, "\n");
1475         // cleanup all un-updated processed (exited, killed, etc)
1476         for(p = root_of_pids; p ;) {
1477                 if(!p->updated) {
1478 //                      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);
1479                         
1480                         for(c = 0 ; c < p->fds_size ; c++) if(p->fds[c] > 0) {
1481                                 file_descriptor_not_used(p->fds[c]);
1482                                 p->fds[c] = 0;
1483                         }
1484
1485                         pid_t r = p->pid;
1486                         p = p->next;
1487                         del_pid_entry(r);
1488                 }
1489                 else p = p->next;
1490         }
1491
1492         for (w = target_root; w ; w = w->next) {
1493                 w->openfiles = 0;
1494                 w->openpipes = 0;
1495                 w->opensockets = 0;
1496                 w->openinotifies = 0;
1497                 w->openeventfds = 0;
1498                 w->opentimerfds = 0;
1499                 w->opensignalfds = 0;
1500                 w->openeventpolls = 0;
1501                 w->openother = 0;
1502
1503                 for(c = 1; c < all_files_size ;c++) {
1504                         if(w->fds && w->fds[c] > 0) switch(all_files[c].type) {
1505                                 case FILETYPE_FILE:
1506                                         w->openfiles++;
1507                                         break;
1508
1509                                 case FILETYPE_PIPE:
1510                                         w->openpipes++;
1511                                         break;
1512
1513                                 case FILETYPE_SOCKET:
1514                                         w->opensockets++;
1515                                         break;
1516
1517                                 case FILETYPE_INOTIFY:
1518                                         w->openinotifies++;
1519                                         break;
1520
1521                                 case FILETYPE_EVENTFD:
1522                                         w->openeventfds++;
1523                                         break;
1524
1525                                 case FILETYPE_TIMERFD:
1526                                         w->opentimerfds++;
1527                                         break;
1528
1529                                 case FILETYPE_SIGNALFD:
1530                                         w->opensignalfds++;
1531                                         break;
1532
1533                                 case FILETYPE_EVENTPOLL:
1534                                         w->openeventpolls++;
1535                                         break;
1536
1537                                 default:
1538                                         w->openother++;
1539                         }
1540                 }
1541
1542                 free(w->fds);
1543                 w->fds = NULL;
1544         }
1545 }
1546
1547 // ----------------------------------------------------------------------------
1548 // update chart dimensions
1549
1550 void show_dimensions(void)
1551 {
1552         static struct timeval last = { 0, 0 };
1553         static struct rusage me_last;
1554
1555         struct target *w;
1556         struct timeval now;
1557         struct rusage me;
1558
1559         unsigned long long usec;
1560         unsigned long long cpuuser;
1561         unsigned long long cpusyst;
1562
1563         if(!last.tv_sec) {
1564                 gettimeofday(&last, NULL);
1565                 getrusage(RUSAGE_SELF, &me_last);
1566
1567                 // the first time, give a zero to allow
1568                 // netdata calibrate to the current time
1569                 // usec = update_every * 1000000ULL;
1570                 usec = 0ULL;
1571                 cpuuser = 0;
1572                 cpusyst = 0;
1573         }
1574         else {
1575                 gettimeofday(&now, NULL);
1576                 getrusage(RUSAGE_SELF, &me);
1577
1578                 usec = usecdiff(&now, &last);
1579                 cpuuser = me.ru_utime.tv_sec * 1000000ULL + me.ru_utime.tv_usec;
1580                 cpusyst = me.ru_stime.tv_sec * 1000000ULL + me.ru_stime.tv_usec;
1581
1582                 bcopy(&now, &last, sizeof(struct timeval));
1583                 bcopy(&me, &me_last, sizeof(struct rusage));
1584         }
1585
1586         fprintf(stdout, "BEGIN apps.cpu %llu\n", usec);
1587         for (w = target_root; w ; w = w->next) {
1588                 if(w->target || (!w->processes && !w->exposed)) continue;
1589
1590                 fprintf(stdout, "SET %s = %llu\n", w->name, w->utime + w->stime + w->fix_utime + w->fix_stime);
1591         }
1592         fprintf(stdout, "END\n");
1593
1594         fprintf(stdout, "BEGIN apps.cpu_user %llu\n", usec);
1595         for (w = target_root; w ; w = w->next) {
1596                 if(w->target || (!w->processes && !w->exposed)) continue;
1597
1598                 fprintf(stdout, "SET %s = %llu\n", w->name, w->utime + w->fix_utime);
1599         }
1600         fprintf(stdout, "END\n");
1601
1602         fprintf(stdout, "BEGIN apps.cpu_system %llu\n", usec);
1603         for (w = target_root; w ; w = w->next) {
1604                 if(w->target || (!w->processes && !w->exposed)) continue;
1605
1606                 fprintf(stdout, "SET %s = %llu\n", w->name, w->stime + w->fix_stime);
1607         }
1608         fprintf(stdout, "END\n");
1609
1610         fprintf(stdout, "BEGIN apps.threads %llu\n", usec);
1611         for (w = target_root; w ; w = w->next) {
1612                 if(w->target || (!w->processes && !w->exposed)) continue;
1613
1614                 fprintf(stdout, "SET %s = %llu\n", w->name, w->num_threads);
1615         }
1616         fprintf(stdout, "END\n");
1617
1618         fprintf(stdout, "BEGIN apps.processes %llu\n", usec);
1619         for (w = target_root; w ; w = w->next) {
1620                 if(w->target || (!w->processes && !w->exposed)) continue;
1621
1622                 fprintf(stdout, "SET %s = %lu\n", w->name, w->processes);
1623         }
1624         fprintf(stdout, "END\n");
1625
1626         fprintf(stdout, "BEGIN apps.mem %llu\n", usec);
1627         for (w = target_root; w ; w = w->next) {
1628                 if(w->target || (!w->processes && !w->exposed)) continue;
1629
1630                 fprintf(stdout, "SET %s = %lld\n", w->name, (long long)w->statm_resident - (long long)w->statm_share);
1631         }
1632         fprintf(stdout, "END\n");
1633
1634         fprintf(stdout, "BEGIN apps.minor_faults %llu\n", usec);
1635         for (w = target_root; w ; w = w->next) {
1636                 if(w->target || (!w->processes && !w->exposed)) continue;
1637
1638                 fprintf(stdout, "SET %s = %llu\n", w->name, w->minflt + w->fix_minflt);
1639         }
1640         fprintf(stdout, "END\n");
1641
1642         fprintf(stdout, "BEGIN apps.major_faults %llu\n", usec);
1643         for (w = target_root; w ; w = w->next) {
1644                 if(w->target || (!w->processes && !w->exposed)) continue;
1645
1646                 fprintf(stdout, "SET %s = %llu\n", w->name, w->majflt + w->fix_majflt);
1647         }
1648         fprintf(stdout, "END\n");
1649
1650         fprintf(stdout, "BEGIN apps.lreads %llu\n", usec);
1651         for (w = target_root; w ; w = w->next) {
1652                 if(w->target || (!w->processes && !w->exposed)) continue;
1653
1654                 fprintf(stdout, "SET %s = %llu\n", w->name, w->io_logical_bytes_read);
1655         }
1656         fprintf(stdout, "END\n");
1657
1658         fprintf(stdout, "BEGIN apps.lwrites %llu\n", usec);
1659         for (w = target_root; w ; w = w->next) {
1660                 if(w->target || (!w->processes && !w->exposed)) continue;
1661
1662                 fprintf(stdout, "SET %s = %llu\n", w->name, w->io_logical_bytes_written);
1663         }
1664         fprintf(stdout, "END\n");
1665
1666         fprintf(stdout, "BEGIN apps.preads %llu\n", usec);
1667         for (w = target_root; w ; w = w->next) {
1668                 if(w->target || (!w->processes && !w->exposed)) continue;
1669
1670                 fprintf(stdout, "SET %s = %llu\n", w->name, w->io_storage_bytes_read);
1671         }
1672         fprintf(stdout, "END\n");
1673
1674         fprintf(stdout, "BEGIN apps.pwrites %llu\n", usec);
1675         for (w = target_root; w ; w = w->next) {
1676                 if(w->target || (!w->processes && !w->exposed)) continue;
1677
1678                 fprintf(stdout, "SET %s = %llu\n", w->name, w->io_storage_bytes_written);
1679         }
1680         fprintf(stdout, "END\n");
1681
1682         fprintf(stdout, "BEGIN apps.files %llu\n", usec);
1683         for (w = target_root; w ; w = w->next) {
1684                 if(w->target || (!w->processes && !w->exposed)) continue;
1685
1686                 fprintf(stdout, "SET %s = %llu\n", w->name, w->openfiles);
1687         }
1688         fprintf(stdout, "END\n");
1689
1690         fprintf(stdout, "BEGIN apps.sockets %llu\n", usec);
1691         for (w = target_root; w ; w = w->next) {
1692                 if(w->target || (!w->processes && !w->exposed)) continue;
1693
1694                 fprintf(stdout, "SET %s = %llu\n", w->name, w->opensockets);
1695         }
1696         fprintf(stdout, "END\n");
1697
1698         fprintf(stdout, "BEGIN apps.pipes %llu\n", usec);
1699         for (w = target_root; w ; w = w->next) {
1700                 if(w->target || (!w->processes && !w->exposed)) continue;
1701
1702                 fprintf(stdout, "SET %s = %llu\n", w->name, w->openpipes);
1703         }
1704         fprintf(stdout, "END\n");
1705
1706         fprintf(stdout, "BEGIN netdata.apps_cpu %llu\n", usec);
1707         fprintf(stdout, "SET user = %llu\n", cpuuser);
1708         fprintf(stdout, "SET system = %llu\n", cpusyst);
1709         fprintf(stdout, "END\n");
1710
1711         fprintf(stdout, "BEGIN netdata.apps_files %llu\n", usec);
1712         fprintf(stdout, "SET files = %llu\n", file_counter);
1713         fprintf(stdout, "SET pids = %ld\n", all_pids_count);
1714         fprintf(stdout, "SET fds = %d\n", all_files_len);
1715         fprintf(stdout, "SET targets = %ld\n", targets);
1716         fprintf(stdout, "END\n");
1717
1718         fflush(stdout);
1719 }
1720
1721
1722 // ----------------------------------------------------------------------------
1723 // generate the charts
1724
1725 void show_charts(void)
1726 {
1727         struct target *w;
1728         int newly_added = 0;
1729
1730         for(w = target_root ; w ; w = w->next)
1731                 if(!w->exposed && w->processes) {
1732                         newly_added++;
1733                         w->exposed = 1;
1734                         if(debug || w->debug) fprintf(stderr, "apps.plugin: %s just added - regenerating charts.\n", w->name);
1735                 }
1736
1737         // nothing more to show
1738         if(!newly_added) return;
1739
1740         // we have something new to show
1741         // update the charts
1742         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);
1743         for (w = target_root; w ; w = w->next) {
1744                 if(w->target || (!w->processes && !w->exposed)) continue;
1745
1746                 fprintf(stdout, "DIMENSION %s '' incremental 100 %llu %s\n", w->name, (unsigned long long)(Hertz * update_every), w->hidden?"hidden":"");
1747         }
1748
1749         fprintf(stdout, "CHART apps.mem '' 'Apps Dedicated Memory (w/o shared)' 'MB' apps apps stacked 20003 %d\n", update_every);
1750         for (w = target_root; w ; w = w->next) {
1751                 if(w->target || (!w->processes && !w->exposed)) continue;
1752
1753                 fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
1754         }
1755
1756         fprintf(stdout, "CHART apps.threads '' 'Apps Threads' 'threads' apps apps stacked 20005 %d\n", update_every);
1757         for (w = target_root; w ; w = w->next) {
1758                 if(w->target || (!w->processes && !w->exposed)) continue;
1759
1760                 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
1761         }
1762
1763         fprintf(stdout, "CHART apps.processes '' 'Apps Processes' 'processes' apps apps stacked 20004 %d\n", update_every);
1764         for (w = target_root; w ; w = w->next) {
1765                 if(w->target || (!w->processes && !w->exposed)) continue;
1766
1767                 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
1768         }
1769
1770         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);
1771         for (w = target_root; w ; w = w->next) {
1772                 if(w->target || (!w->processes && !w->exposed)) continue;
1773
1774                 fprintf(stdout, "DIMENSION %s '' incremental 100 %llu\n", w->name, Hertz * processors * update_every);
1775         }
1776
1777         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);
1778         for (w = target_root; w ; w = w->next) {
1779                 if(w->target || (!w->processes && !w->exposed)) continue;
1780
1781                 fprintf(stdout, "DIMENSION %s '' incremental 100 %llu\n", w->name, Hertz * processors * update_every);
1782         }
1783
1784         fprintf(stdout, "CHART apps.major_faults '' 'Apps Major Page Faults (swaps in)' 'page faults/s' apps apps stacked 20010 %d\n", update_every);
1785         for (w = target_root; w ; w = w->next) {
1786                 if(w->target || (!w->processes && !w->exposed)) continue;
1787
1788                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d\n", w->name, update_every);
1789         }
1790
1791         fprintf(stdout, "CHART apps.minor_faults '' 'Apps Minor Page Faults' 'page faults/s' apps none stacked 20011 %d\n", update_every);
1792         for (w = target_root; w ; w = w->next) {
1793                 if(w->target || (!w->processes && !w->exposed)) continue;
1794
1795                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d\n", w->name, update_every);
1796         }
1797
1798         fprintf(stdout, "CHART apps.lreads '' 'Apps Disk Logical Reads' 'kilobytes/s' apps none stacked 20042 %d\n", update_every);
1799         for (w = target_root; w ; w = w->next) {
1800                 if(w->target || (!w->processes && !w->exposed)) continue;
1801
1802                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d\n", w->name, 1024 * update_every);
1803         }
1804
1805         fprintf(stdout, "CHART apps.lwrites '' 'Apps I/O Logical Writes' 'kilobytes/s' apps none stacked 20042 %d\n", update_every);
1806         for (w = target_root; w ; w = w->next) {
1807                 if(w->target || (!w->processes && !w->exposed)) continue;
1808
1809                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d\n", w->name, 1024 * update_every);
1810         }
1811
1812         fprintf(stdout, "CHART apps.preads '' 'Apps Disk Reads' 'kilobytes/s' apps apps stacked 20002 %d\n", update_every);
1813         for (w = target_root; w ; w = w->next) {
1814                 if(w->target || (!w->processes && !w->exposed)) continue;
1815
1816                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d\n", w->name, 1024 * update_every);
1817         }
1818
1819         fprintf(stdout, "CHART apps.pwrites '' 'Apps Disk Writes' 'kilobytes/s' apps apps stacked 20002 %d\n", update_every);
1820         for (w = target_root; w ; w = w->next) {
1821                 if(w->target || (!w->processes && !w->exposed)) continue;
1822
1823                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d\n", w->name, 1024 * update_every);
1824         }
1825
1826         fprintf(stdout, "CHART apps.files '' 'Apps Open Files' 'open files' apps apps stacked 20050 %d\n", update_every);
1827         for (w = target_root; w ; w = w->next) {
1828                 if(w->target || (!w->processes && !w->exposed)) continue;
1829
1830                 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
1831         }
1832
1833         fprintf(stdout, "CHART apps.sockets '' 'Apps Open Sockets' 'open sockets' apps apps stacked 20051 %d\n", update_every);
1834         for (w = target_root; w ; w = w->next) {
1835                 if(w->target || (!w->processes && !w->exposed)) continue;
1836
1837                 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
1838         }
1839
1840         fprintf(stdout, "CHART apps.pipes '' 'Apps Pipes' 'open pipes' apps none stacked 20053 %d\n", update_every);
1841         for (w = target_root; w ; w = w->next) {
1842                 if(w->target || (!w->processes && !w->exposed)) continue;
1843
1844                 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
1845         }
1846
1847         fprintf(stdout, "CHART netdata.apps_cpu '' 'Apps Plugin CPU' 'milliseconds/s' netdata netdata stacked 10000 %d\n", update_every);
1848         fprintf(stdout, "DIMENSION user '' incremental 1 %d\n", 1000 * update_every);
1849         fprintf(stdout, "DIMENSION system '' incremental 1 %d\n", 1000 * update_every);
1850
1851         fprintf(stdout, "CHART netdata.apps_files '' 'Apps Plugin Files' 'files/s' netdata netdata line 10001 %d\n", update_every);
1852         fprintf(stdout, "DIMENSION files '' incremental 1 %d\n", update_every);
1853         fprintf(stdout, "DIMENSION pids '' absolute 1 1\n");
1854         fprintf(stdout, "DIMENSION fds '' absolute 1 1\n");
1855         fprintf(stdout, "DIMENSION targets '' absolute 1 1\n");
1856
1857         fflush(stdout);
1858 }
1859
1860
1861 // ----------------------------------------------------------------------------
1862 // parse command line arguments
1863
1864 void parse_args(int argc, char **argv)
1865 {
1866         int i, freq = 0;
1867         char *name = NULL;
1868
1869         for(i = 1; i < argc; i++) {
1870                 if(!freq) {
1871                         int n = atoi(argv[i]);
1872                         if(n > 0) {
1873                                 freq = n;
1874                                 continue;
1875                         }
1876                 }
1877
1878                 if(strcmp("debug", argv[i]) == 0) {
1879                         debug = 1;
1880                         debug_flags = 0xffffffff;
1881                         continue;
1882                 }
1883
1884                 if(!name) {
1885                         name = argv[i];
1886                         continue;
1887                 }
1888
1889                 error("Cannot understand option %s", argv[i]);
1890                 exit(1);
1891         }
1892
1893         if(freq > 0) update_every = freq;
1894         if(!name) name = "groups";
1895
1896         if(read_process_groups(name)) {
1897                 error("Cannot read process groups %s", name);
1898                 exit(1);
1899         }
1900 }
1901
1902 int main(int argc, char **argv)
1903 {
1904         // debug_flags = D_PROCFILE;
1905
1906         // set the name for logging
1907         program_name = "apps.plugin";
1908
1909         info("starting...");
1910
1911         procfile_adaptive_initial_allocation = 1;
1912
1913         unsigned long started_t = time(NULL), current_t;
1914         Hertz = get_hertz();
1915         pid_max = get_pid_max();
1916         processors = get_processors();
1917
1918         parse_args(argc, argv);
1919
1920         all_pids = calloc(sizeof(struct pid_stat *), pid_max);
1921         if(!all_pids) {
1922                 error("Cannot allocate %lu bytes of memory.", sizeof(struct pid_stat *) * pid_max);
1923                 printf("DISABLE\n");
1924                 exit(1);
1925         }
1926
1927         unsigned long long counter = 1;
1928         unsigned long long usec = 0, susec = 0;
1929         struct timeval last, now;
1930         gettimeofday(&last, NULL);
1931
1932         for(;1; counter++) {
1933                 if(!update_from_proc()) {
1934                         error("Cannot allocate %lu bytes of memory.", sizeof(struct pid_stat *) * pid_max);
1935                         printf("DISABLE\n");
1936                         exit(1);
1937                 }
1938
1939                 update_statistics();
1940                 show_charts();          // this is smart enough to show only newly added apps, when needed
1941                 show_dimensions();
1942
1943                 if(debug) fprintf(stderr, "apps.plugin: done Loop No %llu\n", counter);
1944                 fflush(NULL);
1945
1946                 gettimeofday(&now, NULL);
1947                 usec = usecdiff(&now, &last) - susec;
1948                 if(debug) fprintf(stderr, "apps.plugin: last loop took %llu usec (worked for %llu, sleeped for %llu).\n", usec + susec, usec, susec);
1949
1950                 // if the last loop took less than half the time
1951                 // wait the rest of the time
1952                 if(usec < (update_every * 1000000ULL / 2)) susec = (update_every * 1000000ULL) - usec;
1953                 else susec = update_every * 1000000ULL / 2;
1954
1955                 usleep(susec);
1956                 bcopy(&now, &last, sizeof(struct timeval));
1957                 
1958                 current_t = time(NULL);
1959                 if(current_t - started_t > 3600) exit(0);
1960         }
1961 }