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