]> arthur.barton.de Git - netdata.git/blob - src/apps_plugin.c
Merge pull request #1998 from ktsaou/master
[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 #ifndef __FreeBSD__
1084 cleanup:
1085     p->statm_size           = 0;
1086     p->statm_resident       = 0;
1087     p->statm_share          = 0;
1088     // p->statm_text           = 0;
1089     // p->statm_lib            = 0;
1090     // p->statm_data           = 0;
1091     // p->statm_dirty          = 0;
1092     return 0;
1093 #endif
1094 }
1095
1096 static inline int read_proc_pid_io(struct pid_stat *p, void *ptr) {
1097     (void)ptr;
1098 #ifdef __FreeBSD__
1099     struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
1100 #else
1101     static procfile *ff = NULL;
1102
1103     if(unlikely(!p->io_filename)) {
1104         char filename[FILENAME_MAX + 1];
1105         snprintfz(filename, FILENAME_MAX, "%s/proc/%d/io", netdata_configured_host_prefix, p->pid);
1106         p->io_filename = strdupz(filename);
1107     }
1108
1109     // open the file
1110     ff = procfile_reopen(ff, p->io_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
1111     if(unlikely(!ff)) goto cleanup;
1112
1113     ff = procfile_readall(ff);
1114     if(unlikely(!ff)) goto cleanup;
1115 #endif
1116
1117     calls_counter++;
1118
1119     p->last_io_collected_usec = p->io_collected_usec;
1120     p->io_collected_usec = now_monotonic_usec();
1121
1122 #ifdef __FreeBSD__
1123     pid_incremental_rate(io, p->io_storage_bytes_read,       proc_info->ki_rusage.ru_inblock);
1124     pid_incremental_rate(io, p->io_storage_bytes_written,    proc_info->ki_rusage.ru_oublock);
1125 #else
1126     pid_incremental_rate(io, p->io_logical_bytes_read,       str2kernel_uint_t(procfile_lineword(ff, 0,  1)));
1127     pid_incremental_rate(io, p->io_logical_bytes_written,    str2kernel_uint_t(procfile_lineword(ff, 1,  1)));
1128     // pid_incremental_rate(io, p->io_read_calls,               str2kernel_uint_t(procfile_lineword(ff, 2,  1)));
1129     // pid_incremental_rate(io, p->io_write_calls,              str2kernel_uint_t(procfile_lineword(ff, 3,  1)));
1130     pid_incremental_rate(io, p->io_storage_bytes_read,       str2kernel_uint_t(procfile_lineword(ff, 4,  1)));
1131     pid_incremental_rate(io, p->io_storage_bytes_written,    str2kernel_uint_t(procfile_lineword(ff, 5,  1)));
1132     // pid_incremental_rate(io, p->io_cancelled_write_bytes,    str2kernel_uint_t(procfile_lineword(ff, 6,  1)));
1133 #endif
1134
1135     if(unlikely(global_iterations_counter == 1)) {
1136         p->io_logical_bytes_read        = 0;
1137         p->io_logical_bytes_written     = 0;
1138         // p->io_read_calls             = 0;
1139         // p->io_write_calls            = 0;
1140         p->io_storage_bytes_read        = 0;
1141         p->io_storage_bytes_written     = 0;
1142         // p->io_cancelled_write_bytes  = 0;
1143     }
1144
1145     return 1;
1146
1147 #ifndef __FreeBSD__
1148 cleanup:
1149     p->io_logical_bytes_read        = 0;
1150     p->io_logical_bytes_written     = 0;
1151     // p->io_read_calls             = 0;
1152     // p->io_write_calls            = 0;
1153     p->io_storage_bytes_read        = 0;
1154     p->io_storage_bytes_written     = 0;
1155     // p->io_cancelled_write_bytes  = 0;
1156     return 0;
1157 #endif
1158 }
1159
1160 static inline int read_proc_stat() {
1161 #ifdef __FreeBSD__
1162     long cp_time[CPUSTATES];
1163     static kernel_uint_t utime_raw = 0, stime_raw = 0, ntime_raw = 0;
1164
1165     if (unlikely(CPUSTATES != 5)) {
1166         error("FREEBSD: There are %d CPU states (5 was expected)", CPUSTATES);
1167         goto cleanup;
1168     }
1169     if (unlikely(GETSYSCTL_BY_NAME("kern.cp_time", cp_time))) goto cleanup;
1170 #else
1171     static char filename[FILENAME_MAX + 1] = "";
1172     static procfile *ff = NULL;
1173     static kernel_uint_t utime_raw = 0, stime_raw = 0, gtime_raw = 0, gntime_raw = 0, ntime_raw = 0;
1174 #endif
1175     static usec_t collected_usec = 0, last_collected_usec = 0;
1176
1177 #ifndef __FreeBSD__
1178     if(unlikely(!ff)) {
1179         snprintfz(filename, FILENAME_MAX, "%s/proc/stat", netdata_configured_host_prefix);
1180         ff = procfile_open(filename, " \t:", PROCFILE_FLAG_DEFAULT);
1181         if(unlikely(!ff)) goto cleanup;
1182     }
1183
1184     ff = procfile_readall(ff);
1185     if(unlikely(!ff)) goto cleanup;
1186 #endif
1187
1188     last_collected_usec = collected_usec;
1189     collected_usec = now_monotonic_usec();
1190
1191     calls_counter++;
1192
1193     // temporary - it is added global_ntime;
1194     kernel_uint_t global_ntime = 0;
1195
1196 #ifdef __FreeBSD__
1197     incremental_rate(global_utime, utime_raw, cp_time[0], collected_usec, last_collected_usec);
1198     incremental_rate(global_ntime, ntime_raw, cp_time[1], collected_usec, last_collected_usec);
1199     incremental_rate(global_stime, stime_raw, cp_time[2], collected_usec, last_collected_usec);
1200 #else
1201     incremental_rate(global_utime, utime_raw, str2kernel_uint_t(procfile_lineword(ff, 0,  1)), collected_usec, last_collected_usec);
1202     incremental_rate(global_ntime, ntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0,  2)), collected_usec, last_collected_usec);
1203     incremental_rate(global_stime, stime_raw, str2kernel_uint_t(procfile_lineword(ff, 0,  3)), collected_usec, last_collected_usec);
1204     incremental_rate(global_gtime, gtime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 10)), collected_usec, last_collected_usec);
1205 #endif
1206
1207     global_utime += global_ntime;
1208
1209 #ifdef __FreeBSD__
1210     if(enable_guest_charts) {
1211         enable_guest_charts = 0;
1212         info("Guest charts aren't supported by FreeBSD");
1213     }
1214 #else
1215     if(enable_guest_charts) {
1216         // temporary - it is added global_ntime;
1217         kernel_uint_t global_gntime = 0;
1218
1219         // guest nice time, on guest time
1220         incremental_rate(global_gntime, gntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 11)), collected_usec, last_collected_usec);
1221
1222         global_gtime += global_gntime;
1223
1224         // remove guest time from user time
1225         global_utime -= (global_utime > global_gtime) ? global_gtime : global_utime;
1226     }
1227 #endif
1228
1229     if(unlikely(global_iterations_counter == 1)) {
1230         global_utime = 0;
1231         global_stime = 0;
1232         global_gtime = 0;
1233     }
1234
1235     return 1;
1236
1237 cleanup:
1238     global_utime = 0;
1239     global_stime = 0;
1240     global_gtime = 0;
1241     return 0;
1242 }
1243
1244
1245 // ----------------------------------------------------------------------------
1246
1247 int file_descriptor_compare(void* a, void* b) {
1248 #ifdef NETDATA_INTERNAL_CHECKS
1249     if(((struct file_descriptor *)a)->magic != 0x0BADCAFE || ((struct file_descriptor *)b)->magic != 0x0BADCAFE)
1250         error("Corrupted index data detected. Please report this.");
1251 #endif /* NETDATA_INTERNAL_CHECKS */
1252
1253     if(((struct file_descriptor *)a)->hash < ((struct file_descriptor *)b)->hash)
1254         return -1;
1255
1256     else if(((struct file_descriptor *)a)->hash > ((struct file_descriptor *)b)->hash)
1257         return 1;
1258
1259     else
1260         return strcmp(((struct file_descriptor *)a)->name, ((struct file_descriptor *)b)->name);
1261 }
1262
1263 int file_descriptor_iterator(avl *a) { if(a) {}; return 0; }
1264
1265 avl_tree all_files_index = {
1266         NULL,
1267         file_descriptor_compare
1268 };
1269
1270 static struct file_descriptor *file_descriptor_find(const char *name, uint32_t hash) {
1271     struct file_descriptor tmp;
1272     tmp.hash = (hash)?hash:simple_hash(name);
1273     tmp.name = name;
1274     tmp.count = 0;
1275     tmp.pos = 0;
1276 #ifdef NETDATA_INTERNAL_CHECKS
1277     tmp.magic = 0x0BADCAFE;
1278 #endif /* NETDATA_INTERNAL_CHECKS */
1279
1280     return (struct file_descriptor *)avl_search(&all_files_index, (avl *) &tmp);
1281 }
1282
1283 #define file_descriptor_add(fd) avl_insert(&all_files_index, (avl *)(fd))
1284 #define file_descriptor_remove(fd) avl_remove(&all_files_index, (avl *)(fd))
1285
1286 // ----------------------------------------------------------------------------
1287
1288 static inline void file_descriptor_not_used(int id)
1289 {
1290     if(id > 0 && id < all_files_size) {
1291
1292 #ifdef NETDATA_INTERNAL_CHECKS
1293         if(all_files[id].magic != 0x0BADCAFE) {
1294             error("Ignoring request to remove empty file id %d.", id);
1295             return;
1296         }
1297 #endif /* NETDATA_INTERNAL_CHECKS */
1298
1299         if(unlikely(debug))
1300             fprintf(stderr, "apps.plugin: decreasing slot %d (count = %d).\n", id, all_files[id].count);
1301
1302         if(all_files[id].count > 0) {
1303             all_files[id].count--;
1304
1305             if(!all_files[id].count) {
1306                 if(unlikely(debug))
1307                     fprintf(stderr, "apps.plugin:   >> slot %d is empty.\n", id);
1308
1309                 if(unlikely(file_descriptor_remove(&all_files[id]) != (void *)&all_files[id]))
1310                     error("INTERNAL ERROR: removal of unused fd from index, removed a different fd");
1311
1312 #ifdef NETDATA_INTERNAL_CHECKS
1313                 all_files[id].magic = 0x00000000;
1314 #endif /* NETDATA_INTERNAL_CHECKS */
1315                 all_files_len--;
1316             }
1317         }
1318         else
1319             error("Request to decrease counter of fd %d (%s), while the use counter is 0", id, all_files[id].name);
1320     }
1321     else    error("Request to decrease counter of fd %d, which is outside the array size (1 to %d)", id, all_files_size);
1322 }
1323
1324 static inline void all_files_grow() {
1325     void *old = all_files;
1326     int i;
1327
1328     // there is no empty slot
1329     if(unlikely(debug))
1330         fprintf(stderr, "apps.plugin: extending fd array to %d entries\n", all_files_size + FILE_DESCRIPTORS_INCREASE_STEP);
1331
1332     all_files = reallocz(all_files, (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP) * sizeof(struct file_descriptor));
1333
1334     // if the address changed, we have to rebuild the index
1335     // since all pointers are now invalid
1336
1337     if(unlikely(old && old != (void *)all_files)) {
1338         if(unlikely(debug))
1339             fprintf(stderr, "apps.plugin:   >> re-indexing.\n");
1340
1341         all_files_index.root = NULL;
1342         for(i = 0; i < all_files_size; i++) {
1343             if(!all_files[i].count) continue;
1344             if(unlikely(file_descriptor_add(&all_files[i]) != (void *)&all_files[i]))
1345                 error("INTERNAL ERROR: duplicate indexing of fd during realloc.");
1346         }
1347
1348         if(unlikely(debug))
1349             fprintf(stderr, "apps.plugin:   >> re-indexing done.\n");
1350     }
1351
1352     // initialize the newly added entries
1353
1354     for(i = all_files_size; i < (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP); i++) {
1355         all_files[i].count = 0;
1356         all_files[i].name = NULL;
1357 #ifdef NETDATA_INTERNAL_CHECKS
1358         all_files[i].magic = 0x00000000;
1359 #endif /* NETDATA_INTERNAL_CHECKS */
1360         all_files[i].pos = i;
1361     }
1362
1363     if(unlikely(!all_files_size)) all_files_len = 1;
1364     all_files_size += FILE_DESCRIPTORS_INCREASE_STEP;
1365 }
1366
1367 static inline int file_descriptor_set_on_empty_slot(const char *name, uint32_t hash, FD_FILETYPE type) {
1368     // check we have enough memory to add it
1369     if(!all_files || all_files_len == all_files_size)
1370         all_files_grow();
1371
1372     if(unlikely(debug))
1373         fprintf(stderr, "apps.plugin:   >> searching for empty slot.\n");
1374
1375     // search for an empty slot
1376
1377     static int last_pos = 0;
1378     int i, c;
1379     for(i = 0, c = last_pos ; i < all_files_size ; i++, c++) {
1380         if(c >= all_files_size) c = 0;
1381         if(c == 0) continue;
1382
1383         if(!all_files[c].count) {
1384             if(unlikely(debug))
1385                 fprintf(stderr, "apps.plugin:   >> Examining slot %d.\n", c);
1386
1387 #ifdef NETDATA_INTERNAL_CHECKS
1388             if(all_files[c].magic == 0x0BADCAFE && all_files[c].name && file_descriptor_find(all_files[c].name, all_files[c].hash))
1389                 error("fd on position %d is not cleared properly. It still has %s in it.\n", c, all_files[c].name);
1390 #endif /* NETDATA_INTERNAL_CHECKS */
1391
1392             if(unlikely(debug))
1393                 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);
1394
1395             freez((void *)all_files[c].name);
1396             all_files[c].name = NULL;
1397             last_pos = c;
1398             break;
1399         }
1400     }
1401
1402     all_files_len++;
1403
1404     if(i == all_files_size) {
1405         fatal("We should find an empty slot, but there isn't any");
1406         exit(1);
1407     }
1408     // else we have an empty slot in 'c'
1409
1410     if(unlikely(debug))
1411         fprintf(stderr, "apps.plugin:   >> updating slot %d.\n", c);
1412
1413     all_files[c].name = strdupz(name);
1414     all_files[c].hash = hash;
1415     all_files[c].type = type;
1416     all_files[c].pos  = c;
1417     all_files[c].count = 1;
1418 #ifdef NETDATA_INTERNAL_CHECKS
1419     all_files[c].magic = 0x0BADCAFE;
1420 #endif /* NETDATA_INTERNAL_CHECKS */
1421     if(unlikely(file_descriptor_add(&all_files[c]) != (void *)&all_files[c]))
1422         error("INTERNAL ERROR: duplicate indexing of fd.");
1423
1424     if(unlikely(debug))
1425         fprintf(stderr, "apps.plugin: using fd position %d (name: %s)\n", c, all_files[c].name);
1426
1427     return c;
1428 }
1429
1430 static inline int file_descriptor_find_or_add(const char *name)
1431 {
1432     uint32_t hash = simple_hash(name);
1433
1434     if(unlikely(debug))
1435         fprintf(stderr, "apps.plugin: adding or finding name '%s' with hash %u\n", name, hash);
1436
1437     struct file_descriptor *fd = file_descriptor_find(name, hash);
1438     if(fd) {
1439         // found
1440         if(unlikely(debug))
1441             fprintf(stderr, "apps.plugin:   >> found on slot %d\n", fd->pos);
1442
1443         fd->count++;
1444         return fd->pos;
1445     }
1446     // not found
1447
1448     FD_FILETYPE type;
1449     if(likely(name[0] == '/')) type = FILETYPE_FILE;
1450     else if(likely(strncmp(name, "pipe:", 5) == 0)) type = FILETYPE_PIPE;
1451     else if(likely(strncmp(name, "socket:", 7) == 0)) type = FILETYPE_SOCKET;
1452     else if(likely(strncmp(name, "anon_inode:", 11) == 0)) {
1453         const char *t = &name[11];
1454
1455              if(strcmp(t, "inotify") == 0) type = FILETYPE_INOTIFY;
1456         else if(strcmp(t, "[eventfd]") == 0) type = FILETYPE_EVENTFD;
1457         else if(strcmp(t, "[eventpoll]") == 0) type = FILETYPE_EVENTPOLL;
1458         else if(strcmp(t, "[timerfd]") == 0) type = FILETYPE_TIMERFD;
1459         else if(strcmp(t, "[signalfd]") == 0) type = FILETYPE_SIGNALFD;
1460         else {
1461             if(unlikely(debug))
1462                 fprintf(stderr, "apps.plugin: FIXME: unknown anonymous inode: %s\n", name);
1463
1464             type = FILETYPE_OTHER;
1465         }
1466     }
1467     else if(likely(strcmp(name, "inotify") == 0)) type = FILETYPE_INOTIFY;
1468     else {
1469         if(unlikely(debug))
1470             fprintf(stderr, "apps.plugin: FIXME: cannot understand linkname: %s\n", name);
1471
1472         type = FILETYPE_OTHER;
1473     }
1474
1475     return file_descriptor_set_on_empty_slot(name, hash, type);
1476 }
1477
1478 static inline void make_all_pid_fds_negative(struct pid_stat *p) {
1479     int *fd = p->fds, *end = &p->fds[p->fds_size];
1480     while(fd < end) {
1481         *fd = -(*fd);
1482         fd++;
1483     }
1484 }
1485
1486 static inline void cleanup_negative_pid_fds(struct pid_stat *p) {
1487     int *fd = p->fds, *fdend = &p->fds[p->fds_size];
1488
1489     while(fd < fdend) {
1490         if(unlikely(*fd < 0)) {
1491             file_descriptor_not_used(-(*fd));
1492             *fd++ = 0;
1493         }
1494         else
1495             fd++;
1496     }
1497 }
1498
1499 static inline void zero_pid_fds(struct pid_stat *p, int first, int size) {
1500     int *fd = &p->fds[first], *end = &p->fds[first + size];
1501     while(fd < end) *fd++ = 0;
1502 }
1503
1504 static inline int read_pid_file_descriptors(struct pid_stat *p, void *ptr) {
1505     (void)ptr;
1506 #ifdef __FreeBSD__
1507     int mib[4];
1508     size_t size;
1509     struct kinfo_file *fds;
1510     static char *fdsbuf;
1511     char *bfdsbuf, *efdsbuf;
1512     char fdsname[FILENAME_MAX + 1];
1513
1514     // we make all pid fds negative, so that
1515     // we can detect unused file descriptors
1516     // at the end, to free them
1517     make_all_pid_fds_negative(p);
1518
1519     mib[0] = CTL_KERN;
1520     mib[1] = KERN_PROC;
1521     mib[2] = KERN_PROC_FILEDESC;
1522     mib[3] = p->pid;
1523
1524     if (unlikely(sysctl(mib, 4, NULL, &size, NULL, 0))) {
1525         error("sysctl error: Can't get file descriptors data size for pid %d", p->pid);
1526         return 0;
1527     }
1528     if (likely(size > 0))
1529         fdsbuf = reallocz(fdsbuf, size);
1530     if (unlikely(sysctl(mib, 4, fdsbuf, &size, NULL, 0))) {
1531         error("sysctl error: Can't get file descriptors data for pid %d", p->pid);
1532         return 0;
1533     }
1534
1535     bfdsbuf = fdsbuf;
1536     efdsbuf = fdsbuf + size;
1537     while (bfdsbuf < efdsbuf) {
1538         fds = (struct kinfo_file *)(uintptr_t)bfdsbuf;
1539         if (unlikely(fds->kf_structsize == 0))
1540             break;
1541
1542         // do not process file descriptors for current working directory, root directory,
1543         // jail directory, ktrace vnode, text vnode and controlling terminal
1544         if (unlikely(fds->kf_fd < 0)) {
1545             bfdsbuf += fds->kf_structsize;
1546             continue;
1547         }
1548
1549         // get file descriptors array index
1550         int fdid = fds->kf_fd;
1551
1552         // check if the fds array is small
1553         if (unlikely(fdid >= p->fds_size)) {
1554             // it is small, extend it
1555
1556             if (unlikely(debug))
1557                 fprintf(stderr, "apps.plugin: extending fd memory slots for %s from %d to %d\n", p->comm, p->fds_size, fdid + MAX_SPARE_FDS);
1558
1559             p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(int));
1560
1561             // and initialize it
1562             zero_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
1563             p->fds_size = fdid + MAX_SPARE_FDS;
1564         }
1565
1566         if (unlikely(p->fds[fdid] == 0)) {
1567             // we don't know this fd, get it
1568
1569             switch (fds->kf_type) {
1570                 case KF_TYPE_FIFO:
1571                 case KF_TYPE_VNODE:
1572                     if (unlikely(!fds->kf_path[0])) {
1573                         sprintf(fdsname, "other: inode: %lu", fds->kf_un.kf_file.kf_file_fileid);
1574                         break;
1575                     }
1576                     sprintf(fdsname, "%s", fds->kf_path);
1577                     break;
1578                 case KF_TYPE_SOCKET:
1579                     switch (fds->kf_sock_domain) {
1580                         case AF_INET:
1581                         case AF_INET6:
1582                             if (fds->kf_sock_protocol == IPPROTO_TCP)
1583                                 sprintf(fdsname, "socket: %d %lx", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sock_inpcb);
1584                             else
1585                                 sprintf(fdsname, "socket: %d %lx", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sock_pcb);
1586                             break;
1587                         case AF_UNIX:
1588                             /* print address of pcb and connected pcb */
1589                             sprintf(fdsname, "socket: %lx %lx", fds->kf_un.kf_sock.kf_sock_pcb, fds->kf_un.kf_sock.kf_sock_unpconn);
1590                             break;
1591                         default:
1592                             /* print protocol number and socket address */
1593                             sprintf(fdsname, "socket: other: %d %s %s", fds->kf_sock_protocol, fds->kf_sa_local.__ss_pad1, fds->kf_sa_local.__ss_pad2);
1594                     }
1595                     break;
1596                 case KF_TYPE_PIPE:
1597                     sprintf(fdsname, "pipe: %lu %lu", fds->kf_un.kf_pipe.kf_pipe_addr, fds->kf_un.kf_pipe.kf_pipe_peer);
1598                     break;
1599                 case KF_TYPE_PTS:
1600                     sprintf(fdsname, "other: pts: %u", fds->kf_un.kf_pts.kf_pts_dev);
1601                     break;
1602                 case KF_TYPE_SHM:
1603                     sprintf(fdsname, "other: shm: %s size: %lu", fds->kf_path, fds->kf_un.kf_file.kf_file_size);
1604                     break;
1605                 case KF_TYPE_SEM:
1606                     sprintf(fdsname, "other: sem: %u", fds->kf_un.kf_sem.kf_sem_value);
1607                     break;
1608                 default:
1609                     sprintf(fdsname, "other: pid: %d fd: %d", fds->kf_un.kf_proc.kf_pid, fds->kf_fd);
1610             }
1611
1612             // if another process already has this, we will get
1613             // the same id
1614             p->fds[fdid] = file_descriptor_find_or_add(fdsname);
1615         }
1616
1617             // else make it positive again, we need it
1618             // of course, the actual file may have changed, but we don't care so much
1619             // FIXME: we could compare the inode as returned by readdir dirent structure
1620
1621         else
1622             p->fds[fdid] = -p->fds[fdid];
1623
1624         bfdsbuf += fds->kf_structsize;
1625     }
1626 #else
1627     if(unlikely(!p->fds_dirname)) {
1628         char dirname[FILENAME_MAX+1];
1629         snprintfz(dirname, FILENAME_MAX, "%s/proc/%d/fd", netdata_configured_host_prefix, p->pid);
1630         p->fds_dirname = strdupz(dirname);
1631     }
1632
1633     DIR *fds = opendir(p->fds_dirname);
1634     if(unlikely(!fds)) return 0;
1635
1636     struct dirent *de;
1637     char fdname[FILENAME_MAX + 1];
1638     char linkname[FILENAME_MAX + 1];
1639
1640     // we make all pid fds negative, so that
1641     // we can detect unused file descriptors
1642     // at the end, to free them
1643     make_all_pid_fds_negative(p);
1644
1645     while((de = readdir(fds))) {
1646         // we need only files with numeric names
1647
1648         if(unlikely(de->d_name[0] < '0' || de->d_name[0] > '9'))
1649             continue;
1650
1651         // get its number
1652         int fdid = (int) str2l(de->d_name);
1653         if(unlikely(fdid < 0)) continue;
1654
1655         // check if the fds array is small
1656         if(unlikely(fdid >= p->fds_size)) {
1657             // it is small, extend it
1658
1659             if(unlikely(debug))
1660                 fprintf(stderr
1661                         , "apps.plugin: extending fd memory slots for %s from %d to %d\n"
1662                         , p->comm
1663                         , p->fds_size
1664                         , fdid + MAX_SPARE_FDS
1665                 );
1666
1667             p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(int));
1668
1669             // and initialize it
1670             zero_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
1671             p->fds_size = fdid + MAX_SPARE_FDS;
1672         }
1673
1674         if(unlikely(p->fds[fdid] == 0)) {
1675             // we don't know this fd, get it
1676
1677             sprintf(fdname, "%s/proc/%d/fd/%s", netdata_configured_host_prefix, p->pid, de->d_name);
1678             ssize_t l = readlink(fdname, linkname, FILENAME_MAX);
1679             if(unlikely(l == -1)) {
1680                 if(debug || (p->target && p->target->debug)) {
1681                     if(debug || (p->target && p->target->debug))
1682                         error("Cannot read link %s", fdname);
1683                 }
1684                 continue;
1685             }
1686             else
1687                 linkname[l] = '\0';
1688
1689             file_counter++;
1690
1691             // if another process already has this, we will get
1692             // the same id
1693             p->fds[fdid] = file_descriptor_find_or_add(linkname);
1694         }
1695
1696             // else make it positive again, we need it
1697             // of course, the actual file may have changed, but we don't care so much
1698             // FIXME: we could compare the inode as returned by readdir dirent structure
1699             // UPDATE: no we cannot use inodes - under /proc inodes don't change when the link is changed
1700
1701         else
1702             p->fds[fdid] = -p->fds[fdid];
1703     }
1704
1705     closedir(fds);
1706 #endif
1707     cleanup_negative_pid_fds(p);
1708
1709     return 1;
1710 }
1711
1712 // ----------------------------------------------------------------------------
1713
1714 static inline int print_process_and_parents(struct pid_stat *p, usec_t time) {
1715     char *prefix = "\\_ ";
1716     int indent = 0;
1717
1718     if(p->parent)
1719         indent = print_process_and_parents(p->parent, p->stat_collected_usec);
1720     else
1721         prefix = " > ";
1722
1723     char buffer[indent + 1];
1724     int i;
1725
1726     for(i = 0; i < indent ;i++) buffer[i] = ' ';
1727     buffer[i] = '\0';
1728
1729     fprintf(stderr, "  %s %s%s (%d %s %llu"
1730         , buffer
1731         , prefix
1732         , p->comm
1733         , p->pid
1734         , p->updated?"running":"exited"
1735         , p->stat_collected_usec - time
1736         );
1737
1738     if(p->utime)   fprintf(stderr, " utime=" KERNEL_UINT_FORMAT,   p->utime);
1739     if(p->stime)   fprintf(stderr, " stime=" KERNEL_UINT_FORMAT,   p->stime);
1740     if(p->gtime)   fprintf(stderr, " gtime=" KERNEL_UINT_FORMAT,   p->gtime);
1741     if(p->cutime)  fprintf(stderr, " cutime=" KERNEL_UINT_FORMAT,  p->cutime);
1742     if(p->cstime)  fprintf(stderr, " cstime=" KERNEL_UINT_FORMAT,  p->cstime);
1743     if(p->cgtime)  fprintf(stderr, " cgtime=" KERNEL_UINT_FORMAT,  p->cgtime);
1744     if(p->minflt)  fprintf(stderr, " minflt=" KERNEL_UINT_FORMAT,  p->minflt);
1745     if(p->cminflt) fprintf(stderr, " cminflt=" KERNEL_UINT_FORMAT, p->cminflt);
1746     if(p->majflt)  fprintf(stderr, " majflt=" KERNEL_UINT_FORMAT,  p->majflt);
1747     if(p->cmajflt) fprintf(stderr, " cmajflt=" KERNEL_UINT_FORMAT, p->cmajflt);
1748     fprintf(stderr, ")\n");
1749
1750     return indent + 1;
1751 }
1752
1753 static inline void print_process_tree(struct pid_stat *p, char *msg) {
1754     log_date(stderr);
1755     fprintf(stderr, "%s: process %s (%d, %s) with parents:\n", msg, p->comm, p->pid, p->updated?"running":"exited");
1756     print_process_and_parents(p, p->stat_collected_usec);
1757 }
1758
1759 static inline void find_lost_child_debug(struct pid_stat *pe, kernel_uint_t lost, int type) {
1760     int found = 0;
1761     struct pid_stat *p = NULL;
1762
1763     for(p = root_of_pids; p ; p = p->next) {
1764         if(p == pe) continue;
1765
1766         switch(type) {
1767             case 1:
1768                 if(p->cminflt > lost) {
1769                     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);
1770                     found++;
1771                 }
1772                 break;
1773
1774             case 2:
1775                 if(p->cmajflt > lost) {
1776                     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);
1777                     found++;
1778                 }
1779                 break;
1780
1781             case 3:
1782                 if(p->cutime > lost) {
1783                     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);
1784                     found++;
1785                 }
1786                 break;
1787
1788             case 4:
1789                 if(p->cstime > lost) {
1790                     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);
1791                     found++;
1792                 }
1793                 break;
1794
1795             case 5:
1796                 if(p->cgtime > lost) {
1797                     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);
1798                     found++;
1799                 }
1800                 break;
1801         }
1802     }
1803
1804     if(!found) {
1805         switch(type) {
1806             case 1:
1807                 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);
1808                 break;
1809
1810             case 2:
1811                 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);
1812                 break;
1813
1814             case 3:
1815                 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);
1816                 break;
1817
1818             case 4:
1819                 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);
1820                 break;
1821
1822             case 5:
1823                 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);
1824                 break;
1825         }
1826     }
1827 }
1828
1829 static inline kernel_uint_t remove_exited_child_from_parent(kernel_uint_t *field, kernel_uint_t *pfield) {
1830     kernel_uint_t absorbed = 0;
1831
1832     if(*field > *pfield) {
1833         absorbed += *pfield;
1834         *field -= *pfield;
1835         *pfield = 0;
1836     }
1837     else {
1838         absorbed += *field;
1839         *pfield -= *field;
1840         *field = 0;
1841     }
1842
1843     return absorbed;
1844 }
1845
1846 static inline void process_exited_processes() {
1847     struct pid_stat *p;
1848
1849     for(p = root_of_pids; p ; p = p->next) {
1850         if(p->updated || !p->stat_collected_usec)
1851             continue;
1852
1853         kernel_uint_t utime  = (p->utime_raw + p->cutime_raw)   * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1854         kernel_uint_t stime  = (p->stime_raw + p->cstime_raw)   * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1855         kernel_uint_t gtime  = (p->gtime_raw + p->cgtime_raw)   * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1856         kernel_uint_t minflt = (p->minflt_raw + p->cminflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1857         kernel_uint_t majflt = (p->majflt_raw + p->cmajflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1858
1859         if(utime + stime + gtime + minflt + majflt == 0)
1860             continue;
1861
1862         if(unlikely(debug)) {
1863             log_date(stderr);
1864             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"
1865                 , p->comm
1866                 , p->pid
1867                 , p->updated?"running":"exited"
1868                 , utime
1869                 , stime
1870                 , gtime
1871                 , minflt
1872                 , majflt
1873                 );
1874             print_process_tree(p, "Searching parents");
1875         }
1876
1877         struct pid_stat *pp;
1878         for(pp = p->parent; pp ; pp = pp->parent) {
1879             if(!pp->updated) continue;
1880
1881             kernel_uint_t absorbed;
1882             absorbed = remove_exited_child_from_parent(&utime,  &pp->cutime);
1883             if(unlikely(debug && absorbed))
1884                 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);
1885
1886             absorbed = remove_exited_child_from_parent(&stime,  &pp->cstime);
1887             if(unlikely(debug && absorbed))
1888                 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);
1889
1890             absorbed = remove_exited_child_from_parent(&gtime,  &pp->cgtime);
1891             if(unlikely(debug && absorbed))
1892                 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);
1893
1894             absorbed = remove_exited_child_from_parent(&minflt, &pp->cminflt);
1895             if(unlikely(debug && absorbed))
1896                 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);
1897
1898             absorbed = remove_exited_child_from_parent(&majflt, &pp->cmajflt);
1899             if(unlikely(debug && absorbed))
1900                 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);
1901         }
1902
1903         if(unlikely(utime + stime + gtime + minflt + majflt > 0)) {
1904             if(unlikely(debug)) {
1905                 if(utime)  find_lost_child_debug(p, utime,  3);
1906                 if(stime)  find_lost_child_debug(p, stime,  4);
1907                 if(gtime)  find_lost_child_debug(p, gtime,  5);
1908                 if(minflt) find_lost_child_debug(p, minflt, 1);
1909                 if(majflt) find_lost_child_debug(p, majflt, 2);
1910             }
1911
1912             p->keep = 1;
1913
1914             if(unlikely(debug))
1915                 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"
1916                     , p->comm
1917                     , p->pid
1918                     , p->updated?"running":"exited"
1919                     , utime
1920                     , stime
1921                     , gtime
1922                     , minflt
1923                     , majflt
1924                     );
1925
1926             for(pp = p->parent; pp ; pp = pp->parent) {
1927                 if(pp->updated) break;
1928                 pp->keep = 1;
1929
1930                 if(unlikely(debug))
1931                     fprintf(stderr, " > - KEEP - parent for another loop: %s (%d %s)\n"
1932                         , pp->comm
1933                         , pp->pid
1934                         , pp->updated?"running":"exited"
1935                         );
1936             }
1937
1938             p->utime_raw   = utime  * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1939             p->stime_raw   = stime  * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1940             p->gtime_raw   = gtime  * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1941             p->minflt_raw  = minflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1942             p->majflt_raw  = majflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1943             p->cutime_raw = p->cstime_raw = p->cgtime_raw = p->cminflt_raw = p->cmajflt_raw = 0;
1944
1945             if(unlikely(debug))
1946                 fprintf(stderr, "\n");
1947         }
1948         else if(unlikely(debug)) {
1949             fprintf(stderr, " > totally absorbed - DONE - %s (%d %s)\n"
1950                 , p->comm
1951                 , p->pid
1952                 , p->updated?"running":"exited"
1953                 );
1954         }
1955     }
1956 }
1957
1958 static inline void link_all_processes_to_their_parents(void) {
1959     struct pid_stat *p, *pp;
1960
1961     // link all children to their parents
1962     // and update children count on parents
1963     for(p = root_of_pids; p ; p = p->next) {
1964         // for each process found
1965
1966         p->sortlist = 0;
1967         p->parent = NULL;
1968
1969         if(unlikely(!p->ppid)) {
1970             p->parent = NULL;
1971             continue;
1972         }
1973
1974         pp = all_pids[p->ppid];
1975         if(likely(pp)) {
1976             p->parent = pp;
1977             pp->children_count++;
1978
1979             if(unlikely(debug || (p->target && p->target->debug)))
1980                 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);
1981         }
1982         else {
1983             p->parent = NULL;
1984             error("pid %d %s states parent %d, but the later does not exist.", p->pid, p->comm, p->ppid);
1985         }
1986     }
1987 }
1988
1989 // ----------------------------------------------------------------------------
1990
1991 // 1. read all files in /proc
1992 // 2. for each numeric directory:
1993 //    i.   read /proc/pid/stat
1994 //    ii.  read /proc/pid/statm
1995 //    iii. read /proc/pid/io (requires root access)
1996 //    iii. read the entries in directory /proc/pid/fd (requires root access)
1997 //         for each entry:
1998 //         a. find or create a struct file_descriptor
1999 //         b. cleanup any old/unused file_descriptors
2000
2001 // after all these, some pids may be linked to targets, while others may not
2002
2003 // in case of errors, only 1 every 1000 errors is printed
2004 // to avoid filling up all disk space
2005 // if debug is enabled, all errors are printed
2006
2007 #ifndef __FreeBSD__
2008 static int compar_pid(const void *pid1, const void *pid2) {
2009
2010     struct pid_stat *p1 = all_pids[*((pid_t *)pid1)];
2011     struct pid_stat *p2 = all_pids[*((pid_t *)pid2)];
2012
2013     if(p1->sortlist > p2->sortlist)
2014         return -1;
2015     else
2016         return 1;
2017 }
2018 #endif
2019
2020 static inline int collect_data_for_pid(pid_t pid, void *ptr) {
2021     if(unlikely(pid < INIT_PID || pid > pid_max)) {
2022         error("Invalid pid %d read (expected %d to %d). Ignoring process.", pid, INIT_PID, pid_max);
2023         return 0;
2024     }
2025
2026     struct pid_stat *p = get_pid_entry(pid);
2027     if(unlikely(!p || p->read)) return 0;
2028     p->read = 1;
2029
2030     // fprintf(stderr, "Reading process %d (%s), sortlist %d\n", p->pid, p->comm, p->sortlist);
2031
2032     // --------------------------------------------------------------------
2033     // /proc/<pid>/stat
2034
2035     if(unlikely(!managed_log(p, PID_LOG_STAT, read_proc_pid_stat(p, ptr))))
2036         // there is no reason to proceed if we cannot get its status
2037         return 0;
2038
2039     read_proc_pid_ownership(p, ptr);
2040
2041     // check its parent pid
2042     if(unlikely(p->ppid < 0 || p->ppid > pid_max)) {
2043         error("Pid %d (command '%s') states invalid parent pid %d. Using 0.", pid, p->comm, p->ppid);
2044         p->ppid = 0;
2045     }
2046
2047     // --------------------------------------------------------------------
2048     // /proc/<pid>/io
2049
2050     managed_log(p, PID_LOG_IO, read_proc_pid_io(p, ptr));
2051
2052     // --------------------------------------------------------------------
2053     // /proc/<pid>/statm
2054
2055     if(unlikely(!managed_log(p, PID_LOG_STATM, read_proc_pid_statm(p, ptr))))
2056         // there is no reason to proceed if we cannot get its memory status
2057         return 0;
2058
2059     // --------------------------------------------------------------------
2060     // /proc/<pid>/fd
2061
2062     if(enable_file_charts)
2063             managed_log(p, PID_LOG_FDS, read_pid_file_descriptors(p, ptr));
2064
2065     // --------------------------------------------------------------------
2066     // done!
2067
2068     if(unlikely(debug && include_exited_childs && all_pids_count && p->ppid && all_pids[p->ppid] && !all_pids[p->ppid]->read))
2069         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);
2070
2071     // mark it as updated
2072     p->updated = 1;
2073     p->keep = 0;
2074     p->keeploops = 0;
2075
2076     return 1;
2077 }
2078
2079 static int collect_data_for_all_processes(void) {
2080     struct pid_stat *p = NULL;
2081
2082 #ifdef __FreeBSD__
2083     int i, procnum;
2084     size_t procbase_size;
2085     static struct kinfo_proc *procbase;
2086
2087     int mib[3];
2088
2089     mib[0] = CTL_KERN;
2090     mib[1] = KERN_PROC;
2091     mib[2] = KERN_PROC_PROC;
2092     if (unlikely(sysctl(mib, 3, NULL, &procbase_size, NULL, 0))) {
2093         error("sysctl error: Can't get processes data size");
2094         return 0;
2095     }
2096     procbase = reallocz(procbase, procbase_size);
2097     if (unlikely(sysctl(mib, 3, procbase, &procbase_size, NULL, 0))) {
2098         error("sysctl error: Can't get processes data");
2099         return 0;
2100     }
2101     procnum = procbase_size / sizeof(struct kinfo_proc);
2102 #endif
2103
2104     if(all_pids_count) {
2105 #ifndef __FreeBSD__
2106         size_t slc = 0;
2107 #endif
2108         for(p = root_of_pids; p ; p = p->next) {
2109             p->read             = 0; // mark it as not read, so that collect_data_for_pid() will read it
2110             p->updated          = 0;
2111             p->merged           = 0;
2112             p->children_count   = 0;
2113             p->parent           = NULL;
2114
2115 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
2116             all_pids_sortlist[slc++] = p->pid;
2117 #endif
2118         }
2119
2120 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
2121         if(unlikely(slc != all_pids_count)) {
2122             error("Internal error: I was thinking I had %zu processes in my arrays, but it seems there are more.", all_pids_count);
2123             all_pids_count = slc;
2124         }
2125
2126         if(include_exited_childs) {
2127             // Read parents before childs
2128             // This is needed to prevent a situation where
2129             // a child is found running, but until we read
2130             // its parent, it has exited and its parent
2131             // has accumulated its resources.
2132
2133             qsort((void *)all_pids_sortlist, (size_t)all_pids_count, sizeof(pid_t), compar_pid);
2134
2135             // we forward read all running processes
2136             // collect_data_for_pid() is smart enough,
2137             // not to read the same pid twice per iteration
2138             for(slc = 0; slc < all_pids_count; slc++)
2139                 collect_data_for_pid(all_pids_sortlist[slc], NULL);
2140         }
2141 #endif
2142     }
2143
2144 #ifdef __FreeBSD__
2145     for (i = INIT_PID; i < procnum - INIT_PID; ++i) {
2146         pid_t pid = procbase[i].ki_pid;
2147         collect_data_for_pid(pid, &procbase[i]);
2148     }
2149 #else
2150     char dirname[FILENAME_MAX + 1];
2151
2152     snprintfz(dirname, FILENAME_MAX, "%s/proc", netdata_configured_host_prefix);
2153     DIR *dir = opendir(dirname);
2154     if(!dir) return 0;
2155
2156     struct dirent *de = NULL;
2157
2158     while((de = readdir(dir))) {
2159         char *endptr = de->d_name;
2160
2161         if(unlikely(de->d_type != DT_DIR || de->d_name[0] < '0' || de->d_name[0] > '9'))
2162             continue;
2163
2164         pid_t pid = (pid_t) strtoul(de->d_name, &endptr, 10);
2165
2166         // make sure we read a valid number
2167         if(unlikely(endptr == de->d_name || *endptr != '\0'))
2168             continue;
2169
2170         collect_data_for_pid(pid, NULL);
2171     }
2172     closedir(dir);
2173 #endif
2174
2175     if(!all_pids_count)
2176         return 0;
2177
2178     // we need /proc/stat to normalize the cpu consumption of the exited childs
2179     read_proc_stat();
2180
2181     // build the process tree
2182     link_all_processes_to_their_parents();
2183
2184     // normally this is done
2185     // however we may have processes exited while we collected values
2186     // so let's find the exited ones
2187     // we do this by collecting the ownership of process
2188     // if we manage to get the ownership, the process still runs
2189     process_exited_processes();
2190
2191     return 1;
2192 }
2193
2194 // ----------------------------------------------------------------------------
2195 // update statistics on the targets
2196
2197 // 1. link all childs to their parents
2198 // 2. go from bottom to top, marking as merged all childs to their parents
2199 //    this step links all parents without a target to the child target, if any
2200 // 3. link all top level processes (the ones not merged) to the default target
2201 // 4. go from top to bottom, linking all childs without a target, to their parent target
2202 //    after this step, all processes have a target
2203 // [5. for each killed pid (updated = 0), remove its usage from its target]
2204 // 6. zero all apps_groups_targets
2205 // 7. concentrate all values on the apps_groups_targets
2206 // 8. remove all killed processes
2207 // 9. find the unique file count for each target
2208 // check: update_apps_groups_statistics()
2209
2210 static void cleanup_exited_pids(void) {
2211     int c;
2212     struct pid_stat *p = NULL;
2213
2214     for(p = root_of_pids; p ;) {
2215         if(!p->updated && (!p->keep || p->keeploops > 0)) {
2216             if(unlikely(debug && (p->keep || p->keeploops)))
2217                 fprintf(stderr, " > CLEANUP cannot keep exited process %d (%s) anymore - removing it.\n", p->pid, p->comm);
2218
2219             for(c = 0; c < p->fds_size; c++)
2220                 if(p->fds[c] > 0) {
2221                     file_descriptor_not_used(p->fds[c]);
2222                     p->fds[c] = 0;
2223                 }
2224
2225             pid_t r = p->pid;
2226             p = p->next;
2227             del_pid_entry(r);
2228         }
2229         else {
2230             if(unlikely(p->keep)) p->keeploops++;
2231             p->keep = 0;
2232             p = p->next;
2233         }
2234     }
2235 }
2236
2237 static void apply_apps_groups_targets_inheritance(void) {
2238     struct pid_stat *p = NULL;
2239
2240     // children that do not have a target
2241     // inherit their target from their parent
2242     int found = 1, loops = 0;
2243     while(found) {
2244         if(unlikely(debug)) loops++;
2245         found = 0;
2246         for(p = root_of_pids; p ; p = p->next) {
2247             // if this process does not have a target
2248             // and it has a parent
2249             // and its parent has a target
2250             // then, set the parent's target to this process
2251             if(unlikely(!p->target && p->parent && p->parent->target)) {
2252                 p->target = p->parent->target;
2253                 found++;
2254
2255                 if(debug || (p->target && p->target->debug))
2256                     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);
2257             }
2258         }
2259     }
2260
2261     // find all the procs with 0 childs and merge them to their parents
2262     // repeat, until nothing more can be done.
2263     int sortlist = 1;
2264     found = 1;
2265     while(found) {
2266         if(unlikely(debug)) loops++;
2267         found = 0;
2268
2269         for(p = root_of_pids; p ; p = p->next) {
2270             if(unlikely(!p->sortlist && !p->children_count))
2271                 p->sortlist = sortlist++;
2272
2273             // if this process does not have any children
2274             // and is not already merged
2275             // and has a parent
2276             // and its parent has children
2277             // and the target of this process and its parent is the same, or the parent does not have a target
2278             // and its parent is not init
2279             // then, mark them as merged.
2280             if(unlikely(
2281                     !p->children_count
2282                     && !p->merged
2283                     && p->parent
2284                     && p->parent->children_count
2285                     && (p->target == p->parent->target || !p->parent->target)
2286                     && p->ppid != INIT_PID
2287                 )) {
2288                 p->parent->children_count--;
2289                 p->merged = 1;
2290
2291                 // the parent inherits the child's target, if it does not have a target itself
2292                 if(unlikely(p->target && !p->parent->target)) {
2293                     p->parent->target = p->target;
2294
2295                     if(debug || (p->target && p->target->debug))
2296                         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);
2297                 }
2298
2299                 found++;
2300             }
2301         }
2302
2303         if(unlikely(debug))
2304             fprintf(stderr, "apps.plugin: TARGET INHERITANCE: merged %d processes\n", found);
2305     }
2306
2307     // init goes always to default target
2308     if(all_pids[INIT_PID])
2309         all_pids[INIT_PID]->target = apps_groups_default_target;
2310
2311     // give a default target on all top level processes
2312     if(unlikely(debug)) loops++;
2313     for(p = root_of_pids; p ; p = p->next) {
2314         // if the process is not merged itself
2315         // then is is a top level process
2316         if(unlikely(!p->merged && !p->target))
2317             p->target = apps_groups_default_target;
2318
2319         // make sure all processes have a sortlist
2320         if(unlikely(!p->sortlist))
2321             p->sortlist = sortlist++;
2322     }
2323
2324     if(all_pids[1])
2325         all_pids[1]->sortlist = sortlist++;
2326
2327     // give a target to all merged child processes
2328     found = 1;
2329     while(found) {
2330         if(unlikely(debug)) loops++;
2331         found = 0;
2332         for(p = root_of_pids; p ; p = p->next) {
2333             if(unlikely(!p->target && p->merged && p->parent && p->parent->target)) {
2334                 p->target = p->parent->target;
2335                 found++;
2336
2337                 if(debug || (p->target && p->target->debug))
2338                     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);
2339             }
2340         }
2341     }
2342
2343     if(unlikely(debug))
2344         fprintf(stderr, "apps.plugin: apply_apps_groups_targets_inheritance() made %d loops on the process tree\n", loops);
2345 }
2346
2347 static size_t zero_all_targets(struct target *root) {
2348     struct target *w;
2349     size_t count = 0;
2350
2351     for (w = root; w ; w = w->next) {
2352         count++;
2353
2354         w->minflt = 0;
2355         w->majflt = 0;
2356         w->utime = 0;
2357         w->stime = 0;
2358         w->gtime = 0;
2359         w->cminflt = 0;
2360         w->cmajflt = 0;
2361         w->cutime = 0;
2362         w->cstime = 0;
2363         w->cgtime = 0;
2364         w->num_threads = 0;
2365         // w->rss = 0;
2366         w->processes = 0;
2367
2368         w->statm_size = 0;
2369         w->statm_resident = 0;
2370         w->statm_share = 0;
2371         // w->statm_text = 0;
2372         // w->statm_lib = 0;
2373         // w->statm_data = 0;
2374         // w->statm_dirty = 0;
2375
2376         w->io_logical_bytes_read = 0;
2377         w->io_logical_bytes_written = 0;
2378         // w->io_read_calls = 0;
2379         // w->io_write_calls = 0;
2380         w->io_storage_bytes_read = 0;
2381         w->io_storage_bytes_written = 0;
2382         // w->io_cancelled_write_bytes = 0;
2383
2384         // zero file counters
2385         if(w->target_fds) {
2386             memset(w->target_fds, 0, sizeof(int) * w->target_fds_size);
2387             w->openfiles = 0;
2388             w->openpipes = 0;
2389             w->opensockets = 0;
2390             w->openinotifies = 0;
2391             w->openeventfds = 0;
2392             w->opentimerfds = 0;
2393             w->opensignalfds = 0;
2394             w->openeventpolls = 0;
2395             w->openother = 0;
2396         }
2397     }
2398
2399     return count;
2400 }
2401
2402 static inline void reallocate_target_fds(struct target *w) {
2403     if(unlikely(!w))
2404         return;
2405
2406     if(unlikely(!w->target_fds || w->target_fds_size < all_files_size)) {
2407         w->target_fds = reallocz(w->target_fds, sizeof(int) * all_files_size);
2408         memset(&w->target_fds[w->target_fds_size], 0, sizeof(int) * (all_files_size - w->target_fds_size));
2409         w->target_fds_size = all_files_size;
2410     }
2411 }
2412
2413 static inline void aggregate_fd_on_target(int fd, struct target *w) {
2414     if(unlikely(!w))
2415         return;
2416
2417     if(unlikely(w->target_fds[fd])) {
2418         // it is already aggregated
2419         // just increase its usage counter
2420         w->target_fds[fd]++;
2421         return;
2422     }
2423
2424     // increase its usage counter
2425     // so that we will not add it again
2426     w->target_fds[fd]++;
2427
2428     switch(all_files[fd].type) {
2429         case FILETYPE_FILE:
2430             w->openfiles++;
2431             break;
2432
2433         case FILETYPE_PIPE:
2434             w->openpipes++;
2435             break;
2436
2437         case FILETYPE_SOCKET:
2438             w->opensockets++;
2439             break;
2440
2441         case FILETYPE_INOTIFY:
2442             w->openinotifies++;
2443             break;
2444
2445         case FILETYPE_EVENTFD:
2446             w->openeventfds++;
2447             break;
2448
2449         case FILETYPE_TIMERFD:
2450             w->opentimerfds++;
2451             break;
2452
2453         case FILETYPE_SIGNALFD:
2454             w->opensignalfds++;
2455             break;
2456
2457         case FILETYPE_EVENTPOLL:
2458             w->openeventpolls++;
2459             break;
2460
2461         case FILETYPE_OTHER:
2462             w->openother++;
2463             break;
2464     }
2465 }
2466
2467 static inline void aggregate_pid_fds_on_targets(struct pid_stat *p) {
2468
2469     if(unlikely(!p->updated)) {
2470         // the process is not running
2471         return;
2472     }
2473
2474     struct target *w = p->target, *u = p->user_target, *g = p->group_target;
2475
2476     reallocate_target_fds(w);
2477     reallocate_target_fds(u);
2478     reallocate_target_fds(g);
2479
2480     int c, size = p->fds_size, *fds = p->fds;
2481     for(c = 0; c < size ;c++) {
2482         int fd = fds[c];
2483
2484         if(likely(fd <= 0 || fd >= all_files_size))
2485             continue;
2486
2487         aggregate_fd_on_target(fd, w);
2488         aggregate_fd_on_target(fd, u);
2489         aggregate_fd_on_target(fd, g);
2490     }
2491 }
2492
2493 static inline void aggregate_pid_on_target(struct target *w, struct pid_stat *p, struct target *o) {
2494     (void)o;
2495
2496     if(unlikely(!p->updated)) {
2497         // the process is not running
2498         return;
2499     }
2500
2501     if(unlikely(!w)) {
2502         error("pid %d %s was left without a target!", p->pid, p->comm);
2503         return;
2504     }
2505
2506     w->cutime  += p->cutime;
2507     w->cstime  += p->cstime;
2508     w->cgtime  += p->cgtime;
2509     w->cminflt += p->cminflt;
2510     w->cmajflt += p->cmajflt;
2511
2512     w->utime  += p->utime;
2513     w->stime  += p->stime;
2514     w->gtime  += p->gtime;
2515     w->minflt += p->minflt;
2516     w->majflt += p->majflt;
2517
2518     // w->rss += p->rss;
2519
2520     w->statm_size += p->statm_size;
2521     w->statm_resident += p->statm_resident;
2522     w->statm_share += p->statm_share;
2523     // w->statm_text += p->statm_text;
2524     // w->statm_lib += p->statm_lib;
2525     // w->statm_data += p->statm_data;
2526     // w->statm_dirty += p->statm_dirty;
2527
2528     w->io_logical_bytes_read    += p->io_logical_bytes_read;
2529     w->io_logical_bytes_written += p->io_logical_bytes_written;
2530     // w->io_read_calls            += p->io_read_calls;
2531     // w->io_write_calls           += p->io_write_calls;
2532     w->io_storage_bytes_read    += p->io_storage_bytes_read;
2533     w->io_storage_bytes_written += p->io_storage_bytes_written;
2534     // w->io_cancelled_write_bytes += p->io_cancelled_write_bytes;
2535
2536     w->processes++;
2537     w->num_threads += p->num_threads;
2538
2539     if(unlikely(debug || w->debug))
2540         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);
2541 }
2542
2543 static void calculate_netdata_statistics(void) {
2544
2545     apply_apps_groups_targets_inheritance();
2546
2547     zero_all_targets(users_root_target);
2548     zero_all_targets(groups_root_target);
2549     apps_groups_targets_count = zero_all_targets(apps_groups_root_target);
2550
2551     // this has to be done, before the cleanup
2552     struct pid_stat *p = NULL;
2553     struct target *w = NULL, *o = NULL;
2554
2555     // concentrate everything on the targets
2556     for(p = root_of_pids; p ; p = p->next) {
2557
2558         // --------------------------------------------------------------------
2559         // apps_groups target
2560
2561         aggregate_pid_on_target(p->target, p, NULL);
2562
2563
2564         // --------------------------------------------------------------------
2565         // user target
2566
2567         o = p->user_target;
2568         if(likely(p->user_target && p->user_target->uid == p->uid))
2569             w = p->user_target;
2570         else {
2571             if(unlikely(debug && p->user_target))
2572                     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);
2573
2574             w = p->user_target = get_users_target(p->uid);
2575         }
2576
2577         aggregate_pid_on_target(w, p, o);
2578
2579
2580         // --------------------------------------------------------------------
2581         // user group target
2582
2583         o = p->group_target;
2584         if(likely(p->group_target && p->group_target->gid == p->gid))
2585             w = p->group_target;
2586         else {
2587             if(unlikely(debug && p->group_target))
2588                     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);
2589
2590             w = p->group_target = get_groups_target(p->gid);
2591         }
2592
2593         aggregate_pid_on_target(w, p, o);
2594
2595
2596         // --------------------------------------------------------------------
2597         // aggregate all file descriptors
2598
2599         if(enable_file_charts)
2600             aggregate_pid_fds_on_targets(p);
2601     }
2602
2603     cleanup_exited_pids();
2604 }
2605
2606 // ----------------------------------------------------------------------------
2607 // update chart dimensions
2608
2609 int print_calculated_number(char *str, calculated_number value) { (void)str; (void)value; return 0; }
2610
2611 static inline void send_BEGIN(const char *type, const char *id, usec_t usec) {
2612     fprintf(stdout, "BEGIN %s.%s %llu\n", type, id, usec);
2613 }
2614
2615 static inline void send_SET(const char *name, kernel_uint_t value) {
2616     fprintf(stdout, "SET %s = " KERNEL_UINT_FORMAT "\n", name, value);
2617 }
2618
2619 static inline void send_END(void) {
2620     fprintf(stdout, "END\n");
2621 }
2622
2623 static usec_t send_resource_usage_to_netdata() {
2624     static struct timeval last = { 0, 0 };
2625     static struct rusage me_last;
2626
2627     struct timeval now;
2628     struct rusage me;
2629
2630     usec_t usec;
2631     usec_t cpuuser;
2632     usec_t cpusyst;
2633
2634     if(!last.tv_sec) {
2635         now_monotonic_timeval(&last);
2636         getrusage(RUSAGE_SELF, &me_last);
2637
2638         // the first time, give a zero to allow
2639         // netdata calibrate to the current time
2640         // usec = update_every * USEC_PER_SEC;
2641         usec = 0ULL;
2642         cpuuser = 0;
2643         cpusyst = 0;
2644     }
2645     else {
2646         now_monotonic_timeval(&now);
2647         getrusage(RUSAGE_SELF, &me);
2648
2649         usec = dt_usec(&now, &last);
2650         cpuuser = me.ru_utime.tv_sec * USEC_PER_SEC + me.ru_utime.tv_usec;
2651         cpusyst = me.ru_stime.tv_sec * USEC_PER_SEC + me.ru_stime.tv_usec;
2652
2653         memmove(&last, &now, sizeof(struct timeval));
2654         memmove(&me_last, &me, sizeof(struct rusage));
2655     }
2656
2657     static char created_charts = 0;
2658     if(unlikely(!created_charts)) {
2659         created_charts = 1;
2660
2661         fprintf(stdout
2662                 , "CHART netdata.apps_cpu '' 'Apps Plugin CPU' 'milliseconds/s' apps.plugin netdata.apps_cpu stacked 140000 %1$d\n"
2663                         "DIMENSION user '' incremental 1 1000\n"
2664                         "DIMENSION system '' incremental 1 1000\n"
2665                         "CHART netdata.apps_sizes '' 'Apps Plugin Files' 'files/s' apps.plugin netdata.apps_sizes line 140001 %1$d\n"
2666                         "DIMENSION calls '' incremental 1 1\n"
2667                         "DIMENSION files '' incremental 1 1\n"
2668                         "DIMENSION pids '' absolute 1 1\n"
2669                         "DIMENSION fds '' absolute 1 1\n"
2670                         "DIMENSION targets '' absolute 1 1\n"
2671                         "DIMENSION new_pids 'new pids' incremental 1 1\n"
2672                         "CHART netdata.apps_fix '' 'Apps Plugin Normalization Ratios' 'percentage' apps.plugin netdata.apps_fix line 140002 %1$d\n"
2673                         "DIMENSION utime '' absolute 1 %2$llu\n"
2674                         "DIMENSION stime '' absolute 1 %2$llu\n"
2675                         "DIMENSION gtime '' absolute 1 %2$llu\n"
2676                         "DIMENSION minflt '' absolute 1 %2$llu\n"
2677                         "DIMENSION majflt '' absolute 1 %2$llu\n"
2678                 , update_every
2679                 , RATES_DETAIL
2680         );
2681
2682         if(include_exited_childs)
2683             fprintf(stdout
2684                     , "CHART netdata.apps_children_fix '' 'Apps Plugin Exited Children Normalization Ratios' 'percentage' apps.plugin netdata.apps_children_fix line 140003 %1$d\n"
2685                             "DIMENSION cutime '' absolute 1 %2$llu\n"
2686                             "DIMENSION cstime '' absolute 1 %2$llu\n"
2687                             "DIMENSION cgtime '' absolute 1 %2$llu\n"
2688                             "DIMENSION cminflt '' absolute 1 %2$llu\n"
2689                             "DIMENSION cmajflt '' absolute 1 %2$llu\n"
2690                     , update_every
2691                     , RATES_DETAIL
2692             );
2693     }
2694
2695     fprintf(stdout,
2696         "BEGIN netdata.apps_cpu %llu\n"
2697         "SET user = %llu\n"
2698         "SET system = %llu\n"
2699         "END\n"
2700         "BEGIN netdata.apps_sizes %llu\n"
2701         "SET calls = %zu\n"
2702         "SET files = %zu\n"
2703         "SET pids = %zu\n"
2704         "SET fds = %d\n"
2705         "SET targets = %zu\n"
2706         "SET new_pids = %zu\n"
2707         "END\n"
2708         "BEGIN netdata.apps_fix %llu\n"
2709         "SET utime = %u\n"
2710         "SET stime = %u\n"
2711         "SET gtime = %u\n"
2712         "SET minflt = %u\n"
2713         "SET majflt = %u\n"
2714         "END\n"
2715         , usec
2716         , cpuuser
2717         , cpusyst
2718         , usec
2719         , calls_counter
2720         , file_counter
2721         , all_pids_count
2722         , all_files_len
2723         , apps_groups_targets_count
2724         , targets_assignment_counter
2725         , usec
2726         , (unsigned int)(utime_fix_ratio   * 100 * RATES_DETAIL)
2727         , (unsigned int)(stime_fix_ratio   * 100 * RATES_DETAIL)
2728         , (unsigned int)(gtime_fix_ratio   * 100 * RATES_DETAIL)
2729         , (unsigned int)(minflt_fix_ratio  * 100 * RATES_DETAIL)
2730         , (unsigned int)(majflt_fix_ratio  * 100 * RATES_DETAIL)
2731         );
2732
2733     if(include_exited_childs)
2734         fprintf(stdout,
2735             "BEGIN netdata.apps_children_fix %llu\n"
2736             "SET cutime = %u\n"
2737             "SET cstime = %u\n"
2738             "SET cgtime = %u\n"
2739             "SET cminflt = %u\n"
2740             "SET cmajflt = %u\n"
2741             "END\n"
2742             , usec
2743             , (unsigned int)(cutime_fix_ratio  * 100 * RATES_DETAIL)
2744             , (unsigned int)(cstime_fix_ratio  * 100 * RATES_DETAIL)
2745             , (unsigned int)(cgtime_fix_ratio  * 100 * RATES_DETAIL)
2746             , (unsigned int)(cminflt_fix_ratio * 100 * RATES_DETAIL)
2747             , (unsigned int)(cmajflt_fix_ratio * 100 * RATES_DETAIL)
2748             );
2749
2750     return usec;
2751 }
2752
2753 static void normalize_utilization(struct target *root) {
2754     struct target *w;
2755
2756     // childs processing introduces spikes
2757     // here we try to eliminate them by disabling childs processing either for specific dimensions
2758     // or entirely. Of course, either way, we disable it just a single iteration.
2759
2760     kernel_uint_t max_time = processors * hz * RATES_DETAIL;
2761     kernel_uint_t utime = 0, cutime = 0, stime = 0, cstime = 0, gtime = 0, cgtime = 0, minflt = 0, cminflt = 0, majflt = 0, cmajflt = 0;
2762
2763     if(global_utime > max_time) global_utime = max_time;
2764     if(global_stime > max_time) global_stime = max_time;
2765     if(global_gtime > max_time) global_gtime = max_time;
2766
2767     for(w = root; w ; w = w->next) {
2768         if(w->target || (!w->processes && !w->exposed)) continue;
2769
2770         utime   += w->utime;
2771         stime   += w->stime;
2772         gtime   += w->gtime;
2773         cutime  += w->cutime;
2774         cstime  += w->cstime;
2775         cgtime  += w->cgtime;
2776
2777         minflt  += w->minflt;
2778         majflt  += w->majflt;
2779         cminflt += w->cminflt;
2780         cmajflt += w->cmajflt;
2781     }
2782
2783     if((global_utime || global_stime || global_gtime) && (utime || stime || gtime)) {
2784         if(global_utime + global_stime + global_gtime > utime + cutime + stime + cstime + gtime + cgtime) {
2785             // everything we collected fits
2786             utime_fix_ratio  =
2787             stime_fix_ratio  =
2788             gtime_fix_ratio  =
2789             cutime_fix_ratio =
2790             cstime_fix_ratio =
2791             cgtime_fix_ratio = 1.0; //(double)(global_utime + global_stime) / (double)(utime + cutime + stime + cstime);
2792         }
2793         else if(global_utime + global_stime > utime + stime) {
2794             // childrens resources are too high
2795             // lower only the children resources
2796             utime_fix_ratio  =
2797             stime_fix_ratio  =
2798             gtime_fix_ratio  = 1.0;
2799             cutime_fix_ratio =
2800             cstime_fix_ratio =
2801             cgtime_fix_ratio = (double)((global_utime + global_stime) - (utime + stime)) / (double)(cutime + cstime);
2802         }
2803         else {
2804             // even running processes are unrealistic
2805             // zero the children resources
2806             // lower the running processes resources
2807             utime_fix_ratio  =
2808             stime_fix_ratio  =
2809             gtime_fix_ratio  = (double)(global_utime + global_stime) / (double)(utime + stime);
2810             cutime_fix_ratio =
2811             cstime_fix_ratio =
2812             cgtime_fix_ratio = 0.0;
2813         }
2814     }
2815     else {
2816         utime_fix_ratio  =
2817         stime_fix_ratio  =
2818         gtime_fix_ratio  =
2819         cutime_fix_ratio =
2820         cstime_fix_ratio =
2821         cgtime_fix_ratio = 0.0;
2822     }
2823
2824     if(utime_fix_ratio  > 1.0) utime_fix_ratio  = 1.0;
2825     if(cutime_fix_ratio > 1.0) cutime_fix_ratio = 1.0;
2826     if(stime_fix_ratio  > 1.0) stime_fix_ratio  = 1.0;
2827     if(cstime_fix_ratio > 1.0) cstime_fix_ratio = 1.0;
2828     if(gtime_fix_ratio  > 1.0) gtime_fix_ratio  = 1.0;
2829     if(cgtime_fix_ratio > 1.0) cgtime_fix_ratio = 1.0;
2830
2831     // if(utime_fix_ratio  < 0.0) utime_fix_ratio  = 0.0;
2832     // if(cutime_fix_ratio < 0.0) cutime_fix_ratio = 0.0;
2833     // if(stime_fix_ratio  < 0.0) stime_fix_ratio  = 0.0;
2834     // if(cstime_fix_ratio < 0.0) cstime_fix_ratio = 0.0;
2835     // if(gtime_fix_ratio  < 0.0) gtime_fix_ratio  = 0.0;
2836     // if(cgtime_fix_ratio < 0.0) cgtime_fix_ratio = 0.0;
2837
2838     // FIXME
2839     // we use cpu time to normalize page faults
2840     // the problem is that to find the proper max values
2841     // for page faults we have to parse /proc/vmstat
2842     // which is quite big to do it again (netdata does it already)
2843     //
2844     // a better solution could be to somehow have netdata
2845     // do this normalization for us
2846
2847     if(utime || stime || gtime)
2848         majflt_fix_ratio =
2849         minflt_fix_ratio = (double)(utime * utime_fix_ratio + stime * stime_fix_ratio + gtime * gtime_fix_ratio) / (double)(utime + stime + gtime);
2850     else
2851         minflt_fix_ratio =
2852         majflt_fix_ratio = 1.0;
2853
2854     if(cutime || cstime || cgtime)
2855         cmajflt_fix_ratio =
2856         cminflt_fix_ratio = (double)(cutime * cutime_fix_ratio + cstime * cstime_fix_ratio + cgtime * cgtime_fix_ratio) / (double)(cutime + cstime + cgtime);
2857     else
2858         cminflt_fix_ratio =
2859         cmajflt_fix_ratio = 1.0;
2860
2861     // the report
2862
2863     if(unlikely(debug)) {
2864         fprintf(stderr,
2865             "SYSTEM: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
2866             "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 " "
2867             "DELTA: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
2868             "FIX: u=%0.2f s=%0.2f g=%0.2f cu=%0.2f cs=%0.2f cg=%0.2f "
2869             "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 " "
2870             "\n"
2871             , global_utime
2872             , global_stime
2873             , global_gtime
2874             , utime
2875             , stime
2876             , gtime
2877             , cutime
2878             , cstime
2879             , cgtime
2880             , utime + cutime - global_utime
2881             , stime + cstime - global_stime
2882             , gtime + cgtime - global_gtime
2883             , utime_fix_ratio
2884             , stime_fix_ratio
2885             , gtime_fix_ratio
2886             , cutime_fix_ratio
2887             , cstime_fix_ratio
2888             , cgtime_fix_ratio
2889             , (kernel_uint_t)(utime * utime_fix_ratio)
2890             , (kernel_uint_t)(stime * stime_fix_ratio)
2891             , (kernel_uint_t)(gtime * gtime_fix_ratio)
2892             , (kernel_uint_t)(cutime * cutime_fix_ratio)
2893             , (kernel_uint_t)(cstime * cstime_fix_ratio)
2894             , (kernel_uint_t)(cgtime * cgtime_fix_ratio)
2895             );
2896     }
2897 }
2898
2899 static void send_collected_data_to_netdata(struct target *root, const char *type, usec_t usec) {
2900     struct target *w;
2901
2902     send_BEGIN(type, "cpu", usec);
2903     for (w = root; w ; w = w->next) {
2904         if(unlikely(w->exposed))
2905             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));
2906     }
2907     send_END();
2908
2909     send_BEGIN(type, "cpu_user", usec);
2910     for (w = root; w ; w = w->next) {
2911         if(unlikely(w->exposed))
2912             send_SET(w->name, (kernel_uint_t)(w->utime * utime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cutime * cutime_fix_ratio)):0ULL));
2913     }
2914     send_END();
2915
2916     send_BEGIN(type, "cpu_system", usec);
2917     for (w = root; w ; w = w->next) {
2918         if(unlikely(w->exposed))
2919             send_SET(w->name, (kernel_uint_t)(w->stime * stime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cstime * cstime_fix_ratio)):0ULL));
2920     }
2921     send_END();
2922
2923     if(show_guest_time) {
2924         send_BEGIN(type, "cpu_guest", usec);
2925         for (w = root; w ; w = w->next) {
2926             if(unlikely(w->exposed))
2927                 send_SET(w->name, (kernel_uint_t)(w->gtime * gtime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cgtime * cgtime_fix_ratio)):0ULL));
2928         }
2929         send_END();
2930     }
2931
2932     send_BEGIN(type, "threads", usec);
2933     for (w = root; w ; w = w->next) {
2934         if(unlikely(w->exposed))
2935             send_SET(w->name, w->num_threads);
2936     }
2937     send_END();
2938
2939     send_BEGIN(type, "processes", usec);
2940     for (w = root; w ; w = w->next) {
2941         if(unlikely(w->exposed))
2942             send_SET(w->name, w->processes);
2943     }
2944     send_END();
2945
2946     send_BEGIN(type, "mem", usec);
2947     for (w = root; w ; w = w->next) {
2948         if(unlikely(w->exposed))
2949             send_SET(w->name, (w->statm_resident > w->statm_share)?(w->statm_resident - w->statm_share):0ULL);
2950     }
2951     send_END();
2952
2953     send_BEGIN(type, "vmem", usec);
2954     for (w = root; w ; w = w->next) {
2955         if(unlikely(w->exposed))
2956             send_SET(w->name, w->statm_size);
2957     }
2958     send_END();
2959
2960     send_BEGIN(type, "minor_faults", usec);
2961     for (w = root; w ; w = w->next) {
2962         if(unlikely(w->exposed))
2963             send_SET(w->name, (kernel_uint_t)(w->minflt * minflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cminflt * cminflt_fix_ratio)):0ULL));
2964     }
2965     send_END();
2966
2967     send_BEGIN(type, "major_faults", usec);
2968     for (w = root; w ; w = w->next) {
2969         if(unlikely(w->exposed))
2970             send_SET(w->name, (kernel_uint_t)(w->majflt * majflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cmajflt * cmajflt_fix_ratio)):0ULL));
2971     }
2972     send_END();
2973
2974 #ifndef __FreeBSD__
2975     send_BEGIN(type, "lreads", usec);
2976     for (w = root; w ; w = w->next) {
2977         if(unlikely(w->exposed))
2978             send_SET(w->name, w->io_logical_bytes_read);
2979     }
2980     send_END();
2981
2982     send_BEGIN(type, "lwrites", usec);
2983     for (w = root; w ; w = w->next) {
2984         if(unlikely(w->exposed))
2985             send_SET(w->name, w->io_logical_bytes_written);
2986     }
2987     send_END();
2988 #endif
2989
2990     send_BEGIN(type, "preads", usec);
2991     for (w = root; w ; w = w->next) {
2992         if(unlikely(w->exposed))
2993             send_SET(w->name, w->io_storage_bytes_read);
2994     }
2995     send_END();
2996
2997     send_BEGIN(type, "pwrites", usec);
2998     for (w = root; w ; w = w->next) {
2999         if(unlikely(w->exposed))
3000             send_SET(w->name, w->io_storage_bytes_written);
3001     }
3002     send_END();
3003
3004     if(enable_file_charts) {
3005         send_BEGIN(type, "files", usec);
3006         for (w = root; w; w = w->next) {
3007             if (unlikely(w->exposed))
3008                 send_SET(w->name, w->openfiles);
3009         }
3010         send_END();
3011
3012         send_BEGIN(type, "sockets", usec);
3013         for (w = root; w; w = w->next) {
3014             if (unlikely(w->exposed))
3015                 send_SET(w->name, w->opensockets);
3016         }
3017         send_END();
3018
3019         send_BEGIN(type, "pipes", usec);
3020         for (w = root; w; w = w->next) {
3021             if (unlikely(w->exposed))
3022                 send_SET(w->name, w->openpipes);
3023         }
3024         send_END();
3025     }
3026 }
3027
3028
3029 // ----------------------------------------------------------------------------
3030 // generate the charts
3031
3032 static void send_charts_updates_to_netdata(struct target *root, const char *type, const char *title)
3033 {
3034     struct target *w;
3035     int newly_added = 0;
3036
3037     for(w = root ; w ; w = w->next) {
3038         if (w->target) continue;
3039
3040         if (!w->exposed && w->processes) {
3041             newly_added++;
3042             w->exposed = 1;
3043             if (debug || w->debug) fprintf(stderr, "apps.plugin: %s just added - regenerating charts.\n", w->name);
3044         }
3045     }
3046
3047     // nothing more to show
3048     if(!newly_added && show_guest_time == show_guest_time_old) return;
3049
3050     // we have something new to show
3051     // update the charts
3052     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);
3053     for (w = root; w ; w = w->next) {
3054         if(unlikely(w->exposed))
3055             fprintf(stdout, "DIMENSION %s '' absolute 1 %llu %s\n", w->name, hz * RATES_DETAIL / 100, w->hidden ? "hidden" : "");
3056     }
3057
3058     fprintf(stdout, "CHART %s.mem '' '%s Real Memory (w/o shared)' 'MB' mem %s.mem stacked 20003 %d\n", type, title, type, update_every);
3059     for (w = root; w ; w = w->next) {
3060         if(unlikely(w->exposed))
3061             fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
3062     }
3063
3064     fprintf(stdout, "CHART %s.vmem '' '%s Virtual Memory Size' 'MB' mem %s.vmem stacked 20004 %d\n", type, title, type, update_every);
3065     for (w = root; w ; w = w->next) {
3066         if(unlikely(w->exposed))
3067             fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
3068     }
3069
3070     fprintf(stdout, "CHART %s.threads '' '%s Threads' 'threads' processes %s.threads stacked 20005 %d\n", type, title, type, update_every);
3071     for (w = root; w ; w = w->next) {
3072         if(unlikely(w->exposed))
3073             fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3074     }
3075
3076     fprintf(stdout, "CHART %s.processes '' '%s Processes' 'processes' processes %s.processes stacked 20004 %d\n", type, title, type, update_every);
3077     for (w = root; w ; w = w->next) {
3078         if(unlikely(w->exposed))
3079             fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3080     }
3081
3082     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);
3083     for (w = root; w ; w = w->next) {
3084         if(unlikely(w->exposed))
3085             fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3086     }
3087
3088     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);
3089     for (w = root; w ; w = w->next) {
3090         if(unlikely(w->exposed))
3091             fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3092     }
3093
3094     if(show_guest_time) {
3095         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);
3096         for (w = root; w; w = w->next) {
3097             if(unlikely(w->exposed))
3098                 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3099         }
3100     }
3101
3102     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);
3103     for (w = root; w ; w = w->next) {
3104         if(unlikely(w->exposed))
3105             fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3106     }
3107
3108     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);
3109     for (w = root; w ; w = w->next) {
3110         if(unlikely(w->exposed))
3111             fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3112     }
3113
3114 #ifdef __FreeBSD__
3115     fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'blocks/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
3116     for (w = root; w ; w = w->next) {
3117         if(unlikely(w->exposed))
3118             fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3119     }
3120
3121     fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'blocks/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
3122     for (w = root; w ; w = w->next) {
3123         if(unlikely(w->exposed))
3124             fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3125     }
3126 #else
3127     fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'kilobytes/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
3128     for (w = root; w ; w = w->next) {
3129         if(unlikely(w->exposed))
3130             fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3131     }
3132
3133     fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'kilobytes/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
3134     for (w = root; w ; w = w->next) {
3135         if(unlikely(w->exposed))
3136             fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3137     }
3138
3139     fprintf(stdout, "CHART %s.lreads '' '%s Disk Logical Reads' 'kilobytes/s' disk %s.lreads stacked 20042 %d\n", type, title, type, update_every);
3140     for (w = root; w ; w = w->next) {
3141         if(unlikely(w->exposed))
3142             fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3143     }
3144
3145     fprintf(stdout, "CHART %s.lwrites '' '%s I/O Logical Writes' 'kilobytes/s' disk %s.lwrites stacked 20042 %d\n", type, title, type, update_every);
3146     for (w = root; w ; w = w->next) {
3147         if(unlikely(w->exposed))
3148             fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3149     }
3150 #endif
3151
3152     if(enable_file_charts) {
3153         fprintf(stdout, "CHART %s.files '' '%s Open Files' 'open files' disk %s.files stacked 20050 %d\n", type,
3154                        title, type, update_every);
3155         for (w = root; w; w = w->next) {
3156             if (unlikely(w->exposed))
3157                 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3158         }
3159
3160         fprintf(stdout, "CHART %s.sockets '' '%s Open Sockets' 'open sockets' net %s.sockets stacked 20051 %d\n",
3161                        type, title, type, update_every);
3162         for (w = root; w; w = w->next) {
3163             if (unlikely(w->exposed))
3164                 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3165         }
3166
3167         fprintf(stdout, "CHART %s.pipes '' '%s Pipes' 'open pipes' processes %s.pipes stacked 20053 %d\n", type,
3168                        title, type, update_every);
3169         for (w = root; w; w = w->next) {
3170             if (unlikely(w->exposed))
3171                 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3172         }
3173     }
3174 }
3175
3176
3177 // ----------------------------------------------------------------------------
3178 // parse command line arguments
3179
3180 int check_proc_1_io() {
3181     int ret = 0;
3182
3183     procfile *ff = procfile_open("/proc/1/io", NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
3184     if(!ff) goto cleanup;
3185
3186     ff = procfile_readall(ff);
3187     if(!ff) goto cleanup;
3188
3189     ret = 1;
3190
3191 cleanup:
3192     procfile_close(ff);
3193     return ret;
3194 }
3195
3196 static void parse_args(int argc, char **argv)
3197 {
3198     int i, freq = 0;
3199     char *name = NULL;
3200
3201     for(i = 1; i < argc; i++) {
3202         if(!freq) {
3203             int n = (int)str2l(argv[i]);
3204             if(n > 0) {
3205                 freq = n;
3206                 continue;
3207             }
3208         }
3209
3210         if(strcmp("version", argv[i]) == 0 || strcmp("-v", argv[i]) == 0 || strcmp("-V", argv[i]) == 0) {
3211             printf("apps.plugin %s\n", VERSION);
3212             exit(0);
3213         }
3214
3215         if(strcmp("test-permissions", argv[i]) == 0 || strcmp("-t", argv[i]) == 0) {
3216             if(!check_proc_1_io()) {
3217                 perror("Tried to read /proc/1/io and it failed");
3218                 exit(1);
3219             }
3220             printf("OK\n");
3221             exit(0);
3222         }
3223
3224         if(strcmp("debug", argv[i]) == 0) {
3225             debug = 1;
3226             // debug_flags = 0xffffffff;
3227             continue;
3228         }
3229
3230         if(strcmp("no-childs", argv[i]) == 0 || strcmp("without-childs", argv[i]) == 0) {
3231             include_exited_childs = 0;
3232             continue;
3233         }
3234
3235         if(strcmp("with-childs", argv[i]) == 0) {
3236             include_exited_childs = 1;
3237             continue;
3238         }
3239
3240         if(strcmp("with-guest", argv[i]) == 0) {
3241             enable_guest_charts = 1;
3242             continue;
3243         }
3244
3245         if(strcmp("no-guest", argv[i]) == 0 || strcmp("without-guest", argv[i]) == 0) {
3246             enable_guest_charts = 0;
3247             continue;
3248         }
3249
3250         if(strcmp("with-files", argv[i]) == 0) {
3251             enable_file_charts = 1;
3252             continue;
3253         }
3254
3255         if(strcmp("no-files", argv[i]) == 0 || strcmp("without-files", argv[i]) == 0) {
3256             enable_file_charts = 0;
3257             continue;
3258         }
3259
3260         if(strcmp("no-users", argv[i]) == 0 || strcmp("without-users", argv[i]) == 0) {
3261             enable_users_charts = 0;
3262             continue;
3263         }
3264
3265         if(strcmp("no-groups", argv[i]) == 0 || strcmp("without-groups", argv[i]) == 0) {
3266             enable_groups_charts = 0;
3267             continue;
3268         }
3269
3270         if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0) {
3271             fprintf(stderr,
3272                     "\n"
3273                     " netdata apps.plugin %s\n"
3274                     " Copyright (C) 2016-2017 Costa Tsaousis <costa@tsaousis.gr>\n"
3275                     " Released under GNU General Public License v3 or later.\n"
3276                     " All rights reserved.\n"
3277                     "\n"
3278                     " This program is a data collector plugin for netdata.\n"
3279                     "\n"
3280                     " Available command line options:\n"
3281                     "\n"
3282                     " SECONDS           set the data collection frequency\n"
3283                     "\n"
3284                     " debug             enable debugging (lot of output)\n"
3285                     "\n"
3286                     " with-childs\n"
3287                     " without-childs    enable / disable aggregating exited\n"
3288                     "                   children resources into parents\n"
3289                     "                   (default is enabled)\n"
3290                     "\n"
3291                     " with-guest\n"
3292                     " without-guest     enable / disable reporting guest charts\n"
3293                     "                   (default is disabled)\n"
3294                     "\n"
3295                     " with-files\n"
3296                     " without-files     enable / disable reporting files, sockets, pipes\n"
3297                     "                   (default is enabled)\n"
3298                     "\n"
3299                     " NAME              read apps_NAME.conf instead of\n"
3300                     "                   apps_groups.conf\n"
3301                     "                   (default NAME=groups)\n"
3302                     "\n"
3303                     " version or -v or -V print program version and exit\n"
3304                     "\n"
3305                     , VERSION
3306             );
3307             exit(1);
3308         }
3309
3310         if(!name) {
3311             name = argv[i];
3312             continue;
3313         }
3314
3315         error("Cannot understand option %s", argv[i]);
3316         exit(1);
3317     }
3318
3319     if(freq > 0) update_every = freq;
3320     if(!name) name = "groups";
3321
3322     if(read_apps_groups_conf(name)) {
3323         error("Cannot read process groups '%s/apps_%s.conf'. There are no internal defaults. Failing.", config_dir, name);
3324         exit(1);
3325     }
3326 }
3327
3328 static int am_i_running_as_root() {
3329     uid_t uid = getuid(), euid = geteuid();
3330
3331     if(uid == 0 || euid == 0) {
3332         if(debug) info("I am running with escalated privileges, uid = %u, euid = %u.", uid, euid);
3333         return 1;
3334     }
3335
3336     if(debug) info("I am not running with escalated privileges, uid = %u, euid = %u.", uid, euid);
3337     return 0;
3338 }
3339
3340 #ifdef HAVE_CAPABILITY
3341 static int check_capabilities() {
3342     cap_t caps = cap_get_proc();
3343     if(!caps) {
3344         error("Cannot get current capabilities.");
3345         return 0;
3346     }
3347     else if(debug)
3348         info("Received my capabilities from the system.");
3349
3350     int ret = 1;
3351
3352     cap_flag_value_t cfv = CAP_CLEAR;
3353     if(cap_get_flag(caps, CAP_DAC_READ_SEARCH, CAP_EFFECTIVE, &cfv) == -1) {
3354         error("Cannot find if CAP_DAC_READ_SEARCH is effective.");
3355         ret = 0;
3356     }
3357     else {
3358         if(cfv != CAP_SET) {
3359             error("apps.plugin should run with CAP_DAC_READ_SEARCH.");
3360             ret = 0;
3361         }
3362         else if(debug)
3363             info("apps.plugin runs with CAP_DAC_READ_SEARCH.");
3364     }
3365
3366     cfv = CAP_CLEAR;
3367     if(cap_get_flag(caps, CAP_SYS_PTRACE, CAP_EFFECTIVE, &cfv) == -1) {
3368         error("Cannot find if CAP_SYS_PTRACE is effective.");
3369         ret = 0;
3370     }
3371     else {
3372         if(cfv != CAP_SET) {
3373             error("apps.plugin should run with CAP_SYS_PTRACE.");
3374             ret = 0;
3375         }
3376         else if(debug)
3377             info("apps.plugin runs with CAP_SYS_PTRACE.");
3378     }
3379
3380     cap_free(caps);
3381
3382     return ret;
3383 }
3384 #else
3385 static int check_capabilities() {
3386     return 0;
3387 }
3388 #endif
3389
3390 int main(int argc, char **argv) {
3391     // debug_flags = D_PROCFILE;
3392
3393     // set the name for logging
3394     program_name = "apps.plugin";
3395
3396     // disable syslog for apps.plugin
3397     error_log_syslog = 0;
3398
3399     // set errors flood protection to 100 logs per hour
3400     error_log_errors_per_period = 100;
3401     error_log_throttle_period = 3600;
3402
3403     netdata_configured_host_prefix = getenv("NETDATA_HOST_PREFIX");
3404     if(netdata_configured_host_prefix == NULL) {
3405         // info("NETDATA_HOST_PREFIX is not passed from netdata");
3406         netdata_configured_host_prefix = "";
3407     }
3408     // else info("Found NETDATA_HOST_PREFIX='%s'", netdata_configured_host_prefix);
3409
3410     config_dir = getenv("NETDATA_CONFIG_DIR");
3411     if(config_dir == NULL) {
3412         // info("NETDATA_CONFIG_DIR is not passed from netdata");
3413         config_dir = CONFIG_DIR;
3414     }
3415     // else info("Found NETDATA_CONFIG_DIR='%s'", config_dir);
3416
3417 #ifdef NETDATA_INTERNAL_CHECKS
3418     if(debug_flags != 0) {
3419         struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
3420         if(setrlimit(RLIMIT_CORE, &rl) != 0)
3421             info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
3422 #ifdef HAVE_SYS_PRCTL_H
3423         prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
3424 #endif
3425     }
3426 #endif /* NETDATA_INTERNAL_CHECKS */
3427
3428     procfile_adaptive_initial_allocation = 1;
3429
3430     time_t started_t = now_monotonic_sec();
3431     get_system_HZ();
3432     get_system_pid_max();
3433     get_system_cpus();
3434
3435     parse_args(argc, argv);
3436
3437     if(!check_capabilities() && !am_i_running_as_root() && !check_proc_1_io()) {
3438         uid_t uid = getuid(), euid = geteuid();
3439 #ifdef HAVE_CAPABILITY
3440         error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
3441                       "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
3442                       "To enable capabilities run: sudo setcap cap_dac_read_search,cap_sys_ptrace+ep %s; "
3443                       "To enable setuid to root run: sudo chown root %s; sudo chmod 4755 %s; "
3444               , uid, euid, argv[0], argv[0], argv[0]
3445         );
3446 #else
3447         error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
3448                       "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
3449                       "Your system does not support capabilities. "
3450                       "To enable setuid to root run: sudo chown root %s; sudo chmod 4755 %s; "
3451               , uid, euid, argv[0], argv[0]
3452         );
3453 #endif
3454     }
3455
3456     info("started on pid %d", getpid());
3457
3458 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
3459     all_pids_sortlist = callocz(sizeof(pid_t), (size_t)pid_max);
3460 #endif
3461
3462     all_pids          = callocz(sizeof(struct pid_stat *), (size_t) pid_max);
3463
3464     usec_t step = update_every * USEC_PER_SEC;
3465     global_iterations_counter = 1;
3466     heartbeat_t hb;
3467     heartbeat_init(&hb);
3468     for(;1; global_iterations_counter++) {
3469
3470 #ifdef NETDATA_PROFILING
3471 #warning "compiling for profiling"
3472         static int profiling_count=0;
3473         profiling_count++;
3474         if(unlikely(profiling_count > 1000)) exit(0);
3475 #else
3476         heartbeat_next(&hb, step);
3477 #endif
3478
3479         if(!collect_data_for_all_processes()) {
3480             error("Cannot collect /proc data for running processes. Disabling apps.plugin...");
3481             printf("DISABLE\n");
3482             exit(1);
3483         }
3484
3485         calculate_netdata_statistics();
3486         normalize_utilization(apps_groups_root_target);
3487
3488         usec_t dt = send_resource_usage_to_netdata();
3489
3490         // this is smart enough to show only newly added apps, when needed
3491         send_charts_updates_to_netdata(apps_groups_root_target, "apps", "Apps");
3492
3493         if(likely(enable_users_charts))
3494             send_charts_updates_to_netdata(users_root_target, "users", "Users");
3495
3496         if(likely(enable_groups_charts))
3497             send_charts_updates_to_netdata(groups_root_target, "groups", "User Groups");
3498
3499         send_collected_data_to_netdata(apps_groups_root_target, "apps", dt);
3500
3501         if(likely(enable_users_charts))
3502             send_collected_data_to_netdata(users_root_target, "users", dt);
3503
3504         if(likely(enable_groups_charts))
3505             send_collected_data_to_netdata(groups_root_target, "groups", dt);
3506
3507         fflush(stdout);
3508
3509         show_guest_time_old = show_guest_time;
3510
3511         if(unlikely(debug))
3512             fprintf(stderr, "apps.plugin: done Loop No %zu\n", global_iterations_counter);
3513
3514         // restart check (14400 seconds)
3515         if(now_monotonic_sec() - started_t > 14400) exit(0);
3516     }
3517 }