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