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