]> arthur.barton.de Git - netdata.git/blob - src/apps_plugin.c
prevent apps.plugin errors when files are not found
[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                 if(errno != ENOENT || debug)
1658                         error("Cannot process %s/proc/%d/stat (command '%s')", host_prefix, pid, p->comm);
1659                 else
1660                         errno = 0;
1661                 // there is no reason to proceed if we cannot get its status
1662                 return;
1663         }
1664
1665         read_proc_pid_ownership(p);
1666
1667         // check its parent pid
1668         if(unlikely(p->ppid < 0 || p->ppid > pid_max)) {
1669                 error("Pid %d (command '%s') states invalid parent pid %d. Using 0.", pid, p->comm, p->ppid);
1670                 p->ppid = 0;
1671         }
1672
1673         // --------------------------------------------------------------------
1674         // /proc/<pid>/io
1675
1676         if(unlikely(read_proc_pid_io(p))) {
1677                 if(errno != ENOENT || debug)
1678                         error("Cannot process %s/proc/%d/io (command '%s')", host_prefix, pid, p->comm);
1679                 else
1680                         errno = 0;
1681         }
1682
1683         // --------------------------------------------------------------------
1684         // /proc/<pid>/statm
1685
1686         if(unlikely(read_proc_pid_statm(p))) {
1687                 if(errno != ENOENT || debug)
1688                         error("Cannot process %s/proc/%d/statm (command '%s')", host_prefix, pid, p->comm);
1689                 else
1690                         errno = 0;
1691                 // there is no reason to proceed if we cannot get its memory status
1692                 return;
1693         }
1694
1695         // --------------------------------------------------------------------
1696         // link it
1697
1698         // check if it is target
1699         // we do this only once, the first time this pid is loaded
1700         if(unlikely(p->new_entry)) {
1701                 // /proc/<pid>/cmdline
1702                 if(likely(proc_pid_cmdline_is_needed)) {
1703                         if(unlikely(read_proc_pid_cmdline(p))) {
1704                                 if(errno != ENOENT || debug)
1705                                         error("Cannot process %s/proc/%d/cmdline (command '%s')", host_prefix, pid, p->comm);
1706                                 else
1707                                         errno = 0;
1708                         }
1709                 }
1710
1711                 if(unlikely(debug))
1712                         fprintf(stderr, "apps.plugin: \tJust added %d (%s)\n", pid, p->comm);
1713
1714                 uint32_t hash = simple_hash(p->comm);
1715                 size_t pclen  = strlen(p->comm);
1716
1717                 struct target *w;
1718                 for(w = apps_groups_root_target; w ; w = w->next) {
1719                         // if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \t\tcomparing '%s' with '%s'\n", w->compare, p->comm);
1720
1721                         // find it - 4 cases:
1722                         // 1. the target is not a pattern
1723                         // 2. the target has the prefix
1724                         // 3. the target has the suffix
1725                         // 4. the target is something inside cmdline
1726                         if(     (!w->starts_with && !w->ends_with && w->comparehash == hash && !strcmp(w->compare, p->comm))
1727                                || (w->starts_with && !w->ends_with && !strncmp(w->compare, p->comm, w->comparelen))
1728                                || (!w->starts_with && w->ends_with && pclen >= w->comparelen && !strcmp(w->compare, &p->comm[pclen - w->comparelen]))
1729                                || (proc_pid_cmdline_is_needed && w->starts_with && w->ends_with && strstr(p->cmdline, w->compare))
1730                                         ) {
1731                                 if(w->target) p->target = w->target;
1732                                 else p->target = w;
1733
1734                                 if(debug || (p->target && p->target->debug))
1735                                         fprintf(stderr, "apps.plugin: \t\t%s linked to target %s\n", p->comm, p->target->name);
1736
1737                                 break;
1738                         }
1739                 }
1740         }
1741
1742         // --------------------------------------------------------------------
1743         // /proc/<pid>/fd
1744
1745         if(unlikely(read_pid_file_descriptors(p))) {
1746                 if(errno != ENOENT || debug)
1747                         error("Cannot process entries in %s/proc/%d/fd (command '%s')", host_prefix, pid, p->comm);
1748                 else
1749                         errno = 0;
1750         }
1751
1752         // --------------------------------------------------------------------
1753         // done!
1754
1755         if(unlikely(debug && include_exited_childs && all_pids_count && p->ppid && all_pids[p->ppid] && !all_pids[p->ppid]->read))
1756                 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);
1757
1758         // mark it as updated
1759         p->updated = 1;
1760         p->keep = 0;
1761         p->keeploops = 0;
1762 }
1763
1764 int collect_data_for_all_processes_from_proc(void) {
1765         struct pid_stat *p = NULL;
1766
1767         if(all_pids_count) {
1768                 // read parents before childs
1769                 // this is needed to prevent a situation where
1770                 // a child is found running, but until we read
1771                 // its parent, it has exited and its parent
1772                 // has accumulated its resources
1773
1774                 long slc = 0;
1775                 for(p = root_of_pids; p ; p = p->next) {
1776                         p->read             = 0;
1777                         p->updated          = 0;
1778                         p->new_entry        = 0;
1779                         p->merged           = 0;
1780                         p->children_count   = 0;
1781                         p->parent           = NULL;
1782
1783                         all_pids_sortlist[slc++] = p->pid;
1784                 }
1785
1786                 if(unlikely(slc != all_pids_count)) {
1787                         error("Internal error: I was thinking I had %ld processes in my arrays, but it seems there are more.", all_pids_count);
1788                         all_pids_count = slc;
1789                 }
1790
1791                 if(include_exited_childs) {
1792                         qsort((void *)all_pids_sortlist, all_pids_count, sizeof(pid_t), compar_pid);
1793                         for(slc = 0; slc < all_pids_count; slc++)
1794                                 collect_data_for_pid(all_pids_sortlist[slc]);
1795                 }
1796         }
1797
1798         char dirname[FILENAME_MAX + 1];
1799
1800         snprintfz(dirname, FILENAME_MAX, "%s/proc", host_prefix);
1801         DIR *dir = opendir(dirname);
1802         if(!dir) return 0;
1803
1804         struct dirent *file = NULL;
1805
1806         while((file = readdir(dir))) {
1807                 char *endptr = file->d_name;
1808                 pid_t pid = (pid_t) strtoul(file->d_name, &endptr, 10);
1809
1810                 // make sure we read a valid number
1811                 if(unlikely(endptr == file->d_name || *endptr != '\0'))
1812                         continue;
1813
1814                 collect_data_for_pid(pid);
1815         }
1816         closedir(dir);
1817
1818         // normally this is done
1819         // however we may have processes exited while we collected values
1820         // so let's find the exited ones
1821         // we do this by collecting the ownership of process
1822         // if we manage to get the ownership, the process still runs
1823
1824         read_proc_stat();
1825         link_all_processes_to_their_parents();
1826         process_exited_processes();
1827
1828         return 1;
1829 }
1830
1831 // ----------------------------------------------------------------------------
1832 // update statistics on the targets
1833
1834 // 1. link all childs to their parents
1835 // 2. go from bottom to top, marking as merged all childs to their parents
1836 //    this step links all parents without a target to the child target, if any
1837 // 3. link all top level processes (the ones not merged) to the default target
1838 // 4. go from top to bottom, linking all childs without a target, to their parent target
1839 //    after this step, all processes have a target
1840 // [5. for each killed pid (updated = 0), remove its usage from its target]
1841 // 6. zero all apps_groups_targets
1842 // 7. concentrate all values on the apps_groups_targets
1843 // 8. remove all killed processes
1844 // 9. find the unique file count for each target
1845 // check: update_apps_groups_statistics()
1846
1847 void cleanup_exited_pids(void) {
1848         int c;
1849         struct pid_stat *p = NULL;
1850
1851         for(p = root_of_pids; p ;) {
1852                 if(!p->updated && (!p->keep || p->keeploops > 0)) {
1853 //                      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);
1854
1855                         if(unlikely(debug && (p->keep || p->keeploops)))
1856                                 fprintf(stderr, " > CLEANUP cannot keep exited process %d (%s) anymore - removing it.\n", p->pid, p->comm);
1857
1858                         for(c = 0 ; c < p->fds_size ; c++) if(p->fds[c] > 0) {
1859                                 file_descriptor_not_used(p->fds[c]);
1860                                 p->fds[c] = 0;
1861                         }
1862
1863                         pid_t r = p->pid;
1864                         p = p->next;
1865                         del_pid_entry(r);
1866                 }
1867                 else {
1868                         if(unlikely(p->keep)) p->keeploops++;
1869                         p->keep = 0;
1870                         p = p->next;
1871                 }
1872         }
1873 }
1874
1875 void apply_apps_groups_targets_inheritance(void) {
1876         struct pid_stat *p = NULL;
1877
1878         // children that do not have a target
1879         // inherit their target from their parent
1880         int found = 1, loops = 0;
1881         while(found) {
1882                 if(unlikely(debug)) loops++;
1883                 found = 0;
1884                 for(p = root_of_pids; p ; p = p->next) {
1885                         // if this process does not have a target
1886                         // and it has a parent
1887                         // and its parent has a target
1888                         // then, set the parent's target to this process
1889                         if(unlikely(!p->target && p->parent && p->parent->target)) {
1890                                 p->target = p->parent->target;
1891                                 found++;
1892
1893                                 if(debug || (p->target && p->target->debug))
1894                                         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);
1895                         }
1896                 }
1897         }
1898
1899         // find all the procs with 0 childs and merge them to their parents
1900         // repeat, until nothing more can be done.
1901         int sortlist = 1;
1902         found = 1;
1903         while(found) {
1904                 if(unlikely(debug)) loops++;
1905                 found = 0;
1906
1907                 for(p = root_of_pids; p ; p = p->next) {
1908                         if(unlikely(!p->sortlist && !p->children_count))
1909                                 p->sortlist = sortlist++;
1910
1911                         // if this process does not have any children
1912                         // and is not already merged
1913                         // and has a parent
1914                         // and its parent has children
1915                         // and the target of this process and its parent is the same, or the parent does not have a target
1916                         // and its parent is not init
1917                         // then, mark them as merged.
1918                         if(unlikely(
1919                                         !p->children_count
1920                                         && !p->merged
1921                                         && p->parent
1922                                         && p->parent->children_count
1923                                         && (p->target == p->parent->target || !p->parent->target)
1924                                         && p->ppid != 1
1925                                 )) {
1926                                 p->parent->children_count--;
1927                                 p->merged = 1;
1928
1929                                 // the parent inherits the child's target, if it does not have a target itself
1930                                 if(unlikely(p->target && !p->parent->target)) {
1931                                         p->parent->target = p->target;
1932
1933                                         if(debug || (p->target && p->target->debug))
1934                                                 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);
1935                                 }
1936
1937                                 found++;
1938                         }
1939                 }
1940
1941                 if(unlikely(debug))
1942                         fprintf(stderr, "apps.plugin: TARGET INHERITANCE: merged %d processes\n", found);
1943         }
1944
1945         // init goes always to default target
1946         if(all_pids[1])
1947                 all_pids[1]->target = apps_groups_default_target;
1948
1949         // give a default target on all top level processes
1950         if(unlikely(debug)) loops++;
1951         for(p = root_of_pids; p ; p = p->next) {
1952                 // if the process is not merged itself
1953                 // then is is a top level process
1954                 if(unlikely(!p->merged && !p->target))
1955                         p->target = apps_groups_default_target;
1956
1957                 // make sure all processes have a sortlist
1958                 if(unlikely(!p->sortlist))
1959                         p->sortlist = sortlist++;
1960         }
1961
1962         if(all_pids[1])
1963                 all_pids[1]->sortlist = sortlist++;
1964
1965         // give a target to all merged child processes
1966         found = 1;
1967         while(found) {
1968                 if(unlikely(debug)) loops++;
1969                 found = 0;
1970                 for(p = root_of_pids; p ; p = p->next) {
1971                         if(unlikely(!p->target && p->merged && p->parent && p->parent->target)) {
1972                                 p->target = p->parent->target;
1973                                 found++;
1974
1975                                 if(debug || (p->target && p->target->debug))
1976                                         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);
1977                         }
1978                 }
1979         }
1980
1981         if(unlikely(debug))
1982                 fprintf(stderr, "apps.plugin: apply_apps_groups_targets_inheritance() made %d loops on the process tree\n", loops);
1983 }
1984
1985 long zero_all_targets(struct target *root) {
1986         struct target *w;
1987         long count = 0;
1988
1989         for (w = root; w ; w = w->next) {
1990                 count++;
1991
1992                 if(w->fds) free(w->fds);
1993                 w->fds = NULL;
1994
1995                 w->minflt = 0;
1996                 w->majflt = 0;
1997                 w->utime = 0;
1998                 w->stime = 0;
1999                 w->gtime = 0;
2000                 w->cminflt = 0;
2001                 w->cmajflt = 0;
2002                 w->cutime = 0;
2003                 w->cstime = 0;
2004                 w->cgtime = 0;
2005                 w->num_threads = 0;
2006                 w->rss = 0;
2007                 w->processes = 0;
2008
2009                 w->statm_size = 0;
2010                 w->statm_resident = 0;
2011                 w->statm_share = 0;
2012                 w->statm_text = 0;
2013                 w->statm_lib = 0;
2014                 w->statm_data = 0;
2015                 w->statm_dirty = 0;
2016
2017                 w->io_logical_bytes_read = 0;
2018                 w->io_logical_bytes_written = 0;
2019                 w->io_read_calls = 0;
2020                 w->io_write_calls = 0;
2021                 w->io_storage_bytes_read = 0;
2022                 w->io_storage_bytes_written = 0;
2023                 w->io_cancelled_write_bytes = 0;
2024         }
2025
2026         return count;
2027 }
2028
2029 void aggregate_pid_on_target(struct target *w, struct pid_stat *p, struct target *o) {
2030         (void)o;
2031
2032         if(unlikely(!w->fds)) {
2033                 w->fds = calloc(sizeof(int), (size_t) all_files_size);
2034                 if(unlikely(!w->fds))
2035                         error("Cannot allocate memory for fds in %s", w->name);
2036         }
2037
2038         if(likely(p->updated)) {
2039                 w->cutime  += p->cutime;
2040                 w->cstime  += p->cstime;
2041                 w->cgtime  += p->cgtime;
2042                 w->cminflt += p->cminflt;
2043                 w->cmajflt += p->cmajflt;
2044
2045                 w->utime  += p->utime;
2046                 w->stime  += p->stime;
2047                 w->gtime  += p->gtime;
2048                 w->minflt += p->minflt;
2049                 w->majflt += p->majflt;
2050
2051                 w->rss += p->rss;
2052
2053                 w->statm_size += p->statm_size;
2054                 w->statm_resident += p->statm_resident;
2055                 w->statm_share += p->statm_share;
2056                 w->statm_text += p->statm_text;
2057                 w->statm_lib += p->statm_lib;
2058                 w->statm_data += p->statm_data;
2059                 w->statm_dirty += p->statm_dirty;
2060
2061                 w->io_logical_bytes_read    += p->io_logical_bytes_read;
2062                 w->io_logical_bytes_written += p->io_logical_bytes_written;
2063                 w->io_read_calls            += p->io_read_calls;
2064                 w->io_write_calls           += p->io_write_calls;
2065                 w->io_storage_bytes_read    += p->io_storage_bytes_read;
2066                 w->io_storage_bytes_written += p->io_storage_bytes_written;
2067                 w->io_cancelled_write_bytes += p->io_cancelled_write_bytes;
2068
2069                 w->processes++;
2070                 w->num_threads += p->num_threads;
2071
2072                 if(likely(w->fds)) {
2073                         int c;
2074                         for(c = 0; c < p->fds_size ;c++) {
2075                                 if(p->fds[c] == 0) continue;
2076
2077                                 if(likely(p->fds[c] < all_files_size)) {
2078                                         if(w->fds) w->fds[p->fds[c]]++;
2079                                 }
2080                                 else
2081                                         error("Invalid fd number %d", p->fds[c]);
2082                         }
2083                 }
2084
2085                 if(unlikely(debug || w->debug))
2086                         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);
2087         }
2088 }
2089
2090 void count_targets_fds(struct target *root) {
2091         int c;
2092         struct target *w;
2093
2094         for (w = root; w ; w = w->next) {
2095                 if(!w->fds) continue;
2096
2097                 w->openfiles = 0;
2098                 w->openpipes = 0;
2099                 w->opensockets = 0;
2100                 w->openinotifies = 0;
2101                 w->openeventfds = 0;
2102                 w->opentimerfds = 0;
2103                 w->opensignalfds = 0;
2104                 w->openeventpolls = 0;
2105                 w->openother = 0;
2106
2107                 for(c = 1; c < all_files_size ;c++) {
2108                         if(w->fds[c] > 0)
2109                                 switch(all_files[c].type) {
2110                                 case FILETYPE_FILE:
2111                                         w->openfiles++;
2112                                         break;
2113
2114                                 case FILETYPE_PIPE:
2115                                         w->openpipes++;
2116                                         break;
2117
2118                                 case FILETYPE_SOCKET:
2119                                         w->opensockets++;
2120                                         break;
2121
2122                                 case FILETYPE_INOTIFY:
2123                                         w->openinotifies++;
2124                                         break;
2125
2126                                 case FILETYPE_EVENTFD:
2127                                         w->openeventfds++;
2128                                         break;
2129
2130                                 case FILETYPE_TIMERFD:
2131                                         w->opentimerfds++;
2132                                         break;
2133
2134                                 case FILETYPE_SIGNALFD:
2135                                         w->opensignalfds++;
2136                                         break;
2137
2138                                 case FILETYPE_EVENTPOLL:
2139                                         w->openeventpolls++;
2140                                         break;
2141
2142                                 default:
2143                                         w->openother++;
2144                         }
2145                 }
2146
2147                 free(w->fds);
2148                 w->fds = NULL;
2149         }
2150 }
2151
2152 void calculate_netdata_statistics(void) {
2153         apply_apps_groups_targets_inheritance();
2154
2155         zero_all_targets(users_root_target);
2156         zero_all_targets(groups_root_target);
2157         apps_groups_targets = zero_all_targets(apps_groups_root_target);
2158
2159         // this has to be done, before the cleanup
2160         struct pid_stat *p = NULL;
2161         struct target *w = NULL, *o = NULL;
2162
2163         // concentrate everything on the apps_groups_targets
2164         for(p = root_of_pids; p ; p = p->next) {
2165
2166                 // --------------------------------------------------------------------
2167                 // apps_groups targets
2168                 if(likely(p->target))
2169                         aggregate_pid_on_target(p->target, p, NULL);
2170                 else
2171                         error("pid %d %s was left without a target!", p->pid, p->comm);
2172
2173
2174                 // --------------------------------------------------------------------
2175                 // user targets
2176                 o = p->user_target;
2177                 if(likely(p->user_target && p->user_target->uid == p->uid))
2178                         w = p->user_target;
2179                 else {
2180                         if(unlikely(debug && p->user_target))
2181                                         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);
2182
2183                         w = p->user_target = get_users_target(p->uid);
2184                 }
2185
2186                 if(likely(w))
2187                         aggregate_pid_on_target(w, p, o);
2188                 else
2189                         error("pid %d %s was left without a user target!", p->pid, p->comm);
2190
2191
2192                 // --------------------------------------------------------------------
2193                 // group targets
2194                 o = p->group_target;
2195                 if(likely(p->group_target && p->group_target->gid == p->gid))
2196                         w = p->group_target;
2197                 else {
2198                         if(unlikely(debug && p->group_target))
2199                                         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);
2200
2201                         w = p->group_target = get_groups_target(p->gid);
2202                 }
2203
2204                 if(likely(w))
2205                         aggregate_pid_on_target(w, p, o);
2206                 else
2207                         error("pid %d %s was left without a group target!", p->pid, p->comm);
2208
2209         }
2210
2211         count_targets_fds(apps_groups_root_target);
2212         count_targets_fds(users_root_target);
2213         count_targets_fds(groups_root_target);
2214
2215         cleanup_exited_pids();
2216 }
2217
2218 // ----------------------------------------------------------------------------
2219 // update chart dimensions
2220
2221 BUFFER *output = NULL;
2222 int print_calculated_number(char *str, calculated_number value) { (void)str; (void)value; return 0; }
2223
2224 static inline void send_BEGIN(const char *type, const char *id, unsigned long long usec) {
2225         // fprintf(stdout, "BEGIN %s.%s %llu\n", type, id, usec);
2226         buffer_strcat(output, "BEGIN ");
2227         buffer_strcat(output, type);
2228         buffer_strcat(output, ".");
2229         buffer_strcat(output, id);
2230         buffer_strcat(output, " ");
2231         buffer_print_llu(output, usec);
2232         buffer_strcat(output, "\n");
2233 }
2234
2235 static inline void send_SET(const char *name, unsigned long long value) {
2236         // fprintf(stdout, "SET %s = %llu\n", name, value);
2237         buffer_strcat(output, "SET ");
2238         buffer_strcat(output, name);
2239         buffer_strcat(output, " = ");
2240         buffer_print_llu(output, value);
2241         buffer_strcat(output, "\n");
2242 }
2243
2244 static inline void send_END(void) {
2245         // fprintf(stdout, "END\n");
2246         buffer_strcat(output, "END\n");
2247 }
2248
2249 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;
2250 double minflt_fix_ratio = 1.0, majflt_fix_ratio = 1.0, cminflt_fix_ratio = 1.0, cmajflt_fix_ratio = 1.0;
2251
2252 unsigned long long send_resource_usage_to_netdata() {
2253         static struct timeval last = { 0, 0 };
2254         static struct rusage me_last;
2255
2256         struct timeval now;
2257         struct rusage me;
2258
2259         unsigned long long usec;
2260         unsigned long long cpuuser;
2261         unsigned long long cpusyst;
2262
2263         if(!last.tv_sec) {
2264                 gettimeofday(&last, NULL);
2265                 getrusage(RUSAGE_SELF, &me_last);
2266
2267                 // the first time, give a zero to allow
2268                 // netdata calibrate to the current time
2269                 // usec = update_every * 1000000ULL;
2270                 usec = 0ULL;
2271                 cpuuser = 0;
2272                 cpusyst = 0;
2273         }
2274         else {
2275                 gettimeofday(&now, NULL);
2276                 getrusage(RUSAGE_SELF, &me);
2277
2278                 usec = usecdiff(&now, &last);
2279                 cpuuser = me.ru_utime.tv_sec * 1000000ULL + me.ru_utime.tv_usec;
2280                 cpusyst = me.ru_stime.tv_sec * 1000000ULL + me.ru_stime.tv_usec;
2281
2282                 bcopy(&now, &last, sizeof(struct timeval));
2283                 bcopy(&me, &me_last, sizeof(struct rusage));
2284         }
2285
2286         buffer_sprintf(output,
2287                 "BEGIN netdata.apps_cpu %llu\n"
2288                 "SET user = %llu\n"
2289                 "SET system = %llu\n"
2290                 "END\n"
2291                 "BEGIN netdata.apps_files %llu\n"
2292                 "SET files = %llu\n"
2293                 "SET pids = %ld\n"
2294                 "SET fds = %d\n"
2295                 "SET targets = %ld\n"
2296                 "END\n"
2297                 "BEGIN netdata.apps_fix %llu\n"
2298                 "SET utime = %llu\n"
2299                 "SET stime = %llu\n"
2300                 "SET gtime = %llu\n"
2301                 "SET minflt = %llu\n"
2302                 "SET majflt = %llu\n"
2303                 "END\n"
2304                 , usec
2305                 , cpuuser
2306                 , cpusyst
2307                 , usec
2308                 , file_counter
2309                 , all_pids_count
2310                 , all_files_len
2311                 , apps_groups_targets
2312                 , usec
2313                 , (unsigned long long)(utime_fix_ratio   * 100 * RATES_DETAIL)
2314                 , (unsigned long long)(stime_fix_ratio   * 100 * RATES_DETAIL)
2315                 , (unsigned long long)(gtime_fix_ratio   * 100 * RATES_DETAIL)
2316                 , (unsigned long long)(minflt_fix_ratio  * 100 * RATES_DETAIL)
2317                 , (unsigned long long)(majflt_fix_ratio  * 100 * RATES_DETAIL)
2318                 );
2319
2320         if(include_exited_childs)
2321                 buffer_sprintf(output,
2322                         "BEGIN netdata.apps_children_fix %llu\n"
2323                         "SET cutime = %llu\n"
2324                         "SET cstime = %llu\n"
2325                         "SET cgtime = %llu\n"
2326                         "SET cminflt = %llu\n"
2327                         "SET cmajflt = %llu\n"
2328                         "END\n"
2329                         , usec
2330                         , (unsigned long long)(cutime_fix_ratio  * 100 * RATES_DETAIL)
2331                         , (unsigned long long)(cstime_fix_ratio  * 100 * RATES_DETAIL)
2332                         , (unsigned long long)(cgtime_fix_ratio  * 100 * RATES_DETAIL)
2333                         , (unsigned long long)(cminflt_fix_ratio * 100 * RATES_DETAIL)
2334                         , (unsigned long long)(cmajflt_fix_ratio * 100 * RATES_DETAIL)
2335                         );
2336
2337         return usec;
2338 }
2339
2340 void normalize_data(struct target *root) {
2341         struct target *w;
2342
2343         // childs processing introduces spikes
2344         // here we try to eliminate them by disabling childs processing either for specific dimensions
2345         // or entirely. Of course, either way, we disable it just a single iteration.
2346
2347         unsigned long long max = processors * hz * RATES_DETAIL;
2348         unsigned long long utime = 0, cutime = 0, stime = 0, cstime = 0, gtime = 0, cgtime = 0, minflt = 0, cminflt = 0, majflt = 0, cmajflt = 0;
2349
2350         if(global_utime > max) global_utime = max;
2351         if(global_stime > max) global_stime = max;
2352         if(global_gtime > max) global_gtime = max;
2353
2354         for(w = root; w ; w = w->next) {
2355                 if(w->target || (!w->processes && !w->exposed)) continue;
2356
2357                 utime   += w->utime;
2358                 stime   += w->stime;
2359                 gtime   += w->gtime;
2360                 cutime  += w->cutime;
2361                 cstime  += w->cstime;
2362                 cgtime  += w->cgtime;
2363
2364                 minflt  += w->minflt;
2365                 majflt  += w->majflt;
2366                 cminflt += w->cminflt;
2367                 cmajflt += w->cmajflt;
2368         }
2369
2370         if((global_utime || global_stime || global_gtime) && (utime || stime || gtime)) {
2371                 if(global_utime + global_stime + global_gtime > utime + cutime + stime + cstime + gtime + cgtime) {
2372                         // everything we collected fits
2373                         utime_fix_ratio  =
2374                         stime_fix_ratio  =
2375                         gtime_fix_ratio  =
2376                         cutime_fix_ratio =
2377                         cstime_fix_ratio =
2378                         cgtime_fix_ratio = 1.0; //(double)(global_utime + global_stime) / (double)(utime + cutime + stime + cstime);
2379                 }
2380                 else if(global_utime + global_stime > utime + stime) {
2381                         // childrens resources are too high
2382                         // lower only the children resources
2383                         utime_fix_ratio  =
2384                         stime_fix_ratio  =
2385                         gtime_fix_ratio  = 1.0;
2386                         cutime_fix_ratio =
2387                         cstime_fix_ratio =
2388                         cgtime_fix_ratio = (double)((global_utime + global_stime) - (utime + stime)) / (double)(cutime + cstime);
2389                 }
2390                 else {
2391                         // even running processes are unrealistic
2392                         // zero the children resources
2393                         // lower the running processes resources
2394                         utime_fix_ratio  =
2395                         stime_fix_ratio  =
2396                         gtime_fix_ratio  = (double)(global_utime + global_stime) / (double)(utime + stime);
2397                         cutime_fix_ratio =
2398                         cstime_fix_ratio =
2399                         cgtime_fix_ratio = 0.0;
2400                 }
2401         }
2402         else {
2403                 utime_fix_ratio  =
2404                 stime_fix_ratio  =
2405                 gtime_fix_ratio  =
2406                 cutime_fix_ratio =
2407                 cstime_fix_ratio =
2408                 cgtime_fix_ratio = 0.0;
2409         }
2410
2411         if(utime_fix_ratio  > 1.0) utime_fix_ratio  = 1.0;
2412         if(cutime_fix_ratio > 1.0) cutime_fix_ratio = 1.0;
2413         if(stime_fix_ratio  > 1.0) stime_fix_ratio  = 1.0;
2414         if(cstime_fix_ratio > 1.0) cstime_fix_ratio = 1.0;
2415         if(gtime_fix_ratio  > 1.0) gtime_fix_ratio  = 1.0;
2416         if(cgtime_fix_ratio > 1.0) cgtime_fix_ratio = 1.0;
2417
2418         // if(utime_fix_ratio  < 0.0) utime_fix_ratio  = 0.0;
2419         // if(cutime_fix_ratio < 0.0) cutime_fix_ratio = 0.0;
2420         // if(stime_fix_ratio  < 0.0) stime_fix_ratio  = 0.0;
2421         // if(cstime_fix_ratio < 0.0) cstime_fix_ratio = 0.0;
2422         // if(gtime_fix_ratio  < 0.0) gtime_fix_ratio  = 0.0;
2423         // if(cgtime_fix_ratio < 0.0) cgtime_fix_ratio = 0.0;
2424
2425         // FIXME
2426         // we use cpu time to normalize page faults
2427         // the problem is that to find the proper max values
2428         // for page faults we have to parse /proc/vmstat
2429         // which is quite big to do it again (netdata does it already)
2430         //
2431         // a better solution could be to somehow have netdata
2432         // do this normalization for us
2433
2434         if(utime || stime || gtime)
2435                 majflt_fix_ratio =
2436                 minflt_fix_ratio = (double)(utime * utime_fix_ratio + stime * stime_fix_ratio + gtime * gtime_fix_ratio) / (double)(utime + stime + gtime);
2437         else
2438                 minflt_fix_ratio =
2439                 majflt_fix_ratio = 1.0;
2440
2441         if(cutime || cstime || cgtime)
2442                 cmajflt_fix_ratio =
2443                 cminflt_fix_ratio = (double)(cutime * cutime_fix_ratio + cstime * cstime_fix_ratio + cgtime * cgtime_fix_ratio) / (double)(cutime + cstime + cgtime);
2444         else
2445                 cminflt_fix_ratio =
2446                 cmajflt_fix_ratio = 1.0;
2447
2448         // the report
2449
2450         if(unlikely(debug)) {
2451                 fprintf(stderr,
2452                         "SYSTEM: u=%llu s=%llu g=%llu "
2453                         "COLLECTED: u=%llu s=%llu g=%llu cu=%llu cs=%llu cg=%llu "
2454                         "DELTA: u=%lld s=%lld g=%lld "
2455                         "FIX: u=%0.2f s=%0.2f g=%0.2f cu=%0.2f cs=%0.2f cg=%0.2f "
2456                         "FINALLY: u=%llu s=%llu g=%llu cu=%llu cs=%llu cg=%llu "
2457                         "\n"
2458                         , global_utime
2459                         , global_stime
2460                         , global_gtime
2461                         , utime
2462                         , stime
2463                         , gtime
2464                         , cutime
2465                         , cstime
2466                         , cgtime
2467                         , (long long)utime + (long long)cutime - (long long)global_utime
2468                         , (long long)stime + (long long)cstime - (long long)global_stime
2469                         , (long long)gtime + (long long)cgtime - (long long)global_gtime
2470                         , utime_fix_ratio
2471                         , stime_fix_ratio
2472                         , gtime_fix_ratio
2473                         , cutime_fix_ratio
2474                         , cstime_fix_ratio
2475                         , cgtime_fix_ratio
2476                         , (unsigned long long)(utime * utime_fix_ratio)
2477                         , (unsigned long long)(stime * stime_fix_ratio)
2478                         , (unsigned long long)(gtime * gtime_fix_ratio)
2479                         , (unsigned long long)(cutime * cutime_fix_ratio)
2480                         , (unsigned long long)(cstime * cstime_fix_ratio)
2481                         , (unsigned long long)(cgtime * cgtime_fix_ratio)
2482                         );
2483         }
2484 }
2485
2486 void send_collected_data_to_netdata(struct target *root, const char *type, unsigned long long usec) {
2487         struct target *w;
2488
2489         send_BEGIN(type, "cpu", usec);
2490         for (w = root; w ; w = w->next) {
2491                 if(unlikely(w->exposed))
2492                         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));
2493         }
2494         send_END();
2495
2496         send_BEGIN(type, "cpu_user", usec);
2497         for (w = root; w ; w = w->next) {
2498                 if(unlikely(w->exposed))
2499                         send_SET(w->name, (unsigned long long)(w->utime * utime_fix_ratio) + (include_exited_childs?((unsigned long long)(w->cutime * cutime_fix_ratio)):0ULL));
2500         }
2501         send_END();
2502
2503         send_BEGIN(type, "cpu_system", usec);
2504         for (w = root; w ; w = w->next) {
2505                 if(unlikely(w->exposed))
2506                         send_SET(w->name, (unsigned long long)(w->stime * stime_fix_ratio) + (include_exited_childs?((unsigned long long)(w->cstime * cstime_fix_ratio)):0ULL));
2507         }
2508         send_END();
2509
2510         if(show_guest_time) {
2511                 send_BEGIN(type, "cpu_guest", usec);
2512                 for (w = root; w ; w = w->next) {
2513                         if(unlikely(w->exposed))
2514                                 send_SET(w->name, (unsigned long long)(w->gtime * gtime_fix_ratio) + (include_exited_childs?((unsigned long long)(w->cgtime * cgtime_fix_ratio)):0ULL));
2515                 }
2516                 send_END();
2517         }
2518
2519         send_BEGIN(type, "threads", usec);
2520         for (w = root; w ; w = w->next) {
2521                 if(unlikely(w->exposed))
2522                         send_SET(w->name, w->num_threads);
2523         }
2524         send_END();
2525
2526         send_BEGIN(type, "processes", usec);
2527         for (w = root; w ; w = w->next) {
2528                 if(unlikely(w->exposed))
2529                         send_SET(w->name, w->processes);
2530         }
2531         send_END();
2532
2533         send_BEGIN(type, "mem", usec);
2534         for (w = root; w ; w = w->next) {
2535                 if(unlikely(w->exposed))
2536                         send_SET(w->name, (w->statm_resident > w->statm_share)?(w->statm_resident - w->statm_share):0ULL);
2537         }
2538         send_END();
2539
2540         send_BEGIN(type, "minor_faults", usec);
2541         for (w = root; w ; w = w->next) {
2542                 if(unlikely(w->exposed))
2543                         send_SET(w->name, (unsigned long long)(w->minflt * minflt_fix_ratio) + (include_exited_childs?((unsigned long long)(w->cminflt * cminflt_fix_ratio)):0ULL));
2544         }
2545         send_END();
2546
2547         send_BEGIN(type, "major_faults", usec);
2548         for (w = root; w ; w = w->next) {
2549                 if(unlikely(w->exposed))
2550                         send_SET(w->name, (unsigned long long)(w->majflt * majflt_fix_ratio) + (include_exited_childs?((unsigned long long)(w->cmajflt * cmajflt_fix_ratio)):0ULL));
2551         }
2552         send_END();
2553
2554         send_BEGIN(type, "lreads", usec);
2555         for (w = root; w ; w = w->next) {
2556                 if(unlikely(w->exposed))
2557                         send_SET(w->name, w->io_logical_bytes_read);
2558         }
2559         send_END();
2560
2561         send_BEGIN(type, "lwrites", usec);
2562         for (w = root; w ; w = w->next) {
2563                 if(unlikely(w->exposed))
2564                         send_SET(w->name, w->io_logical_bytes_written);
2565         }
2566         send_END();
2567
2568         send_BEGIN(type, "preads", usec);
2569         for (w = root; w ; w = w->next) {
2570                 if(unlikely(w->exposed))
2571                         send_SET(w->name, w->io_storage_bytes_read);
2572         }
2573         send_END();
2574
2575         send_BEGIN(type, "pwrites", usec);
2576         for (w = root; w ; w = w->next) {
2577                 if(unlikely(w->exposed))
2578                         send_SET(w->name, w->io_storage_bytes_written);
2579         }
2580         send_END();
2581
2582         send_BEGIN(type, "files", usec);
2583         for (w = root; w ; w = w->next) {
2584                 if(unlikely(w->exposed))
2585                         send_SET(w->name, w->openfiles);
2586         }
2587         send_END();
2588
2589         send_BEGIN(type, "sockets", usec);
2590         for (w = root; w ; w = w->next) {
2591                 if(unlikely(w->exposed))
2592                         send_SET(w->name, w->opensockets);
2593         }
2594         send_END();
2595
2596         send_BEGIN(type, "pipes", usec);
2597         for (w = root; w ; w = w->next) {
2598                 if(unlikely(w->exposed))
2599                         send_SET(w->name, w->openpipes);
2600         }
2601         send_END();
2602 }
2603
2604
2605 // ----------------------------------------------------------------------------
2606 // generate the charts
2607
2608 void send_charts_updates_to_netdata(struct target *root, const char *type, const char *title)
2609 {
2610         struct target *w;
2611         int newly_added = 0;
2612
2613         for(w = root ; w ; w = w->next) {
2614                 if (w->target) continue;
2615
2616                 if (!w->exposed && w->processes) {
2617                         newly_added++;
2618                         w->exposed = 1;
2619                         if (debug || w->debug) fprintf(stderr, "apps.plugin: %s just added - regenerating charts.\n", w->name);
2620                 }
2621         }
2622
2623         // nothing more to show
2624         if(!newly_added && show_guest_time == show_guest_time_old) return;
2625
2626         // we have something new to show
2627         // update the charts
2628         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);
2629         for (w = root; w ; w = w->next) {
2630                 if(unlikely(w->exposed))
2631                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu %s\n", w->name, hz * RATES_DETAIL / 100, w->hidden ? "hidden" : "");
2632         }
2633
2634         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);
2635         for (w = root; w ; w = w->next) {
2636                 if(unlikely(w->exposed))
2637                         buffer_sprintf(output, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
2638         }
2639
2640         buffer_sprintf(output, "CHART %s.threads '' '%s Threads' 'threads' processes %s.threads stacked 20005 %d\n", type, title, type, update_every);
2641         for (w = root; w ; w = w->next) {
2642                 if(unlikely(w->exposed))
2643                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 1\n", w->name);
2644         }
2645
2646         buffer_sprintf(output, "CHART %s.processes '' '%s Processes' 'processes' processes %s.processes stacked 20004 %d\n", type, title, type, update_every);
2647         for (w = root; w ; w = w->next) {
2648                 if(unlikely(w->exposed))
2649                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 1\n", w->name);
2650         }
2651
2652         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);
2653         for (w = root; w ; w = w->next) {
2654                 if(unlikely(w->exposed))
2655                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
2656         }
2657
2658         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);
2659         for (w = root; w ; w = w->next) {
2660                 if(unlikely(w->exposed))
2661                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
2662         }
2663
2664         if(show_guest_time) {
2665                 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);
2666                 for (w = root; w; w = w->next) {
2667                         if(unlikely(w->exposed))
2668                                 buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
2669                 }
2670         }
2671
2672         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);
2673         for (w = root; w ; w = w->next) {
2674                 if(unlikely(w->exposed))
2675                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
2676         }
2677
2678         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);
2679         for (w = root; w ; w = w->next) {
2680                 if(unlikely(w->exposed))
2681                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
2682         }
2683
2684         buffer_sprintf(output, "CHART %s.lreads '' '%s Disk Logical Reads' 'kilobytes/s' disk %s.lreads stacked 20042 %d\n", type, title, type, update_every);
2685         for (w = root; w ; w = w->next) {
2686                 if(unlikely(w->exposed))
2687                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
2688         }
2689
2690         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);
2691         for (w = root; w ; w = w->next) {
2692                 if(unlikely(w->exposed))
2693                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
2694         }
2695
2696         buffer_sprintf(output, "CHART %s.preads '' '%s Disk Reads' 'kilobytes/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
2697         for (w = root; w ; w = w->next) {
2698                 if(unlikely(w->exposed))
2699                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
2700         }
2701
2702         buffer_sprintf(output, "CHART %s.pwrites '' '%s Disk Writes' 'kilobytes/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
2703         for (w = root; w ; w = w->next) {
2704                 if(unlikely(w->exposed))
2705                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
2706         }
2707
2708         buffer_sprintf(output, "CHART %s.files '' '%s Open Files' 'open files' disk %s.files stacked 20050 %d\n", type, title, type, update_every);
2709         for (w = root; w ; w = w->next) {
2710                 if(unlikely(w->exposed))
2711                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 1\n", w->name);
2712         }
2713
2714         buffer_sprintf(output, "CHART %s.sockets '' '%s Open Sockets' 'open sockets' net %s.sockets stacked 20051 %d\n", type, title, type, update_every);
2715         for (w = root; w ; w = w->next) {
2716                 if(unlikely(w->exposed))
2717                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 1\n", w->name);
2718         }
2719
2720         buffer_sprintf(output, "CHART %s.pipes '' '%s Pipes' 'open pipes' processes %s.pipes stacked 20053 %d\n", type, title, type, update_every);
2721         for (w = root; w ; w = w->next) {
2722                 if(unlikely(w->exposed))
2723                         buffer_sprintf(output, "DIMENSION %s '' absolute 1 1\n", w->name);
2724         }
2725 }
2726
2727
2728 // ----------------------------------------------------------------------------
2729 // parse command line arguments
2730
2731 void parse_args(int argc, char **argv)
2732 {
2733         int i, freq = 0;
2734         char *name = NULL;
2735
2736         for(i = 1; i < argc; i++) {
2737                 if(!freq) {
2738                         int n = atoi(argv[i]);
2739                         if(n > 0) {
2740                                 freq = n;
2741                                 continue;
2742                         }
2743                 }
2744
2745                 if(strcmp("debug", argv[i]) == 0) {
2746                         debug = 1;
2747                         // debug_flags = 0xffffffff;
2748                         continue;
2749                 }
2750
2751                 if(strcmp("no-childs", argv[i]) == 0 || strcmp("without-childs", argv[i]) == 0) {
2752                         include_exited_childs = 0;
2753                         continue;
2754                 }
2755
2756                 if(strcmp("with-childs", argv[i]) == 0) {
2757                         include_exited_childs = 1;
2758                         continue;
2759                 }
2760
2761         if(strcmp("with-guest", argv[i]) == 0) {
2762             enable_guest_charts = 1;
2763             continue;
2764         }
2765
2766         if(strcmp("no-guest", argv[i]) == 0 || strcmp("without-guest", argv[i]) == 0) {
2767             enable_guest_charts = 0;
2768             continue;
2769         }
2770
2771                 if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0) {
2772             fprintf(stderr,
2773                     "apps.plugin\n"
2774                     "(C) 2016 Costa Tsaousis"
2775                     "GPL v3+\n"
2776                     "This program is a data collector plugin for netdata.\n"
2777                     "\n"
2778                     "Valid command line options:\n"
2779                     "\n"
2780                     "SECONDS           set the data collection frequency\n"
2781                     "\n"
2782                     "debug             enable debugging (lot of output)\n"
2783                     "\n"
2784                     "with-childs\n"
2785                     "without-childs    enable / disable aggregating exited\n"
2786                     "                  children resources into parents\n"
2787                     "                  (default is enabled)\n"
2788                     "\n"
2789                     "with-guest\n"
2790                     "without-guest     enable / disable reporting guest charts\n"
2791                     "                  (default is disabled)\n"
2792                     "\n"
2793                     "NAME              read apps_NAME.conf instead of\n"
2794                     "                  apps_groups.conf\n"
2795                     "                  (default NAME=groups)\n"
2796             );
2797             exit(1);
2798         }
2799
2800         if(!name) {
2801                         name = argv[i];
2802                         continue;
2803                 }
2804
2805                 error("Cannot understand option %s", argv[i]);
2806                 exit(1);
2807         }
2808
2809         if(freq > 0) update_every = freq;
2810         if(!name) name = "groups";
2811
2812         if(read_apps_groups_conf(name)) {
2813                 error("Cannot read process groups %s", name);
2814                 exit(1);
2815         }
2816 }
2817
2818 int main(int argc, char **argv)
2819 {
2820         // debug_flags = D_PROCFILE;
2821
2822         // set the name for logging
2823         program_name = "apps.plugin";
2824
2825         // disable syslog for apps.plugin
2826         error_log_syslog = 0;
2827
2828         // set errors flood protection to 100 logs per hour
2829         error_log_errors_per_period = 100;
2830         error_log_throttle_period = 3600;
2831
2832         host_prefix = getenv("NETDATA_HOST_PREFIX");
2833         if(host_prefix == NULL) {
2834                 info("NETDATA_HOST_PREFIX is not passed from netdata");
2835                 host_prefix = "";
2836         }
2837         else info("Found NETDATA_HOST_PREFIX='%s'", host_prefix);
2838
2839         config_dir = getenv("NETDATA_CONFIG_DIR");
2840         if(config_dir == NULL) {
2841                 info("NETDATA_CONFIG_DIR is not passed from netdata");
2842                 config_dir = CONFIG_DIR;
2843         }
2844         else info("Found NETDATA_CONFIG_DIR='%s'", config_dir);
2845
2846 #ifdef NETDATA_INTERNAL_CHECKS
2847         if(debug_flags != 0) {
2848                 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
2849                 if(setrlimit(RLIMIT_CORE, &rl) != 0)
2850                         info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
2851                 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
2852         }
2853 #endif /* NETDATA_INTERNAL_CHECKS */
2854
2855         procfile_adaptive_initial_allocation = 1;
2856
2857         time_t started_t = time(NULL);
2858         time_t current_t;
2859         get_HZ();
2860         pid_max = get_system_pid_max();
2861         processors = get_system_cpus();
2862
2863         parse_args(argc, argv);
2864
2865         all_pids_sortlist = calloc(sizeof(pid_t), (size_t)pid_max);
2866         if(!all_pids_sortlist) {
2867                 error("Cannot allocate %zu bytes of memory.", sizeof(pid_t) * pid_max);
2868                 printf("DISABLE\n");
2869                 exit(1);
2870         }
2871
2872         all_pids = calloc(sizeof(struct pid_stat *), (size_t) pid_max);
2873         if(!all_pids) {
2874                 error("Cannot allocate %zu bytes of memory.", sizeof(struct pid_stat *) * pid_max);
2875                 printf("DISABLE\n");
2876                 exit(1);
2877         }
2878
2879         output = buffer_create(1024);
2880         if(!output)
2881                 fatal("Cannot create BUFFER.");
2882
2883         buffer_sprintf(output,
2884                 "CHART netdata.apps_cpu '' 'Apps Plugin CPU' 'milliseconds/s' apps.plugin netdata.apps_cpu stacked 140000 %1$d\n"
2885                 "DIMENSION user '' incremental 1 1000\n"
2886                 "DIMENSION system '' incremental 1 1000\n"
2887                 "CHART netdata.apps_files '' 'Apps Plugin Files' 'files/s' apps.plugin netdata.apps_files line 140001 %1$d\n"
2888                 "DIMENSION files '' incremental 1 1\n"
2889                 "DIMENSION pids '' absolute 1 1\n"
2890                 "DIMENSION fds '' absolute 1 1\n"
2891                 "DIMENSION targets '' absolute 1 1\n"
2892                 "CHART netdata.apps_fix '' 'Apps Plugin Normalization Ratios' 'percentage' apps.plugin netdata.apps_fix line 140002 %1$d\n"
2893                 "DIMENSION utime '' absolute 1 %2$llu\n"
2894                 "DIMENSION stime '' absolute 1 %2$llu\n"
2895                 "DIMENSION gtime '' absolute 1 %2$llu\n"
2896                 "DIMENSION minflt '' absolute 1 %2$llu\n"
2897                 "DIMENSION majflt '' absolute 1 %2$llu\n"
2898                 , update_every
2899                 , RATES_DETAIL
2900                 );
2901
2902         if(include_exited_childs)
2903                 buffer_sprintf(output,
2904                         "CHART netdata.apps_children_fix '' 'Apps Plugin Exited Children Normalization Ratios' 'percentage' apps.plugin netdata.apps_children_fix line 140003 %1$d\n"
2905                         "DIMENSION cutime '' absolute 1 %2$llu\n"
2906                         "DIMENSION cstime '' absolute 1 %2$llu\n"
2907                         "DIMENSION cgtime '' absolute 1 %2$llu\n"
2908                         "DIMENSION cminflt '' absolute 1 %2$llu\n"
2909                         "DIMENSION cmajflt '' absolute 1 %2$llu\n"
2910                         , update_every
2911                         , RATES_DETAIL
2912                         );
2913
2914 #ifndef PROFILING_MODE
2915         unsigned long long sunext = (time(NULL) - (time(NULL) % update_every) + update_every) * 1000000ULL;
2916         unsigned long long sunow;
2917 #endif /* PROFILING_MODE */
2918
2919         global_iterations_counter = 1;
2920         for(;1; global_iterations_counter++) {
2921 #ifndef PROFILING_MODE
2922                 // delay until it is our time to run
2923                 while((sunow = timems()) < sunext)
2924                         usecsleep(sunext - sunow);
2925
2926                 // find the next time we need to run
2927                 while(timems() > sunext)
2928                         sunext += update_every * 1000000ULL;
2929 #endif /* PROFILING_MODE */
2930
2931                 if(!collect_data_for_all_processes_from_proc()) {
2932                         error("Cannot collect /proc data for running processes. Disabling apps.plugin...");
2933                         printf("DISABLE\n");
2934                         exit(1);
2935                 }
2936
2937                 calculate_netdata_statistics();
2938                 normalize_data(apps_groups_root_target);
2939
2940                 unsigned long long dt = send_resource_usage_to_netdata();
2941
2942                 // this is smart enough to show only newly added apps, when needed
2943                 send_charts_updates_to_netdata(apps_groups_root_target, "apps", "Apps");
2944                 send_charts_updates_to_netdata(users_root_target, "users", "Users");
2945                 send_charts_updates_to_netdata(groups_root_target, "groups", "User Groups");
2946
2947                 send_collected_data_to_netdata(apps_groups_root_target, "apps", dt);
2948                 send_collected_data_to_netdata(users_root_target, "users", dt);
2949                 send_collected_data_to_netdata(groups_root_target, "groups", dt);
2950
2951                 show_guest_time_old = show_guest_time;
2952
2953                 //if(puts(buffer_tostring(output)) == EOF)
2954                 if(write(STDOUT_FILENO, buffer_tostring(output), buffer_strlen(output)) == -1)
2955                         fatal("Cannot send chart values to netdata.");
2956
2957                 // fflush(stdout);
2958                 buffer_flush(output);
2959
2960                 if(unlikely(debug))
2961                         fprintf(stderr, "apps.plugin: done Loop No %llu\n", global_iterations_counter);
2962
2963                 current_t = time(NULL);
2964
2965 #ifndef PROFILING_MODE
2966                 // restart check (14400 seconds)
2967                 if(current_t - started_t > 14400) exit(0);
2968 #else
2969                 if(current_t - started_t > 10) exit(0);
2970 #endif /* PROFILING_MODE */
2971         }
2972 }