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