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