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