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