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