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