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