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