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