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