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