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