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