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