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