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