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