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