]> arthur.barton.de Git - netdata.git/blob - src/apps_plugin.c
apps.plugin now properly tracks child resource usage into the application groups...
[netdata.git] / src / apps_plugin.c
1 // TODO
2 //
3 // 1. disable RESET_OR_OVERFLOW check in charts
4
5 #ifdef HAVE_CONFIG_H
6 #include <config.h>
7 #endif
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <time.h>
12 #include <unistd.h>
13 #include <sys/types.h>
14 #include <sys/time.h>
15 #include <sys/wait.h>
16 #include <sys/stat.h>
17
18 #include <sys/resource.h>
19 #include <sys/stat.h>
20
21 #include <errno.h>
22 #include <stdarg.h>
23 #include <locale.h>
24 #include <ctype.h>
25 #include <fcntl.h>
26
27 #include <malloc.h>
28 #include <dirent.h>
29 #include <arpa/inet.h>
30
31 #include <sys/types.h>
32 #include <pwd.h>
33 #include <grp.h>
34
35 #include "avl.h"
36
37 #include "common.h"
38 #include "log.h"
39 #include "procfile.h"
40 #include "../config.h"
41
42 #ifdef NETDATA_INTERNAL_CHECKS
43 #include <sys/prctl.h>
44 #endif
45
46 #define MAX_COMPARE_NAME 100
47 #define MAX_NAME 100
48 #define MAX_CMDLINE 1024
49
50 int processors = 1;
51 pid_t pid_max = 32768;
52 int debug = 0;
53
54 int update_every = 1;
55 unsigned long long file_counter = 0;
56 int proc_pid_cmdline_is_needed = 0;
57
58 char *host_prefix = "";
59 char *config_dir = CONFIG_DIR;
60
61
62 // ----------------------------------------------------------------------------
63
64 void netdata_cleanup_and_exit(int ret) {
65         exit(ret);
66 }
67
68
69 // ----------------------------------------------------------------------------
70 // system functions
71 // to retrieve settings of the system
72
73 long get_system_cpus(void) {
74         procfile *ff = NULL;
75
76         int processors = 0;
77
78         char filename[FILENAME_MAX + 1];
79         snprintfz(filename, FILENAME_MAX, "%s/proc/stat", host_prefix);
80
81         ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);
82         if(!ff) return 1;
83
84         ff = procfile_readall(ff);
85         if(!ff) {
86                 procfile_close(ff);
87                 return 1;
88         }
89
90         unsigned int i;
91         for(i = 0; i < procfile_lines(ff); i++) {
92                 if(!procfile_linewords(ff, i)) continue;
93
94                 if(strncmp(procfile_lineword(ff, i, 0), "cpu", 3) == 0) processors++;
95         }
96         processors--;
97         if(processors < 1) processors = 1;
98
99         procfile_close(ff);
100         return processors;
101 }
102
103 pid_t get_system_pid_max(void) {
104         procfile *ff = NULL;
105         pid_t mpid = 32768;
106
107         char filename[FILENAME_MAX + 1];
108         snprintfz(filename, FILENAME_MAX, "%s/proc/sys/kernel/pid_max", host_prefix);
109         ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);
110         if(!ff) return mpid;
111
112         ff = procfile_readall(ff);
113         if(!ff) {
114                 procfile_close(ff);
115                 return mpid;
116         }
117
118         mpid = (pid_t)atoi(procfile_lineword(ff, 0, 0));
119         if(!mpid) mpid = 32768;
120
121         procfile_close(ff);
122         return mpid;
123 }
124
125 // ----------------------------------------------------------------------------
126 // target
127 // target is the structure that process data are aggregated
128
129 struct target {
130         char compare[MAX_COMPARE_NAME + 1];
131         uint32_t comparehash;
132         size_t comparelen;
133
134         char id[MAX_NAME + 1];
135         uint32_t idhash;
136
137         char name[MAX_NAME + 1];
138
139         uid_t uid;
140         gid_t gid;
141
142         unsigned long long minflt;
143         unsigned long long cminflt;
144         unsigned long long majflt;
145         unsigned long long cmajflt;
146         unsigned long long utime;
147         unsigned long long stime;
148         unsigned long long cutime;
149         unsigned long long cstime;
150         unsigned long long num_threads;
151         unsigned long long rss;
152
153         long long fix_minflt;
154         long long fix_cminflt;
155         long long fix_majflt;
156         long long fix_cmajflt;
157         long long fix_utime;
158         long long fix_stime;
159         long long fix_cutime;
160         long long fix_cstime;
161
162         unsigned long long statm_size;
163         unsigned long long statm_resident;
164         unsigned long long statm_share;
165         unsigned long long statm_text;
166         unsigned long long statm_lib;
167         unsigned long long statm_data;
168         unsigned long long statm_dirty;
169
170         unsigned long long io_logical_bytes_read;
171         unsigned long long io_logical_bytes_written;
172         unsigned long long io_read_calls;
173         unsigned long long io_write_calls;
174         unsigned long long io_storage_bytes_read;
175         unsigned long long io_storage_bytes_written;
176         unsigned long long io_cancelled_write_bytes;
177
178         unsigned long long fix_io_logical_bytes_read;
179         unsigned long long fix_io_logical_bytes_written;
180         unsigned long long fix_io_read_calls;
181         unsigned long long fix_io_write_calls;
182         unsigned long long fix_io_storage_bytes_read;
183         unsigned long long fix_io_storage_bytes_written;
184         unsigned long long fix_io_cancelled_write_bytes;
185
186         int *fds;
187         unsigned long long openfiles;
188         unsigned long long openpipes;
189         unsigned long long opensockets;
190         unsigned long long openinotifies;
191         unsigned long long openeventfds;
192         unsigned long long opentimerfds;
193         unsigned long long opensignalfds;
194         unsigned long long openeventpolls;
195         unsigned long long openother;
196
197         unsigned long processes;        // how many processes have been merged to this
198         int exposed;                            // if set, we have sent this to netdata
199         int hidden;                                     // if set, we set the hidden flag on the dimension
200         int debug;
201         int ends_with;
202         int starts_with;            // if set, the compare string matches only the
203                                                                 // beginning of the command
204
205         struct target *target;          // the one that will be reported to netdata
206         struct target *next;
207 };
208
209
210 // ----------------------------------------------------------------------------
211 // apps_groups.conf
212 // aggregate all processes in groups, to have a limited number of dimensions
213
214 struct target *apps_groups_root_target = NULL;
215 struct target *apps_groups_default_target = NULL;
216 long apps_groups_targets = 0;
217
218 struct target *users_root_target = NULL;
219 struct target *groups_root_target = NULL;
220
221 struct target *get_users_target(uid_t uid)
222 {
223         struct target *w;
224         for(w = users_root_target ; w ; w = w->next)
225                 if(w->uid == uid) return w;
226
227         w = calloc(sizeof(struct target), 1);
228         if(unlikely(!w)) {
229                 error("Cannot allocate %lu bytes of memory", (unsigned long)sizeof(struct target));
230                 return NULL;
231         }
232
233         snprintfz(w->compare, MAX_COMPARE_NAME, "%u", uid);
234         w->comparehash = simple_hash(w->compare);
235         w->comparelen = strlen(w->compare);
236
237         snprintfz(w->id, MAX_NAME, "%u", uid);
238         w->idhash = simple_hash(w->id);
239
240         struct passwd *pw = getpwuid(uid);
241         if(!pw)
242                 snprintfz(w->name, MAX_NAME, "%u", uid);
243         else
244                 snprintfz(w->name, MAX_NAME, "%s", pw->pw_name);
245
246         netdata_fix_chart_name(w->name);
247
248         w->uid = uid;
249
250         w->next = users_root_target;
251         users_root_target = w;
252
253         if(unlikely(debug))
254                 fprintf(stderr, "apps.plugin: added uid %u ('%s') target\n", w->uid, w->name);
255
256         return w;
257 }
258
259 struct target *get_groups_target(gid_t gid)
260 {
261         struct target *w;
262         for(w = groups_root_target ; w ; w = w->next)
263                 if(w->gid == gid) return w;
264
265         w = calloc(sizeof(struct target), 1);
266         if(unlikely(!w)) {
267                 error("Cannot allocate %lu bytes of memory", (unsigned long)sizeof(struct target));
268                 return NULL;
269         }
270
271         snprintfz(w->compare, MAX_COMPARE_NAME, "%u", gid);
272         w->comparehash = simple_hash(w->compare);
273         w->comparelen = strlen(w->compare);
274
275         snprintfz(w->id, MAX_NAME, "%u", gid);
276         w->idhash = simple_hash(w->id);
277
278         struct group *gr = getgrgid(gid);
279         if(!gr)
280                 snprintfz(w->name, MAX_NAME, "%u", gid);
281         else
282                 snprintfz(w->name, MAX_NAME, "%s", gr->gr_name);
283
284         netdata_fix_chart_name(w->name);
285
286         w->gid = gid;
287
288         w->next = groups_root_target;
289         groups_root_target = w;
290
291         if(unlikely(debug))
292                 fprintf(stderr, "apps.plugin: added gid %u ('%s') target\n", w->gid, w->name);
293
294         return w;
295 }
296
297 // find or create a new target
298 // there are targets that are just aggregated to other target (the second argument)
299 struct target *get_apps_groups_target(const char *id, struct target *target)
300 {
301         int tdebug = 0, thidden = 0, ends_with = 0;
302         const char *nid = id;
303
304         while(nid[0] == '-' || nid[0] == '+' || nid[0] == '*') {
305                 if(nid[0] == '-') thidden = 1;
306                 if(nid[0] == '+') tdebug = 1;
307                 if(nid[0] == '*') ends_with = 1;
308                 nid++;
309         }
310         uint32_t hash = simple_hash(id);
311
312         struct target *w;
313         for(w = apps_groups_root_target ; w ; w = w->next) {
314                 if(w->idhash == hash && strncmp(nid, w->id, MAX_NAME) == 0)
315                         return w;
316         }
317
318         w = calloc(sizeof(struct target), 1);
319         if(unlikely(!w)) {
320                 error("Cannot allocate %lu bytes of memory", (unsigned long)sizeof(struct target));
321                 return NULL;
322         }
323
324         strncpyz(w->id, nid, MAX_NAME);
325         w->idhash = simple_hash(w->id);
326
327         strncpyz(w->name, nid, MAX_NAME);
328
329         strncpyz(w->compare, nid, MAX_COMPARE_NAME);
330         int len = strlen(w->compare);
331         if(w->compare[len - 1] == '*') {
332                 w->compare[len - 1] = '\0';
333                 w->starts_with = 1;
334         }
335         w->ends_with = ends_with;
336
337         if(w->starts_with && w->ends_with)
338                 proc_pid_cmdline_is_needed = 1;
339
340         w->comparehash = simple_hash(w->compare);
341         w->comparelen = strlen(w->compare);
342
343         w->hidden = thidden;
344         w->debug = tdebug;
345         w->target = target;
346
347         w->next = apps_groups_root_target;
348         apps_groups_root_target = w;
349
350         if(unlikely(debug))
351                 fprintf(stderr, "apps.plugin: ADDING TARGET ID '%s', process name '%s' (%s), aggregated on target '%s', options: %s %s\n"
352                         , w->id
353                                 , w->compare, (w->starts_with && w->ends_with)?"substring":((w->starts_with)?"prefix":((w->ends_with)?"suffix":"exact"))
354                                 , w->target?w->target->id:w->id
355                                 , (w->hidden)?"hidden":"-"
356                                 , (w->debug)?"debug":"-"
357                 );
358
359         return w;
360 }
361
362 // read the apps_groups.conf file
363 int read_apps_groups_conf(const char *name)
364 {
365         char filename[FILENAME_MAX + 1];
366
367         snprintfz(filename, FILENAME_MAX, "%s/apps_%s.conf", config_dir, name);
368
369         if(unlikely(debug))
370                 fprintf(stderr, "apps.plugin: process groups file: '%s'\n", filename);
371
372         // ----------------------------------------
373
374         procfile *ff = procfile_open(filename, " :\t", PROCFILE_FLAG_DEFAULT);
375         if(!ff) return 1;
376
377         procfile_set_quotes(ff, "'\"");
378
379         ff = procfile_readall(ff);
380         if(!ff) {
381                 procfile_close(ff);
382                 return 1;
383         }
384
385         unsigned long line, lines = procfile_lines(ff);
386
387         for(line = 0; line < lines ;line++) {
388                 unsigned long word, words = procfile_linewords(ff, line);
389                 struct target *w = NULL;
390
391                 char *t = procfile_lineword(ff, line, 0);
392                 if(!t || !*t) continue;
393
394                 for(word = 0; word < words ;word++) {
395                         char *s = procfile_lineword(ff, line, word);
396                         if(!s || !*s) continue;
397                         if(*s == '#') break;
398
399                         if(t == s) continue;
400
401                         struct target *n = get_apps_groups_target(s, w);
402                         if(!n) {
403                                 error("Cannot create target '%s' (line %lu, word %lu)", s, line, word);
404                                 continue;
405                         }
406
407                         if(!w) w = n;
408                 }
409
410                 if(w) {
411                         int tdebug = 0, thidden = 0;
412
413                         while(t[0] == '-' || t[0] == '+') {
414                                 if(t[0] == '-') thidden = 1;
415                                 if(t[0] == '+') tdebug = 1;
416                                 t++;
417                         }
418
419                         strncpyz(w->name, t, MAX_NAME);
420                         w->hidden = thidden;
421                         w->debug = tdebug;
422
423                         if(unlikely(debug))
424                                 fprintf(stderr, "apps.plugin: AGGREGATION TARGET NAME '%s' on ID '%s', process name '%s' (%s), aggregated on target '%s', options: %s %s\n"
425                                                 , w->name
426                                                 , w->id
427                                                 , w->compare, (w->starts_with && w->ends_with)?"substring":((w->starts_with)?"prefix":((w->ends_with)?"suffix":"exact"))
428                                                 , w->target?w->target->id:w->id
429                                                 , (w->hidden)?"hidden":"-"
430                                                 , (w->debug)?"debug":"-"
431                                 );
432                 }
433         }
434
435         procfile_close(ff);
436
437         apps_groups_default_target = get_apps_groups_target("p+!o@w#e$i^r&7*5(-i)l-o_", NULL); // match nothing
438         if(!apps_groups_default_target)
439                 error("Cannot create default target");
440         else
441                 strncpyz(apps_groups_default_target->name, "other", MAX_NAME);
442
443         return 0;
444 }
445
446
447 // ----------------------------------------------------------------------------
448 // data to store for each pid
449 // see: man proc
450
451 struct pid_stat {
452         int32_t pid;
453         char comm[MAX_COMPARE_NAME + 1];
454         char cmdline[MAX_CMDLINE + 1];
455
456         // char state;
457         int32_t ppid;
458         // int32_t pgrp;
459         // int32_t session;
460         // int32_t tty_nr;
461         // int32_t tpgid;
462         // uint64_t flags;
463         unsigned long long minflt;
464         unsigned long long cminflt;
465         unsigned long long majflt;
466         unsigned long long cmajflt;
467         unsigned long long utime;
468         unsigned long long stime;
469         unsigned long long cutime;
470         unsigned long long cstime;
471         // int64_t priority;
472         // int64_t nice;
473         int32_t num_threads;
474         // int64_t itrealvalue;
475         // unsigned long long starttime;
476         // unsigned long long vsize;
477         unsigned long long rss;
478         // unsigned long long rsslim;
479         // unsigned long long starcode;
480         // unsigned long long endcode;
481         // unsigned long long startstack;
482         // unsigned long long kstkesp;
483         // unsigned long long kstkeip;
484         // uint64_t signal;
485         // uint64_t blocked;
486         // uint64_t sigignore;
487         // uint64_t sigcatch;
488         // uint64_t wchan;
489         // uint64_t nswap;
490         // uint64_t cnswap;
491         // int32_t exit_signal;
492         // int32_t processor;
493         // uint32_t rt_priority;
494         // uint32_t policy;
495         // unsigned long long delayacct_blkio_ticks;
496         // uint64_t guest_time;
497         // int64_t cguest_time;
498
499         uid_t uid;
500         gid_t gid;
501
502         unsigned long long statm_size;
503         unsigned long long statm_resident;
504         unsigned long long statm_share;
505         unsigned long long statm_text;
506         unsigned long long statm_lib;
507         unsigned long long statm_data;
508         unsigned long long statm_dirty;
509
510         unsigned long long io_logical_bytes_read;
511         unsigned long long io_logical_bytes_written;
512         unsigned long long io_read_calls;
513         unsigned long long io_write_calls;
514         unsigned long long io_storage_bytes_read;
515         unsigned long long io_storage_bytes_written;
516         unsigned long long io_cancelled_write_bytes;
517
518         // we need the last values
519         // for all incremental counters
520         // so that when a process switches users/groups
521         // we will subtract these values from the old
522         // target
523         unsigned long long last_minflt;
524         unsigned long long last_majflt;
525         unsigned long long last_utime;
526         unsigned long long last_stime;
527
528         unsigned long long last_cminflt;
529         unsigned long long last_cmajflt;
530         unsigned long long last_cutime;
531         unsigned long long last_cstime;
532
533         unsigned long long last_fix_cminflt;
534         unsigned long long last_fix_cmajflt;
535         unsigned long long last_fix_cutime;
536         unsigned long long last_fix_cstime;
537
538         unsigned long long last_io_logical_bytes_read;
539         unsigned long long last_io_logical_bytes_written;
540         unsigned long long last_io_read_calls;
541         unsigned long long last_io_write_calls;
542         unsigned long long last_io_storage_bytes_read;
543         unsigned long long last_io_storage_bytes_written;
544         unsigned long long last_io_cancelled_write_bytes;
545
546         unsigned long long fix_cminflt;
547         unsigned long long fix_cmajflt;
548         unsigned long long fix_cutime;
549         unsigned long long fix_cstime;
550
551         int *fds;                                               // array of fds it uses
552         int fds_size;                                   // the size of the fds array
553
554         int children_count;                             // number of processes directly referencing this
555         int updated;                                    // 1 when update
556         int merged;                                             // 1 when it has been merged to its parent
557         int new_entry;
558
559         struct target *target;                  // app_groups.conf targets
560         struct target *user_target;             // uid based targets
561         struct target *group_target;    // gid based targets
562
563         struct pid_stat *parent;
564         struct pid_stat *prev;
565         struct pid_stat *next;
566
567 } *root_of_pids = NULL, **all_pids;
568
569 long all_pids_count = 0;
570
571 struct pid_stat *get_pid_entry(pid_t pid)
572 {
573         if(all_pids[pid]) {
574                 all_pids[pid]->new_entry = 0;
575                 return all_pids[pid];
576         }
577
578         all_pids[pid] = calloc(sizeof(struct pid_stat), 1);
579         if(!all_pids[pid]) {
580                 error("Cannot allocate %zu bytes of memory", (size_t)sizeof(struct pid_stat));
581                 return NULL;
582         }
583
584         all_pids[pid]->fds = calloc(sizeof(int), 100);
585         if(!all_pids[pid]->fds)
586                 error("Cannot allocate %zu bytes of memory", (size_t)(sizeof(int) * 100));
587         else all_pids[pid]->fds_size = 100;
588
589         if(root_of_pids) root_of_pids->prev = all_pids[pid];
590         all_pids[pid]->next = root_of_pids;
591         root_of_pids = all_pids[pid];
592
593         all_pids[pid]->pid = pid;
594         all_pids[pid]->new_entry = 1;
595
596         return all_pids[pid];
597 }
598
599 void del_pid_entry(pid_t pid)
600 {
601         if(!all_pids[pid]) return;
602
603         if(unlikely(debug))
604                 fprintf(stderr, "apps.plugin: process %d %s exited, deleting it.\n", pid, all_pids[pid]->comm);
605
606         if(root_of_pids == all_pids[pid]) root_of_pids = all_pids[pid]->next;
607         if(all_pids[pid]->next) all_pids[pid]->next->prev = all_pids[pid]->prev;
608         if(all_pids[pid]->prev) all_pids[pid]->prev->next = all_pids[pid]->next;
609
610         if(all_pids[pid]->fds) free(all_pids[pid]->fds);
611         free(all_pids[pid]);
612         all_pids[pid] = NULL;
613 }
614
615
616 // ----------------------------------------------------------------------------
617 // update pids from proc
618
619 int read_proc_pid_cmdline(struct pid_stat *p) {
620         char filename[FILENAME_MAX + 1];
621         snprintfz(filename, FILENAME_MAX, "%s/proc/%d/cmdline", host_prefix, p->pid);
622
623         int fd = open(filename, O_RDONLY, 0666);
624         if(unlikely(fd == -1)) return 1;
625
626         int i, bytes = read(fd, p->cmdline, MAX_CMDLINE);
627         close(fd);
628
629         if(bytes <= 0) {
630                 // copy the command to the command line
631                 strncpyz(p->cmdline, p->comm, MAX_CMDLINE);
632                 return 0;
633         }
634
635         p->cmdline[bytes] = '\0';
636         for(i = 0; i < bytes ; i++)
637                 if(!p->cmdline[i]) p->cmdline[i] = ' ';
638
639         if(unlikely(debug))
640                 fprintf(stderr, "Read file '%s' contents: %s\n", filename, p->cmdline);
641
642         return 0;
643 }
644
645 int read_proc_pid_ownership(struct pid_stat *p) {
646         char filename[FILENAME_MAX + 1];
647
648         snprintfz(filename, FILENAME_MAX, "%s/proc/%d", host_prefix, p->pid);
649
650         // ----------------------------------------
651         // read uid and gid
652
653         struct stat st;
654         if(stat(filename, &st) != 0)
655                 return 1;
656
657         p->uid = st.st_uid;
658         p->gid = st.st_gid;
659
660         return 0;
661 }
662
663 int read_proc_pid_stat(struct pid_stat *p) {
664         static procfile *ff = NULL;
665
666         char filename[FILENAME_MAX + 1];
667
668         snprintfz(filename, FILENAME_MAX, "%s/proc/%d/stat", host_prefix, p->pid);
669
670         // ----------------------------------------
671
672         int set_quotes = (!ff)?1:0;
673
674         ff = procfile_reopen(ff, filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
675         if(!ff) return 1;
676
677         // if(set_quotes) procfile_set_quotes(ff, "()");
678         if(set_quotes) procfile_set_open_close(ff, "(", ")");
679
680         ff = procfile_readall(ff);
681         if(!ff) {
682                 // procfile_close(ff);
683                 return 1;
684         }
685
686         file_counter++;
687
688         // parse the process name
689         unsigned int i = 0;
690         strncpyz(p->comm, procfile_lineword(ff, 0, 1), MAX_COMPARE_NAME);
691
692         // p->pid                       = atol(procfile_lineword(ff, 0, 0+i));
693         // comm is at 1
694         // p->state                     = *(procfile_lineword(ff, 0, 2+i));
695         p->ppid                         = (int32_t) atol(procfile_lineword(ff, 0, 3 + i));
696         // p->pgrp                      = atol(procfile_lineword(ff, 0, 4+i));
697         // p->session           = atol(procfile_lineword(ff, 0, 5+i));
698         // p->tty_nr            = atol(procfile_lineword(ff, 0, 6+i));
699         // p->tpgid                     = atol(procfile_lineword(ff, 0, 7+i));
700         // p->flags                     = strtoull(procfile_lineword(ff, 0, 8+i), NULL, 10);
701         p->minflt                       = strtoull(procfile_lineword(ff, 0, 9+i), NULL, 10);
702         p->cminflt                      = strtoull(procfile_lineword(ff, 0, 10+i), NULL, 10);
703         p->majflt                       = strtoull(procfile_lineword(ff, 0, 11+i), NULL, 10);
704         p->cmajflt                      = strtoull(procfile_lineword(ff, 0, 12+i), NULL, 10);
705         p->utime                        = strtoull(procfile_lineword(ff, 0, 13+i), NULL, 10);
706         p->stime                        = strtoull(procfile_lineword(ff, 0, 14+i), NULL, 10);
707         p->cutime                       = strtoull(procfile_lineword(ff, 0, 15+i), NULL, 10);
708         p->cstime                       = strtoull(procfile_lineword(ff, 0, 16+i), NULL, 10);
709         // p->priority          = strtoull(procfile_lineword(ff, 0, 17+i), NULL, 10);
710         // p->nice                      = strtoull(procfile_lineword(ff, 0, 18+i), NULL, 10);
711         p->num_threads          = (int32_t) atol(procfile_lineword(ff, 0, 19 + i));
712         // p->itrealvalue       = strtoull(procfile_lineword(ff, 0, 20+i), NULL, 10);
713         // p->starttime         = strtoull(procfile_lineword(ff, 0, 21+i), NULL, 10);
714         // p->vsize                     = strtoull(procfile_lineword(ff, 0, 22+i), NULL, 10);
715         p->rss                          = strtoull(procfile_lineword(ff, 0, 23+i), NULL, 10);
716         // p->rsslim            = strtoull(procfile_lineword(ff, 0, 24+i), NULL, 10);
717         // p->starcode          = strtoull(procfile_lineword(ff, 0, 25+i), NULL, 10);
718         // p->endcode           = strtoull(procfile_lineword(ff, 0, 26+i), NULL, 10);
719         // p->startstack        = strtoull(procfile_lineword(ff, 0, 27+i), NULL, 10);
720         // p->kstkesp           = strtoull(procfile_lineword(ff, 0, 28+i), NULL, 10);
721         // p->kstkeip           = strtoull(procfile_lineword(ff, 0, 29+i), NULL, 10);
722         // p->signal            = strtoull(procfile_lineword(ff, 0, 30+i), NULL, 10);
723         // p->blocked           = strtoull(procfile_lineword(ff, 0, 31+i), NULL, 10);
724         // p->sigignore         = strtoull(procfile_lineword(ff, 0, 32+i), NULL, 10);
725         // p->sigcatch          = strtoull(procfile_lineword(ff, 0, 33+i), NULL, 10);
726         // p->wchan                     = strtoull(procfile_lineword(ff, 0, 34+i), NULL, 10);
727         // p->nswap                     = strtoull(procfile_lineword(ff, 0, 35+i), NULL, 10);
728         // p->cnswap            = strtoull(procfile_lineword(ff, 0, 36+i), NULL, 10);
729         // p->exit_signal       = atol(procfile_lineword(ff, 0, 37+i));
730         // p->processor         = atol(procfile_lineword(ff, 0, 38+i));
731         // p->rt_priority       = strtoul(procfile_lineword(ff, 0, 39+i), NULL, 10);
732         // p->policy            = strtoul(procfile_lineword(ff, 0, 40+i), NULL, 10);
733         // p->delayacct_blkio_ticks             = strtoull(procfile_lineword(ff, 0, 41+i), NULL, 10);
734         // p->guest_time        = strtoull(procfile_lineword(ff, 0, 42+i), NULL, 10);
735         // p->cguest_time       = strtoull(procfile_lineword(ff, 0, 43), NULL, 10);
736
737         if(unlikely(debug || (p->target && p->target->debug)))
738                 fprintf(stderr, "apps.plugin: READ PROC/PID/STAT: %s/proc/%d/stat, process: '%s' VALUES: utime=%llu, stime=%llu, cutime=%llu, cstime=%llu, minflt=%llu, majflt=%llu, cminflt=%llu, cmajflt=%llu, threads=%d\n", host_prefix, p->pid, p->comm, p->utime, p->stime, p->cutime, p->cstime, p->minflt, p->majflt, p->cminflt, p->cmajflt, p->num_threads);
739
740         // procfile_close(ff);
741         return 0;
742 }
743
744 int read_proc_pid_statm(struct pid_stat *p) {
745         static procfile *ff = NULL;
746
747         char filename[FILENAME_MAX + 1];
748
749         snprintfz(filename, FILENAME_MAX, "%s/proc/%d/statm", host_prefix, p->pid);
750
751         ff = procfile_reopen(ff, filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
752         if(!ff) return 1;
753
754         ff = procfile_readall(ff);
755         if(!ff) {
756                 // procfile_close(ff);
757                 return 1;
758         }
759
760         file_counter++;
761
762         p->statm_size                   = strtoull(procfile_lineword(ff, 0, 0), NULL, 10);
763         p->statm_resident               = strtoull(procfile_lineword(ff, 0, 1), NULL, 10);
764         p->statm_share                  = strtoull(procfile_lineword(ff, 0, 2), NULL, 10);
765         p->statm_text                   = strtoull(procfile_lineword(ff, 0, 3), NULL, 10);
766         p->statm_lib                    = strtoull(procfile_lineword(ff, 0, 4), NULL, 10);
767         p->statm_data                   = strtoull(procfile_lineword(ff, 0, 5), NULL, 10);
768         p->statm_dirty                  = strtoull(procfile_lineword(ff, 0, 6), NULL, 10);
769
770         // procfile_close(ff);
771         return 0;
772 }
773
774 int read_proc_pid_io(struct pid_stat *p) {
775         static procfile *ff = NULL;
776
777         char filename[FILENAME_MAX + 1];
778
779         snprintfz(filename, FILENAME_MAX, "%s/proc/%d/io", host_prefix, p->pid);
780
781         ff = procfile_reopen(ff, filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
782         if(!ff) return 1;
783
784         ff = procfile_readall(ff);
785         if(!ff) {
786                 // procfile_close(ff);
787                 return 1;
788         }
789
790         file_counter++;
791
792         p->io_logical_bytes_read                = strtoull(procfile_lineword(ff, 0, 1), NULL, 10);
793         p->io_logical_bytes_written     = strtoull(procfile_lineword(ff, 1, 1), NULL, 10);
794         p->io_read_calls                                = strtoull(procfile_lineword(ff, 2, 1), NULL, 10);
795         p->io_write_calls                               = strtoull(procfile_lineword(ff, 3, 1), NULL, 10);
796         p->io_storage_bytes_read                = strtoull(procfile_lineword(ff, 4, 1), NULL, 10);
797         p->io_storage_bytes_written     = strtoull(procfile_lineword(ff, 5, 1), NULL, 10);
798         p->io_cancelled_write_bytes             = strtoull(procfile_lineword(ff, 6, 1), NULL, 10);
799
800         // procfile_close(ff);
801         return 0;
802 }
803
804
805 // ----------------------------------------------------------------------------
806 // file descriptor
807 // this is used to keep a global list of all open files of the system
808 // it is needed in order to calculate the unique files processes have open
809
810 #define FILE_DESCRIPTORS_INCREASE_STEP 100
811
812 struct file_descriptor {
813         avl avl;
814 #ifdef NETDATA_INTERNAL_CHECKS
815         uint32_t magic;
816 #endif /* NETDATA_INTERNAL_CHECKS */
817         uint32_t hash;
818         const char *name;
819         int type;
820         int count;
821         int pos;
822 } *all_files = NULL;
823
824 int all_files_len = 0;
825 int all_files_size = 0;
826
827 int file_descriptor_compare(void* a, void* b) {
828 #ifdef NETDATA_INTERNAL_CHECKS
829         if(((struct file_descriptor *)a)->magic != 0x0BADCAFE || ((struct file_descriptor *)b)->magic != 0x0BADCAFE)
830                 error("Corrupted index data detected. Please report this.");
831 #endif /* NETDATA_INTERNAL_CHECKS */
832
833         if(((struct file_descriptor *)a)->hash < ((struct file_descriptor *)b)->hash)
834                 return -1;
835
836         else if(((struct file_descriptor *)a)->hash > ((struct file_descriptor *)b)->hash)
837                 return 1;
838
839         else
840                 return strcmp(((struct file_descriptor *)a)->name, ((struct file_descriptor *)b)->name);
841 }
842
843 int file_descriptor_iterator(avl *a) { if(a) {}; return 0; }
844
845 avl_tree all_files_index = {
846                 NULL,
847                 file_descriptor_compare
848 };
849
850 static struct file_descriptor *file_descriptor_find(const char *name, uint32_t hash) {
851         struct file_descriptor tmp;
852         tmp.hash = (hash)?hash:simple_hash(name);
853         tmp.name = name;
854         tmp.count = 0;
855         tmp.pos = 0;
856 #ifdef NETDATA_INTERNAL_CHECKS
857         tmp.magic = 0x0BADCAFE;
858 #endif /* NETDATA_INTERNAL_CHECKS */
859
860         return (struct file_descriptor *)avl_search(&all_files_index, (avl *) &tmp);
861 }
862
863 #define file_descriptor_add(fd) avl_insert(&all_files_index, (avl *)(fd))
864 #define file_descriptor_remove(fd) avl_remove(&all_files_index, (avl *)(fd))
865
866 #define FILETYPE_OTHER 0
867 #define FILETYPE_FILE 1
868 #define FILETYPE_PIPE 2
869 #define FILETYPE_SOCKET 3
870 #define FILETYPE_INOTIFY 4
871 #define FILETYPE_EVENTFD 5
872 #define FILETYPE_EVENTPOLL 6
873 #define FILETYPE_TIMERFD 7
874 #define FILETYPE_SIGNALFD 8
875
876 void file_descriptor_not_used(int id)
877 {
878         if(id > 0 && id < all_files_size) {
879
880 #ifdef NETDATA_INTERNAL_CHECKS
881                 if(all_files[id].magic != 0x0BADCAFE) {
882                         error("Ignoring request to remove empty file id %d.", id);
883                         return;
884                 }
885 #endif /* NETDATA_INTERNAL_CHECKS */
886
887                 if(unlikely(debug))
888                         fprintf(stderr, "apps.plugin: decreasing slot %d (count = %d).\n", id, all_files[id].count);
889
890                 if(all_files[id].count > 0) {
891                         all_files[id].count--;
892
893                         if(!all_files[id].count) {
894                                 if(unlikely(debug))
895                                         fprintf(stderr, "apps.plugin:   >> slot %d is empty.\n", id);
896
897                                 file_descriptor_remove(&all_files[id]);
898 #ifdef NETDATA_INTERNAL_CHECKS
899                                 all_files[id].magic = 0x00000000;
900 #endif /* NETDATA_INTERNAL_CHECKS */
901                                 all_files_len--;
902                         }
903                 }
904                 else
905                         error("Request to decrease counter of fd %d (%s), while the use counter is 0", id, all_files[id].name);
906         }
907         else    error("Request to decrease counter of fd %d, which is outside the array size (1 to %d)", id, all_files_size);
908 }
909
910 int file_descriptor_find_or_add(const char *name)
911 {
912         static int last_pos = 0;
913         uint32_t hash = simple_hash(name);
914
915         if(unlikely(debug))
916                 fprintf(stderr, "apps.plugin: adding or finding name '%s' with hash %u\n", name, hash);
917
918         struct file_descriptor *fd = file_descriptor_find(name, hash);
919         if(fd) {
920                 // found
921                 if(unlikely(debug))
922                         fprintf(stderr, "apps.plugin:   >> found on slot %d\n", fd->pos);
923
924                 fd->count++;
925                 return fd->pos;
926         }
927         // not found
928
929         // check we have enough memory to add it
930         if(!all_files || all_files_len == all_files_size) {
931                 void *old = all_files;
932                 int i;
933
934                 // there is no empty slot
935                 if(unlikely(debug))
936                         fprintf(stderr, "apps.plugin: extending fd array to %d entries\n", all_files_size + FILE_DESCRIPTORS_INCREASE_STEP);
937
938                 all_files = realloc(all_files, (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP) * sizeof(struct file_descriptor));
939
940                 // if the address changed, we have to rebuild the index
941                 // since all pointers are now invalid
942                 if(old && old != (void *)all_files) {
943                         if(unlikely(debug))
944                                 fprintf(stderr, "apps.plugin:   >> re-indexing.\n");
945
946                         all_files_index.root = NULL;
947                         for(i = 0; i < all_files_size; i++) {
948                                 if(!all_files[i].count) continue;
949                                 file_descriptor_add(&all_files[i]);
950                         }
951
952                         if(unlikely(debug))
953                                 fprintf(stderr, "apps.plugin:   >> re-indexing done.\n");
954                 }
955
956                 for(i = all_files_size; i < (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP); i++) {
957                         all_files[i].count = 0;
958                         all_files[i].name = NULL;
959 #ifdef NETDATA_INTERNAL_CHECKS
960                         all_files[i].magic = 0x00000000;
961 #endif /* NETDATA_INTERNAL_CHECKS */
962                         all_files[i].pos = i;
963                 }
964
965                 if(!all_files_size) all_files_len = 1;
966                 all_files_size += FILE_DESCRIPTORS_INCREASE_STEP;
967         }
968
969         if(unlikely(debug))
970                 fprintf(stderr, "apps.plugin:   >> searching for empty slot.\n");
971
972         // search for an empty slot
973         int i, c;
974         for(i = 0, c = last_pos ; i < all_files_size ; i++, c++) {
975                 if(c >= all_files_size) c = 0;
976                 if(c == 0) continue;
977
978                 if(!all_files[c].count) {
979                         if(unlikely(debug))
980                                 fprintf(stderr, "apps.plugin:   >> Examining slot %d.\n", c);
981
982 #ifdef NETDATA_INTERNAL_CHECKS
983                         if(all_files[c].magic == 0x0BADCAFE && all_files[c].name && file_descriptor_find(all_files[c].name, all_files[c].hash))
984                                 error("fd on position %d is not cleared properly. It still has %s in it.\n", c, all_files[c].name);
985 #endif /* NETDATA_INTERNAL_CHECKS */
986
987                         if(unlikely(debug))
988                                 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);
989
990                         if(all_files[c].name) free((void *)all_files[c].name);
991                         all_files[c].name = NULL;
992                         last_pos = c;
993                         break;
994                 }
995         }
996         if(i == all_files_size) {
997                 fatal("We should find an empty slot, but there isn't any");
998                 exit(1);
999         }
1000
1001         if(unlikely(debug))
1002                 fprintf(stderr, "apps.plugin:   >> updating slot %d.\n", c);
1003
1004         all_files_len++;
1005
1006         // else we have an empty slot in 'c'
1007
1008         int type;
1009         if(name[0] == '/') type = FILETYPE_FILE;
1010         else if(strncmp(name, "pipe:", 5) == 0) type = FILETYPE_PIPE;
1011         else if(strncmp(name, "socket:", 7) == 0) type = FILETYPE_SOCKET;
1012         else if(strcmp(name, "anon_inode:inotify") == 0 || strcmp(name, "inotify") == 0) type = FILETYPE_INOTIFY;
1013         else if(strcmp(name, "anon_inode:[eventfd]") == 0) type = FILETYPE_EVENTFD;
1014         else if(strcmp(name, "anon_inode:[eventpoll]") == 0) type = FILETYPE_EVENTPOLL;
1015         else if(strcmp(name, "anon_inode:[timerfd]") == 0) type = FILETYPE_TIMERFD;
1016         else if(strcmp(name, "anon_inode:[signalfd]") == 0) type = FILETYPE_SIGNALFD;
1017         else if(strncmp(name, "anon_inode:", 11) == 0) {
1018                 if(unlikely(debug))
1019                         fprintf(stderr, "apps.plugin: FIXME: unknown anonymous inode: %s\n", name);
1020
1021                 type = FILETYPE_OTHER;
1022         }
1023         else {
1024                 if(unlikely(debug))
1025                         fprintf(stderr, "apps.plugin: FIXME: cannot understand linkname: %s\n", name);
1026
1027                 type = FILETYPE_OTHER;
1028         }
1029
1030         all_files[c].name = strdup(name);
1031         all_files[c].hash = hash;
1032         all_files[c].type = type;
1033         all_files[c].pos  = c;
1034         all_files[c].count = 1;
1035 #ifdef NETDATA_INTERNAL_CHECKS
1036         all_files[c].magic = 0x0BADCAFE;
1037 #endif /* NETDATA_INTERNAL_CHECKS */
1038         file_descriptor_add(&all_files[c]);
1039
1040         if(unlikely(debug))
1041                 fprintf(stderr, "apps.plugin: using fd position %d (name: %s)\n", c, all_files[c].name);
1042
1043         return c;
1044 }
1045
1046 int read_pid_file_descriptors(struct pid_stat *p) {
1047         char dirname[FILENAME_MAX+1];
1048
1049         snprintfz(dirname, FILENAME_MAX, "%s/proc/%d/fd", host_prefix, p->pid);
1050         DIR *fds = opendir(dirname);
1051         if(fds) {
1052                 int c;
1053                 struct dirent *de;
1054                 char fdname[FILENAME_MAX + 1];
1055                 char linkname[FILENAME_MAX + 1];
1056
1057                 // make the array negative
1058                 for(c = 0 ; c < p->fds_size ; c++)
1059                         p->fds[c] = -p->fds[c];
1060
1061                 while((de = readdir(fds))) {
1062                         if(strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
1063                                 continue;
1064
1065                         // check if the fds array is small
1066                         int fdid = atoi(de->d_name);
1067                         if(fdid < 0) continue;
1068                         if(fdid >= p->fds_size) {
1069                                 // it is small, extend it
1070                                 if(unlikely(debug))
1071                                         fprintf(stderr, "apps.plugin: extending fd memory slots for %s from %d to %d\n", p->comm, p->fds_size, fdid + 100);
1072
1073                                 p->fds = realloc(p->fds, (fdid + 100) * sizeof(int));
1074                                 if(!p->fds) {
1075                                         fatal("Cannot re-allocate fds for %s", p->comm);
1076                                         break;
1077                                 }
1078
1079                                 // and initialize it
1080                                 for(c = p->fds_size ; c < (fdid + 100) ; c++) p->fds[c] = 0;
1081                                 p->fds_size = fdid + 100;
1082                         }
1083
1084                         if(p->fds[fdid] == 0) {
1085                                 // we don't know this fd, get it
1086
1087                                 sprintf(fdname, "%s/proc/%d/fd/%s", host_prefix, p->pid, de->d_name);
1088                                 ssize_t l = readlink(fdname, linkname, FILENAME_MAX);
1089                                 if(l == -1) {
1090                                         if(debug || (p->target && p->target->debug)) {
1091                                                 if(debug || (p->target && p->target->debug))
1092                                                         error("Cannot read link %s", fdname);
1093                                         }
1094                                         continue;
1095                                 }
1096                                 linkname[l] = '\0';
1097                                 file_counter++;
1098
1099                                 // if another process already has this, we will get
1100                                 // the same id
1101                                 p->fds[fdid] = file_descriptor_find_or_add(linkname);
1102                         }
1103
1104                         // else make it positive again, we need it
1105                         // of course, the actual file may have changed, but we don't care so much
1106                         // FIXME: we could compare the inode as returned by readdir direct structure
1107                         else p->fds[fdid] = -p->fds[fdid];
1108                 }
1109                 closedir(fds);
1110
1111                 // remove all the negative file descriptors
1112                 for(c = 0 ; c < p->fds_size ; c++) if(p->fds[c] < 0) {
1113                         file_descriptor_not_used(-p->fds[c]);
1114                         p->fds[c] = 0;
1115                 }
1116         }
1117         else return 1;
1118
1119         return 0;
1120 }
1121
1122 // ----------------------------------------------------------------------------
1123
1124 // 1. read all files in /proc
1125 // 2. for each numeric directory:
1126 //    i.   read /proc/pid/stat
1127 //    ii.  read /proc/pid/statm
1128 //    iii. read /proc/pid/io (requires root access)
1129 //    iii. read the entries in directory /proc/pid/fd (requires root access)
1130 //         for each entry:
1131 //         a. find or create a struct file_descriptor
1132 //         b. cleanup any old/unused file_descriptors
1133
1134 // after all these, some pids may be linked to targets, while others may not
1135
1136 // in case of errors, only 1 every 1000 errors is printed
1137 // to avoid filling up all disk space
1138 // if debug is enabled, all errors are printed
1139
1140 int collect_data_for_all_processes_from_proc(void)
1141 {
1142         char dirname[FILENAME_MAX + 1];
1143
1144         snprintfz(dirname, FILENAME_MAX, "%s/proc", host_prefix);
1145         DIR *dir = opendir(dirname);
1146         if(!dir) return 0;
1147
1148         struct dirent *file = NULL;
1149         struct pid_stat *p = NULL;
1150
1151         // mark them all as un-updated
1152         all_pids_count = 0;
1153         for(p = root_of_pids; p ; p = p->next) {
1154                 all_pids_count++;
1155                 p->parent = NULL;
1156                 p->updated = 0;
1157                 p->children_count = 0;
1158                 p->merged = 0;
1159                 p->new_entry = 0;
1160
1161         p->last_minflt = p->minflt;
1162         p->last_majflt = p->majflt;
1163         p->last_utime  = p->utime;
1164         p->last_stime  = p->stime;
1165
1166         p->last_cminflt = p->cminflt;
1167         p->last_cmajflt = p->cmajflt;
1168         p->last_cutime  = p->cutime;
1169         p->last_cstime  = p->cstime;
1170
1171         p->last_fix_cminflt = p->fix_cminflt;
1172         p->last_fix_cmajflt = p->fix_cmajflt;
1173         p->last_fix_cutime  = p->fix_cutime;
1174         p->last_fix_cstime  = p->fix_cstime;
1175
1176         p->last_io_logical_bytes_read  = p->io_logical_bytes_read;
1177         p->last_io_logical_bytes_written  = p->io_logical_bytes_written;
1178         p->last_io_read_calls  = p->io_read_calls;
1179         p->last_io_write_calls  = p->io_write_calls;
1180         p->last_io_storage_bytes_read  = p->io_storage_bytes_read;
1181         p->last_io_storage_bytes_written  = p->io_storage_bytes_written;
1182         p->last_io_cancelled_write_bytes  = p->io_cancelled_write_bytes;
1183         }
1184
1185         while((file = readdir(dir))) {
1186                 char *endptr = file->d_name;
1187                 pid_t pid = (pid_t) strtoul(file->d_name, &endptr, 10);
1188
1189                 // make sure we read a valid number
1190                 if(unlikely(endptr == file->d_name || *endptr != '\0'))
1191                         continue;
1192
1193                 if(unlikely(pid <= 0 || pid > pid_max)) {
1194                         error("Invalid pid %d read (expected 1 to %d). Ignoring process.", pid, pid_max);
1195                         continue;
1196                 }
1197
1198                 p = get_pid_entry(pid);
1199                 if(unlikely(!p)) continue;
1200
1201
1202                 // --------------------------------------------------------------------
1203                 // /proc/<pid>/stat
1204
1205                 if(unlikely(read_proc_pid_stat(p))) {
1206                         error("Cannot process %s/proc/%d/stat", host_prefix, pid);
1207                         // there is no reason to proceed if we cannot get its status
1208                         continue;
1209                 }
1210
1211                 // check its parent pid
1212                 if(unlikely(p->ppid < 0 || p->ppid > pid_max)) {
1213                         error("Pid %d states invalid parent pid %d. Using 0.", pid, p->ppid);
1214                         p->ppid = 0;
1215                 }
1216
1217                 // --------------------------------------------------------------------
1218                 // /proc/<pid>/cmdline
1219
1220                 if(proc_pid_cmdline_is_needed) {
1221                         if(unlikely(read_proc_pid_cmdline(p))) {
1222                                         error("Cannot process %s/proc/%d/cmdline", host_prefix, pid);
1223                         }
1224                 }
1225
1226                 // --------------------------------------------------------------------
1227                 // /proc/<pid>/statm
1228
1229                 if(unlikely(read_proc_pid_statm(p))) {
1230                                 error("Cannot process %s/proc/%d/statm", host_prefix, pid);
1231
1232                         // there is no reason to proceed if we cannot get its memory status
1233                         continue;
1234                 }
1235
1236
1237                 // --------------------------------------------------------------------
1238                 // /proc/<pid>/io
1239
1240                 if(unlikely(read_proc_pid_io(p))) {
1241                                 error("Cannot process %s/proc/%d/io", host_prefix, pid);
1242
1243                         // on systems without /proc/X/io
1244                         // allow proceeding without I/O information
1245                         // continue;
1246                 }
1247
1248                 // --------------------------------------------------------------------
1249                 // <pid> ownership
1250
1251                 if(unlikely(read_proc_pid_ownership(p))) {
1252                                 error("Cannot stat %s/proc/%d", host_prefix, pid);
1253                 }
1254
1255                 // --------------------------------------------------------------------
1256                 // link it
1257
1258                 // check if it is target
1259                 // we do this only once, the first time this pid is loaded
1260                 if(unlikely(p->new_entry)) {
1261                         if(unlikely(debug))
1262                                 fprintf(stderr, "apps.plugin: \tJust added %s\n", p->comm);
1263
1264                         uint32_t hash = simple_hash(p->comm);
1265                         size_t pclen = strlen(p->comm);
1266
1267                         struct target *w;
1268                         for(w = apps_groups_root_target; w ; w = w->next) {
1269                                 // if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \t\tcomparing '%s' with '%s'\n", w->compare, p->comm);
1270
1271                                 // find it - 4 cases:
1272                                 // 1. the target is not a pattern
1273                                 // 2. the target has the prefix
1274                                 // 3. the target has the suffix
1275                                 // 4. the target is something inside cmdline
1276                                 if(     (!w->starts_with && !w->ends_with && w->comparehash == hash && !strcmp(w->compare, p->comm))
1277                                        || (w->starts_with && !w->ends_with && !strncmp(w->compare, p->comm, w->comparelen))
1278                                        || (!w->starts_with && w->ends_with && pclen >= w->comparelen && !strcmp(w->compare, &p->comm[pclen - w->comparelen]))
1279                                        || (proc_pid_cmdline_is_needed && w->starts_with && w->ends_with && strstr(p->cmdline, w->compare))
1280                                                 ) {
1281                                         if(w->target) p->target = w->target;
1282                                         else p->target = w;
1283
1284                                         if(debug || (p->target && p->target->debug))
1285                                                 fprintf(stderr, "apps.plugin: \t\t%s linked to target %s\n", p->comm, p->target->name);
1286                                 }
1287                         }
1288                 }
1289
1290                 // --------------------------------------------------------------------
1291                 // /proc/<pid>/fd
1292
1293                 if(unlikely(read_pid_file_descriptors(p))) {
1294                                 error("Cannot process entries in %s/proc/%d/fd", host_prefix, pid);
1295                 }
1296
1297                 // --------------------------------------------------------------------
1298                 // done!
1299
1300                 // mark it as updated
1301                 p->updated = 1;
1302         }
1303
1304         closedir(dir);
1305
1306         return 1;
1307 }
1308
1309 // ----------------------------------------------------------------------------
1310 // update statistics on the targets
1311
1312 // 1. link all childs to their parents
1313 // 2. go from bottom to top, marking as merged all childs to their parents
1314 //    this step links all parents without a target to the child target, if any
1315 // 3. link all top level processes (the ones not merged) to the default target
1316 // 4. go from top to bottom, linking all childs without a target, to their parent target
1317 //    after this step, all processes have a target
1318 // [5. for each killed pid (updated = 0), remove its usage from its target]
1319 // 6. zero all apps_groups_targets
1320 // 7. concentrate all values on the apps_groups_targets
1321 // 8. remove all killed processes
1322 // 9. find the unique file count for each target
1323 // check: update_apps_groups_statistics()
1324
1325 void link_all_processes_to_their_parents(void) {
1326         struct pid_stat *p = NULL;
1327
1328         // link all children to their parents
1329         // and update children count on parents
1330         for(p = root_of_pids; p ; p = p->next) {
1331                 // for each process found running
1332
1333                 if(likely(p->new_entry && p->updated)) {
1334                         // the first time we see an entry
1335                         // we remove the exited children figures
1336                         // to avoid spikes
1337                         p->fix_cminflt += p->cminflt;
1338                         p->fix_cmajflt += p->cmajflt;
1339                         p->fix_cutime  += p->cutime;
1340                         p->fix_cstime  += p->cstime;
1341                 }
1342
1343                 if(likely(p->ppid > 0 && all_pids[p->ppid])) {
1344                         struct pid_stat *pp;
1345                         // for valid processes
1346
1347                         p->parent = pp = all_pids[p->ppid];
1348                         p->parent->children_count++;
1349
1350                         if(unlikely(debug || (p->target && p->target->debug)))
1351                                 fprintf(stderr, "apps.plugin: \tchild %d (%s, %s) has parent %d (%s, %s). Parent: utime=%llu, stime=%llu, minflt=%llu, majflt=%llu, cutime=%llu, cstime=%llu, cminflt=%llu, cmajflt=%llu, fix_cutime=%llu, fix_cstime=%llu, fix_cminflt=%llu, fix_cmajflt=%llu\n", p->pid, p->comm, p->updated?"running":"exited", pp->pid, pp->comm, pp->updated?"running":"exited", pp->utime, pp->stime, pp->minflt, pp->majflt, pp->cutime, pp->cstime, pp->cminflt, pp->cmajflt, pp->fix_cutime, pp->fix_cstime, pp->fix_cminflt, pp->fix_cmajflt);
1352
1353                         if(unlikely(!p->updated)) {
1354                                 // this process has exit
1355
1356                                 // find the first parent that has been updated
1357                                 while(pp && !pp->updated) {
1358                                         // we may have to forward link it to its parent
1359                                         if(unlikely(!pp->parent && pp->ppid > 0 && all_pids[pp->ppid]))
1360                                                 pp->parent = all_pids[pp->ppid];
1361
1362                                         // check again for parent
1363                                         pp = pp->parent;
1364                                 }
1365
1366                                 if(likely(pp)) {
1367                                         // this is an exited child with a parent
1368                                         // remove the known time from the parent's data
1369                                         pp->fix_cminflt += p->minflt + p->cminflt + p->fix_cminflt;
1370                                         pp->fix_cmajflt += p->majflt + p->cmajflt + p->fix_cmajflt;
1371                                         pp->fix_cutime  += p->utime  + p->cutime  + p->fix_cutime;
1372                                         pp->fix_cstime  += p->stime  + p->cstime  + p->fix_cstime;
1373
1374                                         if(unlikely(debug))
1375                                                 fprintf(stderr, "apps.plugin: \tupdating child metrics of %d (%s, %s) to its parent %d (%s, %s). Parent has now: utime=%llu, stime=%llu, minflt=%llu, majflt=%llu, cutime=%llu, cstime=%llu, cminflt=%llu, cmajflt=%llu, fix_cutime=%llu, fix_cstime=%llu, fix_cminflt=%llu, fix_cmajflt=%llu\n", p->pid, p->comm, p->updated?"running":"exited", pp->pid, pp->comm, pp->updated?"running":"exited", pp->utime, pp->stime, pp->minflt, pp->majflt, pp->cutime, pp->cstime, pp->cminflt, pp->cmajflt, pp->fix_cutime, pp->fix_cstime, pp->fix_cminflt, pp->fix_cmajflt);
1376                                 }
1377                         }
1378                 }
1379                 else if(unlikely(p->ppid != 0))
1380                         error("pid %d %s states parent %d, but the later does not exist.", p->pid, p->comm, p->ppid);
1381         }
1382 }
1383
1384
1385 void cleanup_non_existing_pids(void) {
1386         int c;
1387         struct pid_stat *p = NULL;
1388
1389         for(p = root_of_pids; p ;) {
1390                 if(!p->updated) {
1391 //                      fprintf(stderr, "\tEXITED %d %s [parent %d %s, target %s] utime=%llu, stime=%llu, cutime=%llu, cstime=%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->cutime, p->cstime, p->minflt, p->majflt, p->cminflt, p->cmajflt);
1392
1393                         for(c = 0 ; c < p->fds_size ; c++) if(p->fds[c] > 0) {
1394                                 file_descriptor_not_used(p->fds[c]);
1395                                 p->fds[c] = 0;
1396                         }
1397
1398                         pid_t r = p->pid;
1399                         p = p->next;
1400                         del_pid_entry(r);
1401                 }
1402                 else p = p->next;
1403         }
1404 }
1405
1406 void apply_apps_groups_targets_inheritance(void) {
1407         struct pid_stat *p = NULL;
1408
1409         // children that do not have a target
1410         // inherit their target from their parent
1411         int found = 1, loops = 0;
1412         while(found) {
1413                 if(unlikely(debug)) loops++;
1414                 found = 0;
1415                 for(p = root_of_pids; p ; p = p->next) {
1416                         // if this process does not have a target
1417                         // and it has a parent
1418                         // and its parent has a target
1419                         // then, set the parent's target to this process
1420                         if(unlikely(!p->target && p->parent && p->parent->target)) {
1421                                 p->target = p->parent->target;
1422                                 found++;
1423
1424                                 if(debug || (p->target && p->target->debug))
1425                                         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);
1426                         }
1427                 }
1428         }
1429
1430
1431         // find all the procs with 0 childs and merge them to their parents
1432         // repeat, until nothing more can be done.
1433         found = 1;
1434         while(found) {
1435                 if(unlikely(debug)) loops++;
1436                 found = 0;
1437                 for(p = root_of_pids; p ; p = p->next) {
1438                         // if this process does not have any children
1439                         // and is not already merged
1440                         // and has a parent
1441                         // and its parent has children
1442                         // and the target of this process and its parent is the same, or the parent does not have a target
1443                         // and its parent is not init
1444                         // then, mark them as merged.
1445                         if(unlikely(
1446                                         !p->children_count
1447                                         && !p->merged
1448                                         && p->parent
1449                                         && p->parent->children_count
1450                                         && (p->target == p->parent->target || !p->parent->target)
1451                                         && p->ppid != 1
1452                                 )) {
1453                                 p->parent->children_count--;
1454                                 p->merged = 1;
1455
1456                                 // the parent inherits the child's target, if it does not have a target itself
1457                                 if(unlikely(p->target && !p->parent->target)) {
1458                                         p->parent->target = p->target;
1459
1460                                         if(debug || (p->target && p->target->debug))
1461                                                 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);
1462                                 }
1463
1464                                 found++;
1465                         }
1466                 }
1467
1468                 if(unlikely(debug))
1469                         fprintf(stderr, "apps.plugin: merged %d processes\n", found);
1470         }
1471
1472         // init goes always to default target
1473         if(all_pids[1])
1474                 all_pids[1]->target = apps_groups_default_target;
1475
1476         // give a default target on all top level processes
1477         if(unlikely(debug)) loops++;
1478         for(p = root_of_pids; p ; p = p->next) {
1479                 // if the process is not merged itself
1480                 // then is is a top level process
1481                 if(!p->merged && !p->target)
1482                         p->target = apps_groups_default_target;
1483         }
1484
1485         // give a target to all merged child processes
1486         found = 1;
1487         while(found) {
1488                 if(unlikely(debug)) loops++;
1489                 found = 0;
1490                 for(p = root_of_pids; p ; p = p->next) {
1491                         if(unlikely(!p->target && p->merged && p->parent && p->parent->target)) {
1492                                 p->target = p->parent->target;
1493                                 found++;
1494
1495                                 if(debug || (p->target && p->target->debug))
1496                                         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);
1497                         }
1498                 }
1499         }
1500
1501         if(unlikely(debug))
1502                 fprintf(stderr, "apps.plugin: apply_apps_groups_targets_inheritance() made %d loops on the process tree\n", loops);
1503 }
1504
1505 long zero_all_targets(struct target *root) {
1506         struct target *w;
1507         long count = 0;
1508
1509         for (w = root; w ; w = w->next) {
1510                 count++;
1511
1512                 if(w->fds) free(w->fds);
1513                 w->fds = NULL;
1514
1515                 w->minflt = 0;
1516                 w->majflt = 0;
1517                 w->utime = 0;
1518                 w->stime = 0;
1519                 w->cminflt = 0;
1520                 w->cmajflt = 0;
1521                 w->cutime = 0;
1522                 w->cstime = 0;
1523                 w->num_threads = 0;
1524                 w->rss = 0;
1525                 w->processes = 0;
1526
1527                 w->statm_size = 0;
1528                 w->statm_resident = 0;
1529                 w->statm_share = 0;
1530                 w->statm_text = 0;
1531                 w->statm_lib = 0;
1532                 w->statm_data = 0;
1533                 w->statm_dirty = 0;
1534
1535                 w->io_logical_bytes_read = 0;
1536                 w->io_logical_bytes_written = 0;
1537                 w->io_read_calls = 0;
1538                 w->io_write_calls = 0;
1539                 w->io_storage_bytes_read = 0;
1540                 w->io_storage_bytes_written = 0;
1541                 w->io_cancelled_write_bytes = 0;
1542         }
1543
1544         return count;
1545 }
1546
1547 void aggregate_pid_on_target(struct target *w, struct pid_stat *p, struct target *o) {
1548         if(unlikely(!w->fds)) {
1549                 w->fds = calloc(sizeof(int), (size_t) all_files_size);
1550                 if(unlikely(!w->fds))
1551                         error("Cannot allocate memory for fds in %s", w->name);
1552         }
1553
1554         if(likely(p->updated)) {
1555                 if(unlikely(debug && (p->fix_cutime || p->fix_cstime || p->fix_cminflt || p->fix_cmajflt)))
1556                         fprintf(stderr, "apps.plugin: \tadding child counters of %d (%s) to target %s. Currents: cutime=%llu, cstime=%llu, cminflt=%llu, cmajflt=%llu, Fixes: cutime=%llu, cstime=%llu, cminflt=%llu, cmajflt=%llu\n", p->pid, p->comm, w->name, p->cutime, p->cstime, p->cminflt, p->cmajflt, p->fix_cutime, p->fix_cstime, p->fix_cminflt, p->fix_cmajflt);
1557
1558                 w->cutime  += p->cutime  - p->fix_cutime;
1559                 w->cstime  += p->cstime  - p->fix_cstime;
1560                 w->cminflt += p->cminflt - p->fix_cminflt;
1561                 w->cmajflt += p->cmajflt - p->fix_cmajflt;
1562
1563                 w->utime += p->utime; //+ (p->pid != 1)?(p->cutime - p->fix_cutime):0;
1564                 w->stime += p->stime; //+ (p->pid != 1)?(p->cstime - p->fix_cstime):0;
1565                 w->minflt += p->minflt; //+ (p->pid != 1)?(p->cminflt - p->fix_cminflt):0;
1566                 w->majflt += p->majflt; //+ (p->pid != 1)?(p->cmajflt - p->fix_cmajflt):0;
1567
1568                 //if(p->num_threads < 0)
1569                 //      error("Negative threads number for pid '%s' (%d): %d", p->comm, p->pid, p->num_threads);
1570
1571                 //if(p->num_threads > 10000)
1572                 //      error("Excessive threads number for pid '%s' (%d): %d", p->comm, p->pid, p->num_threads);
1573
1574                 w->num_threads += p->num_threads;
1575                 w->rss += p->rss;
1576
1577                 w->statm_size += p->statm_size;
1578                 w->statm_resident += p->statm_resident;
1579                 w->statm_share += p->statm_share;
1580                 w->statm_text += p->statm_text;
1581                 w->statm_lib += p->statm_lib;
1582                 w->statm_data += p->statm_data;
1583                 w->statm_dirty += p->statm_dirty;
1584
1585                 w->io_logical_bytes_read += p->io_logical_bytes_read;
1586                 w->io_logical_bytes_written += p->io_logical_bytes_written;
1587                 w->io_read_calls += p->io_read_calls;
1588                 w->io_write_calls += p->io_write_calls;
1589                 w->io_storage_bytes_read += p->io_storage_bytes_read;
1590                 w->io_storage_bytes_written += p->io_storage_bytes_written;
1591                 w->io_cancelled_write_bytes += p->io_cancelled_write_bytes;
1592
1593                 w->processes++;
1594
1595                 if(likely(w->fds)) {
1596                         int c;
1597                         for(c = 0; c < p->fds_size ;c++) {
1598                                 if(p->fds[c] == 0) continue;
1599
1600                                 if(likely(p->fds[c] < all_files_size)) {
1601                                         if(w->fds) w->fds[p->fds[c]]++;
1602                                 }
1603                                 else
1604                                         error("Invalid fd number %d", p->fds[c]);
1605                         }
1606                 }
1607
1608                 if(unlikely(debug || w->debug))
1609                         fprintf(stderr, "apps.plugin: \tAggregating %s pid %d on %s utime=%llu, stime=%llu, cutime=%llu, cstime=%llu, minflt=%llu, majflt=%llu, cminflt=%llu, cmajflt=%llu, fix_cutime=%llu, fix_cstime=%llu, fix_cminflt=%llu, fix_cmajflt=%llu\n", p->comm, p->pid, w->name, p->utime, p->stime, p->cutime, p->cstime, p->minflt, p->majflt, p->cminflt, p->cmajflt, p->fix_cutime, p->fix_cstime, p->fix_cminflt, p->fix_cmajflt);
1610
1611 /*              if(p->utime - p->old_utime > 100) fprintf(stderr, "BIG CHANGE: %d %s utime increased by %llu from %llu to %llu\n", p->pid, p->comm, p->utime - p->old_utime, p->old_utime, p->utime);
1612                 if(p->cutime - p->old_cutime > 100) fprintf(stderr, "BIG CHANGE: %d %s cutime increased by %llu from %llu to %llu\n", p->pid, p->comm, p->cutime - p->old_cutime, p->old_cutime, p->cutime);
1613                 if(p->stime - p->old_stime > 100) fprintf(stderr, "BIG CHANGE: %d %s stime increased by %llu from %llu to %llu\n", p->pid, p->comm, p->stime - p->old_stime, p->old_stime, p->stime);
1614                 if(p->cstime - p->old_cstime > 100) fprintf(stderr, "BIG CHANGE: %d %s cstime increased by %llu from %llu to %llu\n", p->pid, p->comm, p->cstime - p->old_cstime, p->old_cstime, p->cstime);
1615                 if(p->minflt - p->old_minflt > 5000) fprintf(stderr, "BIG CHANGE: %d %s minflt increased by %llu from %llu to %llu\n", p->pid, p->comm, p->minflt - p->old_minflt, p->old_minflt, p->minflt);
1616                 if(p->majflt - p->old_majflt > 5000) fprintf(stderr, "BIG CHANGE: %d %s majflt increased by %llu from %llu to %llu\n", p->pid, p->comm, p->majflt - p->old_majflt, p->old_majflt, p->majflt);
1617                 if(p->cminflt - p->old_cminflt > 15000) fprintf(stderr, "BIG CHANGE: %d %s cminflt increased by %llu from %llu to %llu\n", p->pid, p->comm, p->cminflt - p->old_cminflt, p->old_cminflt, p->cminflt);
1618                 if(p->cmajflt - p->old_cmajflt > 15000) fprintf(stderr, "BIG CHANGE: %d %s cmajflt increased by %llu from %llu to %llu\n", p->pid, p->comm, p->cmajflt - p->old_cmajflt, p->old_cmajflt, p->cmajflt);
1619 */
1620
1621                 if(o) {
1622                         // since the process switched target
1623                         // for all incremental values
1624                         // we have to subtract its OLD values from the new target
1625                         // and add its OLD values to the old target
1626
1627                         // IMPORTANT
1628                         // We add/subtract the last/OLD values we added to the target
1629
1630                         w->fix_cutime -= (p->last_cutime - p->last_fix_cutime);
1631                         w->fix_cstime -= (p->last_cstime - p->last_fix_cstime);
1632                         w->fix_cminflt -= (p->last_cminflt - p->last_fix_cminflt);
1633                         w->fix_cmajflt -= (p->last_cmajflt - p->last_fix_cmajflt);
1634
1635                         w->fix_utime -= p->last_utime;
1636                         w->fix_stime -= p->last_stime;
1637                         w->fix_minflt -= p->last_minflt;
1638                         w->fix_majflt -= p->last_majflt;
1639
1640                         w->fix_io_logical_bytes_read -= p->last_io_logical_bytes_read;
1641                         w->fix_io_logical_bytes_written -= p->last_io_logical_bytes_written;
1642                         w->fix_io_read_calls -= p->last_io_read_calls;
1643                         w->fix_io_write_calls -= p->last_io_write_calls;
1644                         w->fix_io_storage_bytes_read -= p->last_io_storage_bytes_read;
1645                         w->fix_io_storage_bytes_written -= p->last_io_storage_bytes_written;
1646                         w->fix_io_cancelled_write_bytes -= p->last_io_cancelled_write_bytes;
1647
1648                         // ---
1649
1650                         o->fix_cutime += (p->last_cutime - p->last_fix_cutime);
1651                         o->fix_cstime += (p->last_cstime - p->last_fix_cstime);
1652                         o->fix_cminflt += (p->last_cminflt - p->last_fix_cminflt);
1653                         o->fix_cmajflt += (p->last_cmajflt - p->last_fix_cmajflt);
1654
1655                         o->fix_utime += p->last_utime;
1656                         o->fix_stime += p->last_stime;
1657                         o->fix_minflt += p->last_minflt;
1658                         o->fix_majflt += p->last_majflt;
1659
1660                         o->fix_io_logical_bytes_read += p->last_io_logical_bytes_read;
1661                         o->fix_io_logical_bytes_written += p->last_io_logical_bytes_written;
1662                         o->fix_io_read_calls += p->last_io_read_calls;
1663                         o->fix_io_write_calls += p->last_io_write_calls;
1664                         o->fix_io_storage_bytes_read += p->last_io_storage_bytes_read;
1665                         o->fix_io_storage_bytes_written += p->last_io_storage_bytes_written;
1666                         o->fix_io_cancelled_write_bytes += p->last_io_cancelled_write_bytes;
1667                 }
1668         }
1669         else {
1670                 // if(o) fprintf(stderr, "apps.plugin: \t\tpid %d (%s) is not updated by OLD target %s (%s) is present.\n", p->pid, p->comm, o->id, o->name);
1671
1672                 // since the process has exited, the user
1673                 // will see a drop in our charts, because the incremental
1674                 // values of this process will not be there
1675
1676                 // add them to the fix_* values and they will be added to
1677                 // the reported values, so that the report goes steady
1678                 w->fix_minflt += p->minflt;
1679                 w->fix_majflt += p->majflt;
1680                 w->fix_utime += p->utime;
1681                 w->fix_stime += p->stime;
1682
1683                 w->fix_cminflt += (p->cminflt - p->fix_cminflt);
1684                 w->fix_cmajflt += (p->cmajflt - p->fix_cmajflt);
1685                 w->fix_cutime += (p->cutime - p->fix_cutime);
1686                 w->fix_cstime += (p->cstime - p->fix_cstime);
1687
1688                 w->fix_io_logical_bytes_read += p->io_logical_bytes_read;
1689                 w->fix_io_logical_bytes_written += p->io_logical_bytes_written;
1690                 w->fix_io_read_calls += p->io_read_calls;
1691                 w->fix_io_write_calls += p->io_write_calls;
1692                 w->fix_io_storage_bytes_read += p->io_storage_bytes_read;
1693                 w->fix_io_storage_bytes_written += p->io_storage_bytes_written;
1694                 w->fix_io_cancelled_write_bytes += p->io_cancelled_write_bytes;
1695         }
1696
1697 }
1698
1699 void count_targets_fds(struct target *root) {
1700         int c;
1701         struct target *w;
1702
1703         for (w = root; w ; w = w->next) {
1704                 if(!w->fds) continue;
1705
1706                 w->openfiles = 0;
1707                 w->openpipes = 0;
1708                 w->opensockets = 0;
1709                 w->openinotifies = 0;
1710                 w->openeventfds = 0;
1711                 w->opentimerfds = 0;
1712                 w->opensignalfds = 0;
1713                 w->openeventpolls = 0;
1714                 w->openother = 0;
1715
1716                 for(c = 1; c < all_files_size ;c++) {
1717                         if(w->fds[c] > 0)
1718                                 switch(all_files[c].type) {
1719                                 case FILETYPE_FILE:
1720                                         w->openfiles++;
1721                                         break;
1722
1723                                 case FILETYPE_PIPE:
1724                                         w->openpipes++;
1725                                         break;
1726
1727                                 case FILETYPE_SOCKET:
1728                                         w->opensockets++;
1729                                         break;
1730
1731                                 case FILETYPE_INOTIFY:
1732                                         w->openinotifies++;
1733                                         break;
1734
1735                                 case FILETYPE_EVENTFD:
1736                                         w->openeventfds++;
1737                                         break;
1738
1739                                 case FILETYPE_TIMERFD:
1740                                         w->opentimerfds++;
1741                                         break;
1742
1743                                 case FILETYPE_SIGNALFD:
1744                                         w->opensignalfds++;
1745                                         break;
1746
1747                                 case FILETYPE_EVENTPOLL:
1748                                         w->openeventpolls++;
1749                                         break;
1750
1751                                 default:
1752                                         w->openother++;
1753                         }
1754                 }
1755
1756                 free(w->fds);
1757                 w->fds = NULL;
1758         }
1759 }
1760
1761 void calculate_netdata_statistics(void)
1762 {
1763         link_all_processes_to_their_parents();
1764         apply_apps_groups_targets_inheritance();
1765
1766         zero_all_targets(users_root_target);
1767         zero_all_targets(groups_root_target);
1768         apps_groups_targets = zero_all_targets(apps_groups_root_target);
1769
1770         // this has to be done, before the cleanup
1771         struct pid_stat *p = NULL;
1772         struct target *w = NULL, *o = NULL;
1773
1774         // concentrate everything on the apps_groups_targets
1775         for(p = root_of_pids; p ; p = p->next) {
1776
1777                 // --------------------------------------------------------------------
1778                 // apps_groups targets
1779                 if(likely(p->target))
1780                         aggregate_pid_on_target(p->target, p, NULL);
1781                 else
1782                         error("pid %d %s was left without a target!", p->pid, p->comm);
1783
1784
1785                 // --------------------------------------------------------------------
1786                 // user targets
1787                 o = p->user_target;
1788                 if(likely(p->user_target && p->user_target->uid == p->uid))
1789                         w = p->user_target;
1790                 else {
1791                         if(unlikely(debug && p->user_target))
1792                                         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);
1793
1794                         w = p->user_target = get_users_target(p->uid);
1795                 }
1796
1797                 if(likely(w))
1798                         aggregate_pid_on_target(w, p, o);
1799                 else
1800                         error("pid %d %s was left without a user target!", p->pid, p->comm);
1801
1802
1803                 // --------------------------------------------------------------------
1804                 // group targets
1805                 o = p->group_target;
1806                 if(likely(p->group_target && p->group_target->gid == p->gid))
1807                         w = p->group_target;
1808                 else {
1809                         if(unlikely(debug && p->group_target))
1810                                         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);
1811
1812                         w = p->group_target = get_groups_target(p->gid);
1813                 }
1814
1815                 if(likely(w))
1816                         aggregate_pid_on_target(w, p, o);
1817                 else
1818                         error("pid %d %s was left without a group target!", p->pid, p->comm);
1819
1820         }
1821
1822         count_targets_fds(apps_groups_root_target);
1823         count_targets_fds(users_root_target);
1824         count_targets_fds(groups_root_target);
1825
1826         cleanup_non_existing_pids();
1827 }
1828
1829 // ----------------------------------------------------------------------------
1830 // update chart dimensions
1831
1832 unsigned long long send_resource_usage_to_netdata() {
1833         static struct timeval last = { 0, 0 };
1834         static struct rusage me_last;
1835
1836         struct timeval now;
1837         struct rusage me;
1838
1839         unsigned long long usec;
1840         unsigned long long cpuuser;
1841         unsigned long long cpusyst;
1842
1843         if(!last.tv_sec) {
1844                 gettimeofday(&last, NULL);
1845                 getrusage(RUSAGE_SELF, &me_last);
1846
1847                 // the first time, give a zero to allow
1848                 // netdata calibrate to the current time
1849                 // usec = update_every * 1000000ULL;
1850                 usec = 0ULL;
1851                 cpuuser = 0;
1852                 cpusyst = 0;
1853         }
1854         else {
1855                 gettimeofday(&now, NULL);
1856                 getrusage(RUSAGE_SELF, &me);
1857
1858                 usec = usecdiff(&now, &last);
1859                 cpuuser = me.ru_utime.tv_sec * 1000000ULL + me.ru_utime.tv_usec;
1860                 cpusyst = me.ru_stime.tv_sec * 1000000ULL + me.ru_stime.tv_usec;
1861
1862                 bcopy(&now, &last, sizeof(struct timeval));
1863                 bcopy(&me, &me_last, sizeof(struct rusage));
1864         }
1865
1866         fprintf(stdout, "BEGIN netdata.apps_cpu %llu\n", usec);
1867         fprintf(stdout, "SET user = %llu\n", cpuuser);
1868         fprintf(stdout, "SET system = %llu\n", cpusyst);
1869         fprintf(stdout, "END\n");
1870
1871         fprintf(stdout, "BEGIN netdata.apps_files %llu\n", usec);
1872         fprintf(stdout, "SET files = %llu\n", file_counter);
1873         fprintf(stdout, "SET pids = %ld\n", all_pids_count);
1874         fprintf(stdout, "SET fds = %d\n", all_files_len);
1875         fprintf(stdout, "SET targets = %ld\n", apps_groups_targets);
1876         fprintf(stdout, "END\n");
1877
1878         return usec;
1879 }
1880
1881 void send_collected_data_to_netdata(struct target *root, const char *type, unsigned long long usec)
1882 {
1883         struct target *w;
1884
1885         fprintf(stdout, "BEGIN %s.cpu %llu\n", type, usec);
1886         for (w = root; w ; w = w->next) {
1887                 if(w->target || (!w->processes && !w->exposed)) continue;
1888
1889                 fprintf(stdout, "SET %s = %llu\n", w->name, w->utime + w->stime + w->fix_utime + w->fix_stime + w->cutime + w->cstime + w->fix_cutime + w->fix_cstime);
1890         }
1891         fprintf(stdout, "END\n");
1892
1893         fprintf(stdout, "BEGIN %s.cpu_user %llu\n", type, usec);
1894         for (w = root; w ; w = w->next) {
1895                 if(w->target || (!w->processes && !w->exposed)) continue;
1896
1897                 fprintf(stdout, "SET %s = %llu\n", w->name, w->utime + w->fix_utime + w->cutime + w->fix_cutime);
1898         }
1899         fprintf(stdout, "END\n");
1900
1901         fprintf(stdout, "BEGIN %s.cpu_system %llu\n", type, usec);
1902         for (w = root; w ; w = w->next) {
1903                 if(w->target || (!w->processes && !w->exposed)) continue;
1904
1905                 fprintf(stdout, "SET %s = %llu\n", w->name, w->stime + w->fix_stime + w->cstime + w->fix_cstime);
1906         }
1907         fprintf(stdout, "END\n");
1908
1909         fprintf(stdout, "BEGIN %s.threads %llu\n", type, usec);
1910         for (w = root; w ; w = w->next) {
1911                 if(w->target || (!w->processes && !w->exposed)) continue;
1912
1913                 fprintf(stdout, "SET %s = %llu\n", w->name, w->num_threads);
1914         }
1915         fprintf(stdout, "END\n");
1916
1917         fprintf(stdout, "BEGIN %s.processes %llu\n", type, usec);
1918         for (w = root; w ; w = w->next) {
1919                 if(w->target || (!w->processes && !w->exposed)) continue;
1920
1921                 fprintf(stdout, "SET %s = %lu\n", w->name, w->processes);
1922         }
1923         fprintf(stdout, "END\n");
1924
1925         fprintf(stdout, "BEGIN %s.mem %llu\n", type, usec);
1926         for (w = root; w ; w = w->next) {
1927                 if(w->target || (!w->processes && !w->exposed)) continue;
1928
1929                 fprintf(stdout, "SET %s = %lld\n", w->name, (long long)w->statm_resident - (long long)w->statm_share);
1930         }
1931         fprintf(stdout, "END\n");
1932
1933         fprintf(stdout, "BEGIN %s.minor_faults %llu\n", type, usec);
1934         for (w = root; w ; w = w->next) {
1935                 if(w->target || (!w->processes && !w->exposed)) continue;
1936
1937                 fprintf(stdout, "SET %s = %llu\n", w->name, w->minflt + w->fix_minflt + w->cminflt + w->fix_cminflt);
1938         }
1939         fprintf(stdout, "END\n");
1940
1941         fprintf(stdout, "BEGIN %s.major_faults %llu\n", type, usec);
1942         for (w = root; w ; w = w->next) {
1943                 if(w->target || (!w->processes && !w->exposed)) continue;
1944
1945                 fprintf(stdout, "SET %s = %llu\n", w->name, w->majflt + w->fix_majflt + w->cmajflt + w->fix_cmajflt);
1946         }
1947         fprintf(stdout, "END\n");
1948
1949         fprintf(stdout, "BEGIN %s.lreads %llu\n", type, usec);
1950         for (w = root; w ; w = w->next) {
1951                 if(w->target || (!w->processes && !w->exposed)) continue;
1952
1953                 fprintf(stdout, "SET %s = %llu\n", w->name, w->io_logical_bytes_read + w->fix_io_logical_bytes_read);
1954         }
1955         fprintf(stdout, "END\n");
1956
1957         fprintf(stdout, "BEGIN %s.lwrites %llu\n", type, usec);
1958         for (w = root; w ; w = w->next) {
1959                 if(w->target || (!w->processes && !w->exposed)) continue;
1960
1961                 fprintf(stdout, "SET %s = %llu\n", w->name, w->io_logical_bytes_written + w->fix_io_logical_bytes_written);
1962         }
1963         fprintf(stdout, "END\n");
1964
1965         fprintf(stdout, "BEGIN %s.preads %llu\n", type, usec);
1966         for (w = root; w ; w = w->next) {
1967                 if(w->target || (!w->processes && !w->exposed)) continue;
1968
1969                 fprintf(stdout, "SET %s = %llu\n", w->name, w->io_storage_bytes_read + w->fix_io_storage_bytes_read);
1970         }
1971         fprintf(stdout, "END\n");
1972
1973         fprintf(stdout, "BEGIN %s.pwrites %llu\n", type, usec);
1974         for (w = root; w ; w = w->next) {
1975                 if(w->target || (!w->processes && !w->exposed)) continue;
1976
1977                 fprintf(stdout, "SET %s = %llu\n", w->name, w->io_storage_bytes_written + w->fix_io_storage_bytes_written);
1978         }
1979         fprintf(stdout, "END\n");
1980
1981         fprintf(stdout, "BEGIN %s.files %llu\n", type, usec);
1982         for (w = root; w ; w = w->next) {
1983                 if(w->target || (!w->processes && !w->exposed)) continue;
1984
1985                 fprintf(stdout, "SET %s = %llu\n", w->name, w->openfiles);
1986         }
1987         fprintf(stdout, "END\n");
1988
1989         fprintf(stdout, "BEGIN %s.sockets %llu\n", type, usec);
1990         for (w = root; w ; w = w->next) {
1991                 if(w->target || (!w->processes && !w->exposed)) continue;
1992
1993                 fprintf(stdout, "SET %s = %llu\n", w->name, w->opensockets);
1994         }
1995         fprintf(stdout, "END\n");
1996
1997         fprintf(stdout, "BEGIN %s.pipes %llu\n", type, usec);
1998         for (w = root; w ; w = w->next) {
1999                 if(w->target || (!w->processes && !w->exposed)) continue;
2000
2001                 fprintf(stdout, "SET %s = %llu\n", w->name, w->openpipes);
2002         }
2003         fprintf(stdout, "END\n");
2004
2005         fflush(stdout);
2006 }
2007
2008
2009 // ----------------------------------------------------------------------------
2010 // generate the charts
2011
2012 void send_charts_updates_to_netdata(struct target *root, const char *type, const char *title)
2013 {
2014         struct target *w;
2015         int newly_added = 0;
2016
2017         for(w = root ; w ; w = w->next)
2018                 if(!w->exposed && w->processes) {
2019                         newly_added++;
2020                         w->exposed = 1;
2021                         if(debug || w->debug) fprintf(stderr, "apps.plugin: %s just added - regenerating charts.\n", w->name);
2022                 }
2023
2024         // nothing more to show
2025         if(!newly_added) return;
2026
2027         // we have something new to show
2028         // update the charts
2029         fprintf(stdout, "CHART %s.cpu '' '%s CPU Time (%d%% = %d core%s)' 'cpu time %%' cpu %s.cpu stacked 20001 %d\n", type, title, (processors * 100), processors, (processors>1)?"s":"", type, update_every);
2030         for (w = root; w ; w = w->next) {
2031                 if(w->target || (!w->processes && !w->exposed)) continue;
2032
2033                 fprintf(stdout, "DIMENSION %s '' incremental 100 %u %s\n", w->name, hz, w->hidden ? "hidden,noreset" : "noreset");
2034         }
2035
2036         fprintf(stdout, "CHART %s.mem '' '%s Dedicated Memory (w/o shared)' 'MB' mem %s.mem stacked 20003 %d\n", type, title, type, update_every);
2037         for (w = root; w ; w = w->next) {
2038                 if(w->target || (!w->processes && !w->exposed)) continue;
2039
2040                 fprintf(stdout, "DIMENSION %s '' absolute %ld %ld noreset\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
2041         }
2042
2043         fprintf(stdout, "CHART %s.threads '' '%s Threads' 'threads' processes %s.threads stacked 20005 %d\n", type, title, type, update_every);
2044         for (w = root; w ; w = w->next) {
2045                 if(w->target || (!w->processes && !w->exposed)) continue;
2046
2047                 fprintf(stdout, "DIMENSION %s '' absolute 1 1 noreset\n", w->name);
2048         }
2049
2050         fprintf(stdout, "CHART %s.processes '' '%s Processes' 'processes' processes %s.processes stacked 20004 %d\n", type, title, type, update_every);
2051         for (w = root; w ; w = w->next) {
2052                 if(w->target || (!w->processes && !w->exposed)) continue;
2053
2054                 fprintf(stdout, "DIMENSION %s '' absolute 1 1 noreset\n", w->name);
2055         }
2056
2057         fprintf(stdout, "CHART %s.cpu_user '' '%s CPU User Time (%d%% = %d core%s)' 'cpu time %%' cpu %s.cpu_user stacked 20020 %d\n", type, title, (processors * 100), processors, (processors>1)?"s":"", type, update_every);
2058         for (w = root; w ; w = w->next) {
2059                 if(w->target || (!w->processes && !w->exposed)) continue;
2060
2061                 fprintf(stdout, "DIMENSION %s '' incremental 100 %d noreset\n", w->name, hz);
2062         }
2063
2064         fprintf(stdout, "CHART %s.cpu_system '' '%s CPU System Time (%d%% = %d core%s)' 'cpu time %%' cpu %s.cpu_system stacked 20021 %d\n", type, title, (processors * 100), processors, (processors>1)?"s":"", type, update_every);
2065         for (w = root; w ; w = w->next) {
2066                 if(w->target || (!w->processes && !w->exposed)) continue;
2067
2068                 fprintf(stdout, "DIMENSION %s '' incremental 100 %d noreset\n", w->name, hz);
2069         }
2070
2071         fprintf(stdout, "CHART %s.major_faults '' '%s Major Page Faults (swap read)' 'page faults/s' swap %s.major_faults stacked 20010 %d\n", type, title, type, update_every);
2072         for (w = root; w ; w = w->next) {
2073                 if(w->target || (!w->processes && !w->exposed)) continue;
2074
2075                 fprintf(stdout, "DIMENSION %s '' incremental 1 1 noreset\n", w->name);
2076         }
2077
2078         fprintf(stdout, "CHART %s.minor_faults '' '%s Minor Page Faults' 'page faults/s' mem %s.minor_faults stacked 20011 %d\n", type, title, type, update_every);
2079         for (w = root; w ; w = w->next) {
2080                 if(w->target || (!w->processes && !w->exposed)) continue;
2081
2082                 fprintf(stdout, "DIMENSION %s '' incremental 1 1 noreset\n", w->name);
2083         }
2084
2085         fprintf(stdout, "CHART %s.lreads '' '%s Disk Logical Reads' 'kilobytes/s' disk %s.lreads stacked 20042 %d\n", type, title, type, update_every);
2086         for (w = root; w ; w = w->next) {
2087                 if(w->target || (!w->processes && !w->exposed)) continue;
2088
2089                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d noreset\n", w->name, 1024);
2090         }
2091
2092         fprintf(stdout, "CHART %s.lwrites '' '%s I/O Logical Writes' 'kilobytes/s' disk %s.lwrites stacked 20042 %d\n", type, title, type, update_every);
2093         for (w = root; w ; w = w->next) {
2094                 if(w->target || (!w->processes && !w->exposed)) continue;
2095
2096                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d noreset\n", w->name, 1024);
2097         }
2098
2099         fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'kilobytes/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
2100         for (w = root; w ; w = w->next) {
2101                 if(w->target || (!w->processes && !w->exposed)) continue;
2102
2103                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d noreset\n", w->name, 1024);
2104         }
2105
2106         fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'kilobytes/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
2107         for (w = root; w ; w = w->next) {
2108                 if(w->target || (!w->processes && !w->exposed)) continue;
2109
2110                 fprintf(stdout, "DIMENSION %s '' incremental 1 %d noreset\n", w->name, 1024);
2111         }
2112
2113         fprintf(stdout, "CHART %s.files '' '%s Open Files' 'open files' disk %s.files stacked 20050 %d\n", type, title, type, update_every);
2114         for (w = root; w ; w = w->next) {
2115                 if(w->target || (!w->processes && !w->exposed)) continue;
2116
2117                 fprintf(stdout, "DIMENSION %s '' absolute 1 1 noreset\n", w->name);
2118         }
2119
2120         fprintf(stdout, "CHART %s.sockets '' '%s Open Sockets' 'open sockets' net %s.sockets stacked 20051 %d\n", type, title, type, update_every);
2121         for (w = root; w ; w = w->next) {
2122                 if(w->target || (!w->processes && !w->exposed)) continue;
2123
2124                 fprintf(stdout, "DIMENSION %s '' absolute 1 1 noreset\n", w->name);
2125         }
2126
2127         fprintf(stdout, "CHART %s.pipes '' '%s Pipes' 'open pipes' processes %s.pipes stacked 20053 %d\n", type, title, type, update_every);
2128         for (w = root; w ; w = w->next) {
2129                 if(w->target || (!w->processes && !w->exposed)) continue;
2130
2131                 fprintf(stdout, "DIMENSION %s '' absolute 1 1 noreset\n", w->name);
2132         }
2133 }
2134
2135
2136 // ----------------------------------------------------------------------------
2137 // parse command line arguments
2138
2139 void parse_args(int argc, char **argv)
2140 {
2141         int i, freq = 0;
2142         char *name = NULL;
2143
2144         for(i = 1; i < argc; i++) {
2145                 if(!freq) {
2146                         int n = atoi(argv[i]);
2147                         if(n > 0) {
2148                                 freq = n;
2149                                 continue;
2150                         }
2151                 }
2152
2153                 if(strcmp("debug", argv[i]) == 0) {
2154                         debug = 1;
2155                         debug_flags = 0xffffffff;
2156                         continue;
2157                 }
2158
2159                 if(!name) {
2160                         name = argv[i];
2161                         continue;
2162                 }
2163
2164                 error("Cannot understand option %s", argv[i]);
2165                 exit(1);
2166         }
2167
2168         if(freq > 0) update_every = freq;
2169         if(!name) name = "groups";
2170
2171         if(read_apps_groups_conf(name)) {
2172                 error("Cannot read process groups %s", name);
2173                 exit(1);
2174         }
2175 }
2176
2177 int main(int argc, char **argv)
2178 {
2179         // debug_flags = D_PROCFILE;
2180
2181         // set the name for logging
2182         program_name = "apps.plugin";
2183
2184         // disable syslog for apps.plugin
2185         error_log_syslog = 0;
2186
2187         // set errors flood protection to 100 logs per hour
2188         error_log_errors_per_period = 100;
2189         error_log_throttle_period = 3600;
2190
2191         host_prefix = getenv("NETDATA_HOST_PREFIX");
2192         if(host_prefix == NULL) {
2193                 info("NETDATA_HOST_PREFIX is not passed from netdata");
2194                 host_prefix = "";
2195         }
2196         else info("Found NETDATA_HOST_PREFIX='%s'", host_prefix);
2197
2198         config_dir = getenv("NETDATA_CONFIG_DIR");
2199         if(config_dir == NULL) {
2200                 info("NETDATA_CONFIG_DIR is not passed from netdata");
2201                 config_dir = CONFIG_DIR;
2202         }
2203         else info("Found NETDATA_CONFIG_DIR='%s'", config_dir);
2204
2205 #ifdef NETDATA_INTERNAL_CHECKS
2206         if(debug_flags != 0) {
2207                 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
2208                 if(setrlimit(RLIMIT_CORE, &rl) != 0)
2209                         info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
2210                 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
2211         }
2212 #endif /* NETDATA_INTERNAL_CHECKS */
2213
2214         info("starting...");
2215
2216         procfile_adaptive_initial_allocation = 1;
2217
2218         time_t started_t = time(NULL);
2219         time_t current_t;
2220         get_HZ();
2221         pid_max = get_system_pid_max();
2222         processors = get_system_cpus();
2223
2224         parse_args(argc, argv);
2225
2226         all_pids = calloc(sizeof(struct pid_stat *), (size_t) pid_max);
2227         if(!all_pids) {
2228                 error("Cannot allocate %lu bytes of memory.", sizeof(struct pid_stat *) * pid_max);
2229                 printf("DISABLE\n");
2230                 exit(1);
2231         }
2232
2233         fprintf(stdout, "CHART netdata.apps_cpu '' 'Apps Plugin CPU' 'milliseconds/s' apps.plugin netdata.apps_cpu stacked 140000 %1$d\n"
2234                         "DIMENSION user '' incremental 1 1000\n"
2235                         "DIMENSION system '' incremental 1 1000\n"
2236                         "CHART netdata.apps_files '' 'Apps Plugin Files' 'files/s' apps.plugin netdata.apps_files line 140001 %1$d\n"
2237                         "DIMENSION files '' incremental 1 1\n"  
2238                   "DIMENSION pids '' absolute 1 1\n"  
2239                         "DIMENSION fds '' absolute 1 1\n"  
2240                         "DIMENSION targets '' absolute 1 1\n", update_every);
2241
2242 #ifndef PROFILING_MODE
2243         unsigned long long sunext = (time(NULL) - (time(NULL) % update_every) + update_every) * 1000000ULL;
2244         unsigned long long sunow;
2245 #endif /* PROFILING_MODE */
2246
2247         unsigned long long counter = 1;
2248         for(;1; counter++) {
2249 #ifndef PROFILING_MODE
2250                 // delay until it is our time to run
2251                 while((sunow = timems()) < sunext)
2252                         usleep((useconds_t)(sunext - sunow));
2253
2254                 // find the next time we need to run
2255                 while(timems() > sunext)
2256                         sunext += update_every * 1000000ULL;
2257 #endif /* PROFILING_MODE */
2258
2259                 if(!collect_data_for_all_processes_from_proc()) {
2260                         error("Cannot collect /proc data for running processes. Disabling apps.plugin...");
2261                         printf("DISABLE\n");
2262                         exit(1);
2263                 }
2264
2265                 calculate_netdata_statistics();
2266
2267                 unsigned long long dt = send_resource_usage_to_netdata();
2268
2269                 // this is smart enough to show only newly added apps, when needed
2270                 send_charts_updates_to_netdata(apps_groups_root_target, "apps", "Apps");
2271                 send_charts_updates_to_netdata(users_root_target, "users", "Users");
2272                 send_charts_updates_to_netdata(groups_root_target, "groups", "User Groups");
2273
2274                 send_collected_data_to_netdata(apps_groups_root_target, "apps", dt);
2275                 send_collected_data_to_netdata(users_root_target, "users", dt);
2276                 send_collected_data_to_netdata(groups_root_target, "groups", dt);
2277
2278                 if(unlikely(debug))
2279                         fprintf(stderr, "apps.plugin: done Loop No %llu\n", counter);
2280
2281                 current_t = time(NULL);
2282
2283 #ifndef PROFILING_MODE
2284                 // restart check (14400 seconds)
2285                 if(current_t - started_t > 14400) exit(0);
2286 #else
2287                 if(current_t - started_t > 10) exit(0);
2288 #endif /* PROFILING_MODE */
2289         }
2290 }