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