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