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