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