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