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