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