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