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