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