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