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