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