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