]> arthur.barton.de Git - netdata.git/blob - src/apps_plugin.c
Merge pull request #814 from ktsaou/master
[netdata.git] / src / apps_plugin.c
1 #include "common.h"
2
3 #define MAX_COMPARE_NAME 100
4 #define MAX_NAME 100
5 #define MAX_CMDLINE 1024
6
7 // the rates we are going to send to netdata
8 // will have this detail
9 // a value of:
10 // 1 will send just integer parts to netdata
11 // 100 will send 2 decimal points
12 // 1000 will send 3 decimal points
13 // etc.
14 #define RATES_DETAIL 10000ULL
15
16 int processors = 1;
17 pid_t pid_max = 32768;
18 int debug = 0;
19
20 int update_every = 1;
21 unsigned long long global_iterations_counter = 1;
22 unsigned long long file_counter = 0;
23 int proc_pid_cmdline_is_needed = 0;
24 int include_exited_childs = 1;
25 char *host_prefix = "";
26 char *config_dir = CONFIG_DIR;
27
28 pid_t *all_pids_sortlist = NULL;
29
30 // will be automatically set to 1, if guest values are collected
31 int show_guest_time = 0;
32 int show_guest_time_old = 0;
33
34 int enable_guest_charts = 0;
35 int enable_file_charts = 1;
36
37 // ----------------------------------------------------------------------------
38
39 void netdata_cleanup_and_exit(int ret) {
40     exit(ret);
41 }
42
43
44 // ----------------------------------------------------------------------------
45 // system functions
46 // to retrieve settings of the system
47
48 long get_system_cpus(void) {
49     procfile *ff = NULL;
50
51     int processors = 0;
52
53     char filename[FILENAME_MAX + 1];
54     snprintfz(filename, FILENAME_MAX, "%s/proc/stat", host_prefix);
55
56     ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);
57     if(!ff) return 1;
58
59     ff = procfile_readall(ff);
60     if(!ff)
61         return 1;
62
63     unsigned int i;
64     for(i = 0; i < procfile_lines(ff); i++) {
65         if(!procfile_linewords(ff, i)) continue;
66
67         if(strncmp(procfile_lineword(ff, i, 0), "cpu", 3) == 0) processors++;
68     }
69     processors--;
70     if(processors < 1) processors = 1;
71
72     procfile_close(ff);
73     return processors;
74 }
75
76 pid_t get_system_pid_max(void) {
77     procfile *ff = NULL;
78     pid_t mpid = 32768;
79
80     char filename[FILENAME_MAX + 1];
81     snprintfz(filename, FILENAME_MAX, "%s/proc/sys/kernel/pid_max", host_prefix);
82     ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);
83     if(!ff) return mpid;
84
85     ff = procfile_readall(ff);
86     if(!ff)
87         return mpid;
88
89     mpid = (pid_t)atoi(procfile_lineword(ff, 0, 0));
90     if(!mpid) mpid = 32768;
91
92     procfile_close(ff);
93     return mpid;
94 }
95
96 // ----------------------------------------------------------------------------
97 // target
98 // target is the structure that process data are aggregated
99
100 struct target {
101     char compare[MAX_COMPARE_NAME + 1];
102     uint32_t comparehash;
103     size_t comparelen;
104
105     char id[MAX_NAME + 1];
106     uint32_t idhash;
107
108     char name[MAX_NAME + 1];
109
110     uid_t uid;
111     gid_t gid;
112
113     unsigned long long minflt;
114     unsigned long long cminflt;
115     unsigned long long majflt;
116     unsigned long long cmajflt;
117     unsigned long long utime;
118     unsigned long long stime;
119     unsigned long long gtime;
120     unsigned long long cutime;
121     unsigned long long cstime;
122     unsigned long long cgtime;
123     unsigned long long num_threads;
124     unsigned long long rss;
125
126     unsigned long long statm_size;
127     unsigned long long statm_resident;
128     unsigned long long statm_share;
129     unsigned long long statm_text;
130     unsigned long long statm_lib;
131     unsigned long long statm_data;
132     unsigned long long statm_dirty;
133
134     unsigned long long io_logical_bytes_read;
135     unsigned long long io_logical_bytes_written;
136     unsigned long long io_read_calls;
137     unsigned long long io_write_calls;
138     unsigned long long io_storage_bytes_read;
139     unsigned long long io_storage_bytes_written;
140     unsigned long long io_cancelled_write_bytes;
141
142     int *fds;
143     unsigned long long openfiles;
144     unsigned long long openpipes;
145     unsigned long long opensockets;
146     unsigned long long openinotifies;
147     unsigned long long openeventfds;
148     unsigned long long opentimerfds;
149     unsigned long long opensignalfds;
150     unsigned long long openeventpolls;
151     unsigned long long openother;
152
153     unsigned long processes;    // how many processes have been merged to this
154     int exposed;                // if set, we have sent this to netdata
155     int hidden;                 // if set, we set the hidden flag on the dimension
156     int debug;
157     int ends_with;
158     int starts_with;            // if set, the compare string matches only the
159                                 // beginning of the command
160
161     struct target *target;      // the one that will be reported to netdata
162     struct target *next;
163 };
164
165
166 // ----------------------------------------------------------------------------
167 // apps_groups.conf
168 // aggregate all processes in groups, to have a limited number of dimensions
169
170 struct target *apps_groups_root_target = NULL;
171 struct target *apps_groups_default_target = NULL;
172 long apps_groups_targets = 0;
173
174 struct target *users_root_target = NULL;
175 struct target *groups_root_target = NULL;
176
177 struct target *get_users_target(uid_t uid)
178 {
179     struct target *w;
180     for(w = users_root_target ; w ; w = w->next)
181         if(w->uid == uid) return w;
182
183     w = callocz(sizeof(struct target), 1);
184     snprintfz(w->compare, MAX_COMPARE_NAME, "%u", uid);
185     w->comparehash = simple_hash(w->compare);
186     w->comparelen = strlen(w->compare);
187
188     snprintfz(w->id, MAX_NAME, "%u", uid);
189     w->idhash = simple_hash(w->id);
190
191     struct passwd *pw = getpwuid(uid);
192     if(!pw)
193         snprintfz(w->name, MAX_NAME, "%u", uid);
194     else
195         snprintfz(w->name, MAX_NAME, "%s", pw->pw_name);
196
197     netdata_fix_chart_name(w->name);
198
199     w->uid = uid;
200
201     w->next = users_root_target;
202     users_root_target = w;
203
204     if(unlikely(debug))
205         fprintf(stderr, "apps.plugin: added uid %u ('%s') target\n", w->uid, w->name);
206
207     return w;
208 }
209
210 struct target *get_groups_target(gid_t gid)
211 {
212     struct target *w;
213     for(w = groups_root_target ; w ; w = w->next)
214         if(w->gid == gid) return w;
215
216     w = callocz(sizeof(struct target), 1);
217     snprintfz(w->compare, MAX_COMPARE_NAME, "%u", gid);
218     w->comparehash = simple_hash(w->compare);
219     w->comparelen = strlen(w->compare);
220
221     snprintfz(w->id, MAX_NAME, "%u", gid);
222     w->idhash = simple_hash(w->id);
223
224     struct group *gr = getgrgid(gid);
225     if(!gr)
226         snprintfz(w->name, MAX_NAME, "%u", gid);
227     else
228         snprintfz(w->name, MAX_NAME, "%s", gr->gr_name);
229
230     netdata_fix_chart_name(w->name);
231
232     w->gid = gid;
233
234     w->next = groups_root_target;
235     groups_root_target = w;
236
237     if(unlikely(debug))
238         fprintf(stderr, "apps.plugin: added gid %u ('%s') target\n", w->gid, w->name);
239
240     return w;
241 }
242
243 // find or create a new target
244 // there are targets that are just aggregated to other target (the second argument)
245 struct target *get_apps_groups_target(const char *id, struct target *target) {
246     int tdebug = 0, thidden = 0, ends_with = 0;
247     const char *nid = id;
248
249     while(nid[0] == '-' || nid[0] == '+' || nid[0] == '*') {
250         if(nid[0] == '-') thidden = 1;
251         if(nid[0] == '+') tdebug = 1;
252         if(nid[0] == '*') ends_with = 1;
253         nid++;
254     }
255     uint32_t hash = simple_hash(id);
256
257     struct target *w, *last = apps_groups_root_target;
258     for(w = apps_groups_root_target ; w ; w = w->next) {
259         if(w->idhash == hash && strncmp(nid, w->id, MAX_NAME) == 0)
260             return w;
261
262         last = w;
263     }
264
265     w = callocz(sizeof(struct target), 1);
266     strncpyz(w->id, nid, MAX_NAME);
267     w->idhash = simple_hash(w->id);
268
269     strncpyz(w->name, nid, MAX_NAME);
270
271     strncpyz(w->compare, nid, MAX_COMPARE_NAME);
272     size_t len = strlen(w->compare);
273     if(w->compare[len - 1] == '*') {
274         w->compare[len - 1] = '\0';
275         w->starts_with = 1;
276     }
277     w->ends_with = ends_with;
278
279     if(w->starts_with && w->ends_with)
280         proc_pid_cmdline_is_needed = 1;
281
282     w->comparehash = simple_hash(w->compare);
283     w->comparelen = strlen(w->compare);
284
285     w->hidden = thidden;
286     w->debug = tdebug;
287     w->target = target;
288
289     // append it, to maintain the order in apps_groups.conf
290     if(last) last->next = w;
291     else apps_groups_root_target = w;
292
293     if(unlikely(debug))
294         fprintf(stderr, "apps.plugin: ADDING TARGET ID '%s', process name '%s' (%s), aggregated on target '%s', options: %s %s\n"
295                 , w->id
296                 , w->compare, (w->starts_with && w->ends_with)?"substring":((w->starts_with)?"prefix":((w->ends_with)?"suffix":"exact"))
297                 , w->target?w->target->id:w->id
298                 , (w->hidden)?"hidden":"-"
299                 , (w->debug)?"debug":"-"
300         );
301
302     return w;
303 }
304
305 // read the apps_groups.conf file
306 int read_apps_groups_conf(const char *name)
307 {
308     char filename[FILENAME_MAX + 1];
309
310     snprintfz(filename, FILENAME_MAX, "%s/apps_%s.conf", config_dir, name);
311
312     if(unlikely(debug))
313         fprintf(stderr, "apps.plugin: process groups file: '%s'\n", filename);
314
315     // ----------------------------------------
316
317     procfile *ff = procfile_open(filename, " :\t", PROCFILE_FLAG_DEFAULT);
318     if(!ff) return 1;
319
320     procfile_set_quotes(ff, "'\"");
321
322     ff = procfile_readall(ff);
323     if(!ff)
324         return 1;
325
326     unsigned long line, lines = procfile_lines(ff);
327
328     for(line = 0; line < lines ;line++) {
329         unsigned long word, words = procfile_linewords(ff, line);
330         struct target *w = NULL;
331
332         char *t = procfile_lineword(ff, line, 0);
333         if(!t || !*t) continue;
334
335         for(word = 0; word < words ;word++) {
336             char *s = procfile_lineword(ff, line, word);
337             if(!s || !*s) continue;
338             if(*s == '#') break;
339
340             if(t == s) continue;
341
342             struct target *n = get_apps_groups_target(s, w);
343             if(!n) {
344                 error("Cannot create target '%s' (line %lu, word %lu)", s, line, word);
345                 continue;
346             }
347
348             if(!w) w = n;
349         }
350
351         if(w) {
352             int tdebug = 0, thidden = 0;
353
354             while(t[0] == '-' || t[0] == '+') {
355                 if(t[0] == '-') thidden = 1;
356                 if(t[0] == '+') tdebug = 1;
357                 t++;
358             }
359
360             strncpyz(w->name, t, MAX_NAME);
361             w->hidden = thidden;
362             w->debug = tdebug;
363
364             if(unlikely(debug))
365                 fprintf(stderr, "apps.plugin: AGGREGATION TARGET NAME '%s' on ID '%s', process name '%s' (%s), aggregated on target '%s', options: %s %s\n"
366                         , w->name
367                         , w->id
368                         , w->compare, (w->starts_with && w->ends_with)?"substring":((w->starts_with)?"prefix":((w->ends_with)?"suffix":"exact"))
369                         , w->target?w->target->id:w->id
370                         , (w->hidden)?"hidden":"-"
371                         , (w->debug)?"debug":"-"
372                 );
373         }
374     }
375
376     procfile_close(ff);
377
378     apps_groups_default_target = get_apps_groups_target("p+!o@w#e$i^r&7*5(-i)l-o_", NULL); // match nothing
379     if(!apps_groups_default_target)
380         error("Cannot create default target");
381     else
382         strncpyz(apps_groups_default_target->name, "other", MAX_NAME);
383
384     return 0;
385 }
386
387
388 // ----------------------------------------------------------------------------
389 // data to store for each pid
390 // see: man proc
391
392 #define PID_LOG_IO      0x00000001
393 #define PID_LOG_STATM   0x00000002
394 #define PID_LOG_CMDLINE 0x00000004
395 #define PID_LOG_FDS     0x00000008
396 #define PID_LOG_STAT    0x00000010
397
398 struct pid_stat {
399     int32_t pid;
400     char comm[MAX_COMPARE_NAME + 1];
401     char cmdline[MAX_CMDLINE + 1];
402
403     uint32_t log_thrown;
404
405     // char state;
406     int32_t ppid;
407     // int32_t pgrp;
408     // int32_t session;
409     // int32_t tty_nr;
410     // int32_t tpgid;
411     // uint64_t flags;
412
413     // these are raw values collected
414     unsigned long long minflt_raw;
415     unsigned long long cminflt_raw;
416     unsigned long long majflt_raw;
417     unsigned long long cmajflt_raw;
418     unsigned long long utime_raw;
419     unsigned long long stime_raw;
420     unsigned long long gtime_raw; // guest_time
421     unsigned long long cutime_raw;
422     unsigned long long cstime_raw;
423     unsigned long long cgtime_raw; // cguest_time
424
425     // these are rates
426     unsigned long long minflt;
427     unsigned long long cminflt;
428     unsigned long long majflt;
429     unsigned long long cmajflt;
430     unsigned long long utime;
431     unsigned long long stime;
432     unsigned long long gtime;
433     unsigned long long cutime;
434     unsigned long long cstime;
435     unsigned long long cgtime;
436
437     // int64_t priority;
438     // int64_t nice;
439     int32_t num_threads;
440     // int64_t itrealvalue;
441     // unsigned long long starttime;
442     // unsigned long long vsize;
443     unsigned long long rss;
444     // unsigned long long rsslim;
445     // unsigned long long starcode;
446     // unsigned long long endcode;
447     // unsigned long long startstack;
448     // unsigned long long kstkesp;
449     // unsigned long long kstkeip;
450     // uint64_t signal;
451     // uint64_t blocked;
452     // uint64_t sigignore;
453     // uint64_t sigcatch;
454     // uint64_t wchan;
455     // uint64_t nswap;
456     // uint64_t cnswap;
457     // int32_t exit_signal;
458     // int32_t processor;
459     // uint32_t rt_priority;
460     // uint32_t policy;
461     // unsigned long long delayacct_blkio_ticks;
462
463     uid_t uid;
464     gid_t gid;
465
466     unsigned long long statm_size;
467     unsigned long long statm_resident;
468     unsigned long long statm_share;
469     unsigned long long statm_text;
470     unsigned long long statm_lib;
471     unsigned long long statm_data;
472     unsigned long long statm_dirty;
473
474     unsigned long long io_logical_bytes_read_raw;
475     unsigned long long io_logical_bytes_written_raw;
476     unsigned long long io_read_calls_raw;
477     unsigned long long io_write_calls_raw;
478     unsigned long long io_storage_bytes_read_raw;
479     unsigned long long io_storage_bytes_written_raw;
480     unsigned long long io_cancelled_write_bytes_raw;
481
482     unsigned long long io_logical_bytes_read;
483     unsigned long long io_logical_bytes_written;
484     unsigned long long io_read_calls;
485     unsigned long long io_write_calls;
486     unsigned long long io_storage_bytes_read;
487     unsigned long long io_storage_bytes_written;
488     unsigned long long io_cancelled_write_bytes;
489
490     int *fds;                       // array of fds it uses
491     int fds_size;                   // the size of the fds array
492
493     int children_count;             // number of processes directly referencing this
494     int keep;                       // 1 when we need to keep this process in memory even after it exited
495     int keeploops;                  // increases by 1 every time keep is 1 and updated 0
496     int updated;                    // 1 when the process is currently running
497     int merged;                     // 1 when it has been merged to its parent
498     int new_entry;                  // 1 when this is a new process, just saw for the first time
499     int read;                       // 1 when we have already read this process for this iteration
500     int sortlist;                   // higher numbers = top on the process tree
501                                     // each process gets a unique number
502
503     struct target *target;          // app_groups.conf targets
504     struct target *user_target;     // uid based targets
505     struct target *group_target;    // gid based targets
506
507     unsigned long long stat_collected_usec;
508     unsigned long long last_stat_collected_usec;
509
510     unsigned long long io_collected_usec;
511     unsigned long long last_io_collected_usec;
512
513     char *stat_filename;
514     char *statm_filename;
515     char *io_filename;
516     char *cmdline_filename;
517
518     struct pid_stat *parent;
519     struct pid_stat *prev;
520     struct pid_stat *next;
521 } *root_of_pids = NULL, **all_pids;
522
523 long all_pids_count = 0;
524
525 struct pid_stat *get_pid_entry(pid_t pid) {
526     if(all_pids[pid]) {
527         all_pids[pid]->new_entry = 0;
528         return all_pids[pid];
529     }
530
531     all_pids[pid] = callocz(sizeof(struct pid_stat), 1);
532     all_pids[pid]->fds = callocz(sizeof(int), 100);
533     all_pids[pid]->fds_size = 100;
534
535     if(root_of_pids) root_of_pids->prev = all_pids[pid];
536     all_pids[pid]->next = root_of_pids;
537     root_of_pids = all_pids[pid];
538
539     all_pids[pid]->pid = pid;
540     all_pids[pid]->new_entry = 1;
541
542     all_pids_count++;
543
544     return all_pids[pid];
545 }
546
547 void del_pid_entry(pid_t pid) {
548     if(!all_pids[pid]) {
549         error("attempted to free pid %d that is not allocated.", pid);
550         return;
551     }
552
553     if(unlikely(debug))
554         fprintf(stderr, "apps.plugin: process %d %s exited, deleting it.\n", pid, all_pids[pid]->comm);
555
556     if(root_of_pids == all_pids[pid]) root_of_pids = all_pids[pid]->next;
557     if(all_pids[pid]->next) all_pids[pid]->next->prev = all_pids[pid]->prev;
558     if(all_pids[pid]->prev) all_pids[pid]->prev->next = all_pids[pid]->next;
559
560     if(all_pids[pid]->fds) freez(all_pids[pid]->fds);
561     if(all_pids[pid]->stat_filename) freez(all_pids[pid]->stat_filename);
562     if(all_pids[pid]->statm_filename) freez(all_pids[pid]->statm_filename);
563     if(all_pids[pid]->io_filename) freez(all_pids[pid]->io_filename);
564     if(all_pids[pid]->cmdline_filename) freez(all_pids[pid]->cmdline_filename);
565     freez(all_pids[pid]);
566
567     all_pids[pid] = NULL;
568     all_pids_count--;
569 }
570
571
572 // ----------------------------------------------------------------------------
573 // update pids from proc
574
575 int read_proc_pid_cmdline(struct pid_stat *p) {
576     
577     if(unlikely(!p->cmdline_filename)) {
578         char filename[FILENAME_MAX + 1];
579         snprintfz(filename, FILENAME_MAX, "%s/proc/%d/cmdline", host_prefix, p->pid);
580         p->cmdline_filename = strdupz(filename);
581     }
582
583     int fd = open(p->cmdline_filename, O_RDONLY, 0666);
584     if(unlikely(fd == -1)) goto cleanup;
585
586     ssize_t i, bytes = read(fd, p->cmdline, MAX_CMDLINE);
587     close(fd);
588
589     if(unlikely(bytes < 0)) goto cleanup;
590
591     p->cmdline[bytes] = '\0';
592     for(i = 0; i < bytes ; i++)
593         if(unlikely(!p->cmdline[i])) p->cmdline[i] = ' ';
594
595     if(unlikely(debug))
596         fprintf(stderr, "Read file '%s' contents: %s\n", p->cmdline_filename, p->cmdline);
597
598     return 1;
599
600 cleanup:
601     // copy the command to the command line
602     strncpyz(p->cmdline, p->comm, MAX_CMDLINE);
603     return 0;
604 }
605
606 int read_proc_pid_ownership(struct pid_stat *p) {
607     if(unlikely(!p->stat_filename)) {
608         error("pid %d does not have a stat_filename", p->pid);
609         return 0;
610     }
611
612     // ----------------------------------------
613     // read uid and gid
614
615     struct stat st;
616     if(stat(p->stat_filename, &st) != 0) {
617         error("Cannot stat file '%s'", p->stat_filename);
618         return 1;
619     }
620
621     p->uid = st.st_uid;
622     p->gid = st.st_gid;
623
624     return 1;
625 }
626
627 int read_proc_pid_stat(struct pid_stat *p) {
628     static procfile *ff = NULL;
629
630     if(unlikely(!p->stat_filename)) {
631         char filename[FILENAME_MAX + 1];
632         snprintfz(filename, FILENAME_MAX, "%s/proc/%d/stat", host_prefix, p->pid);
633         p->stat_filename = strdupz(filename);
634     }
635
636     int set_quotes = (!ff)?1:0;
637
638     ff = procfile_reopen(ff, p->stat_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
639     if(unlikely(!ff)) goto cleanup;
640
641     // if(set_quotes) procfile_set_quotes(ff, "()");
642     if(set_quotes) procfile_set_open_close(ff, "(", ")");
643
644     ff = procfile_readall(ff);
645     if(unlikely(!ff)) goto cleanup;
646
647     p->last_stat_collected_usec = p->stat_collected_usec;
648     p->stat_collected_usec = time_usec();
649     file_counter++;
650
651     // p->pid           = atol(procfile_lineword(ff, 0, 0+i));
652
653     strncpyz(p->comm, procfile_lineword(ff, 0, 1), MAX_COMPARE_NAME);
654
655     // p->state         = *(procfile_lineword(ff, 0, 2));
656     p->ppid             = (int32_t) atol(procfile_lineword(ff, 0, 3));
657     // p->pgrp          = atol(procfile_lineword(ff, 0, 4));
658     // p->session       = atol(procfile_lineword(ff, 0, 5));
659     // p->tty_nr        = atol(procfile_lineword(ff, 0, 6));
660     // p->tpgid         = atol(procfile_lineword(ff, 0, 7));
661     // p->flags         = strtoull(procfile_lineword(ff, 0, 8), NULL, 10);
662
663     unsigned long long last;
664
665     last = p->minflt_raw;
666     p->minflt_raw       = strtoull(procfile_lineword(ff, 0, 9), NULL, 10);
667     p->minflt = (p->minflt_raw - last) * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
668
669     last = p->cminflt_raw;
670     p->cminflt_raw      = strtoull(procfile_lineword(ff, 0, 10), NULL, 10);
671     p->cminflt = (p->cminflt_raw - last) * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
672
673     last = p->majflt_raw;
674     p->majflt_raw       = strtoull(procfile_lineword(ff, 0, 11), NULL, 10);
675     p->majflt = (p->majflt_raw - last) * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
676
677     last = p->cmajflt_raw;
678     p->cmajflt_raw      = strtoull(procfile_lineword(ff, 0, 12), NULL, 10);
679     p->cmajflt = (p->cmajflt_raw - last) * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
680
681     last = p->utime_raw;
682     p->utime_raw        = strtoull(procfile_lineword(ff, 0, 13), NULL, 10);
683     p->utime = (p->utime_raw - last) * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
684
685     last = p->stime_raw;
686     p->stime_raw        = strtoull(procfile_lineword(ff, 0, 14), NULL, 10);
687     p->stime = (p->stime_raw - last) * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
688
689     last = p->cutime_raw;
690     p->cutime_raw       = strtoull(procfile_lineword(ff, 0, 15), NULL, 10);
691     p->cutime = (p->cutime_raw - last) * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
692
693     last = p->cstime_raw;
694     p->cstime_raw       = strtoull(procfile_lineword(ff, 0, 16), NULL, 10);
695     p->cstime = (p->cstime_raw - last) * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
696
697     // p->priority      = strtoull(procfile_lineword(ff, 0, 17), NULL, 10);
698     // p->nice          = strtoull(procfile_lineword(ff, 0, 18), NULL, 10);
699     p->num_threads      = (int32_t) atol(procfile_lineword(ff, 0, 19));
700     // p->itrealvalue   = strtoull(procfile_lineword(ff, 0, 20), NULL, 10);
701     // p->starttime     = strtoull(procfile_lineword(ff, 0, 21), NULL, 10);
702     // p->vsize         = strtoull(procfile_lineword(ff, 0, 22), NULL, 10);
703     p->rss              = strtoull(procfile_lineword(ff, 0, 23), NULL, 10);
704     // p->rsslim        = strtoull(procfile_lineword(ff, 0, 24), NULL, 10);
705     // p->starcode      = strtoull(procfile_lineword(ff, 0, 25), NULL, 10);
706     // p->endcode       = strtoull(procfile_lineword(ff, 0, 26), NULL, 10);
707     // p->startstack    = strtoull(procfile_lineword(ff, 0, 27), NULL, 10);
708     // p->kstkesp       = strtoull(procfile_lineword(ff, 0, 28), NULL, 10);
709     // p->kstkeip       = strtoull(procfile_lineword(ff, 0, 29), NULL, 10);
710     // p->signal        = strtoull(procfile_lineword(ff, 0, 30), NULL, 10);
711     // p->blocked       = strtoull(procfile_lineword(ff, 0, 31), NULL, 10);
712     // p->sigignore     = strtoull(procfile_lineword(ff, 0, 32), NULL, 10);
713     // p->sigcatch      = strtoull(procfile_lineword(ff, 0, 33), NULL, 10);
714     // p->wchan         = strtoull(procfile_lineword(ff, 0, 34), NULL, 10);
715     // p->nswap         = strtoull(procfile_lineword(ff, 0, 35), NULL, 10);
716     // p->cnswap        = strtoull(procfile_lineword(ff, 0, 36), NULL, 10);
717     // p->exit_signal   = atol(procfile_lineword(ff, 0, 37));
718     // p->processor     = atol(procfile_lineword(ff, 0, 38));
719     // p->rt_priority   = strtoul(procfile_lineword(ff, 0, 39), NULL, 10);
720     // p->policy        = strtoul(procfile_lineword(ff, 0, 40), NULL, 10);
721     // p->delayacct_blkio_ticks = strtoull(procfile_lineword(ff, 0, 41), NULL, 10);
722
723     if(enable_guest_charts) {
724         last = p->gtime_raw;
725         p->gtime_raw        = strtoull(procfile_lineword(ff, 0, 42), NULL, 10);
726         p->gtime = (p->gtime_raw - last) * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
727
728         last = p->cgtime_raw;
729         p->cgtime_raw       = strtoull(procfile_lineword(ff, 0, 43), NULL, 10);
730         p->cgtime = (p->cgtime_raw - last) * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
731
732         if (show_guest_time || p->gtime || p->cgtime) {
733             p->utime -= (p->utime >= p->gtime) ? p->gtime : p->utime;
734             p->cutime -= (p->cutime >= p->cgtime) ? p->cgtime : p->cutime;
735             show_guest_time = 1;
736         }
737     }
738
739     if(unlikely(debug || (p->target && p->target->debug)))
740         fprintf(stderr, "apps.plugin: READ PROC/PID/STAT: %s/proc/%d/stat, process: '%s' on target '%s' (dt=%llu) VALUES: utime=%llu, stime=%llu, cutime=%llu, cstime=%llu, minflt=%llu, majflt=%llu, cminflt=%llu, cmajflt=%llu, threads=%d\n", host_prefix, p->pid, p->comm, (p->target)?p->target->name:"UNSET", p->stat_collected_usec - p->last_stat_collected_usec, p->utime, p->stime, p->cutime, p->cstime, p->minflt, p->majflt, p->cminflt, p->cmajflt, p->num_threads);
741
742     if(unlikely(global_iterations_counter == 1)) {
743         p->minflt           = 0;
744         p->cminflt          = 0;
745         p->majflt           = 0;
746         p->cmajflt          = 0;
747         p->utime            = 0;
748         p->stime            = 0;
749         p->gtime            = 0;
750         p->cutime           = 0;
751         p->cstime           = 0;
752         p->cgtime           = 0;
753     }
754
755     return 1;
756
757 cleanup:
758     p->minflt           = 0;
759     p->cminflt          = 0;
760     p->majflt           = 0;
761     p->cmajflt          = 0;
762     p->utime            = 0;
763     p->stime            = 0;
764     p->gtime            = 0;
765     p->cutime           = 0;
766     p->cstime           = 0;
767     p->cgtime           = 0;
768     p->num_threads      = 0;
769     p->rss              = 0;
770     return 0;
771 }
772
773 int read_proc_pid_statm(struct pid_stat *p) {
774     static procfile *ff = NULL;
775
776     if(unlikely(!p->statm_filename)) {
777         char filename[FILENAME_MAX + 1];
778         snprintfz(filename, FILENAME_MAX, "%s/proc/%d/statm", host_prefix, p->pid);
779         p->statm_filename = strdupz(filename);
780     }
781
782     ff = procfile_reopen(ff, p->statm_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
783     if(unlikely(!ff)) goto cleanup;
784
785     ff = procfile_readall(ff);
786     if(unlikely(!ff)) goto cleanup;
787
788     file_counter++;
789
790     p->statm_size           = strtoull(procfile_lineword(ff, 0, 0), NULL, 10);
791     p->statm_resident       = strtoull(procfile_lineword(ff, 0, 1), NULL, 10);
792     p->statm_share          = strtoull(procfile_lineword(ff, 0, 2), NULL, 10);
793     p->statm_text           = strtoull(procfile_lineword(ff, 0, 3), NULL, 10);
794     p->statm_lib            = strtoull(procfile_lineword(ff, 0, 4), NULL, 10);
795     p->statm_data           = strtoull(procfile_lineword(ff, 0, 5), NULL, 10);
796     p->statm_dirty          = strtoull(procfile_lineword(ff, 0, 6), NULL, 10);
797
798     return 1;
799
800 cleanup:
801     p->statm_size           = 0;
802     p->statm_resident       = 0;
803     p->statm_share          = 0;
804     p->statm_text           = 0;
805     p->statm_lib            = 0;
806     p->statm_data           = 0;
807     p->statm_dirty          = 0;
808     return 0;
809 }
810
811 int read_proc_pid_io(struct pid_stat *p) {
812     static procfile *ff = NULL;
813
814     if(unlikely(!p->io_filename)) {
815         char filename[FILENAME_MAX + 1];
816         snprintfz(filename, FILENAME_MAX, "%s/proc/%d/io", host_prefix, p->pid);
817         p->io_filename = strdupz(filename);
818     }
819
820     // open the file
821     ff = procfile_reopen(ff, p->io_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
822     if(unlikely(!ff)) goto cleanup;
823
824     ff = procfile_readall(ff);
825     if(unlikely(!ff)) goto cleanup;
826
827     file_counter++;
828
829     p->last_io_collected_usec = p->io_collected_usec;
830     p->io_collected_usec = time_usec();
831
832     unsigned long long last;
833
834     last = p->io_logical_bytes_read_raw;
835     p->io_logical_bytes_read_raw = strtoull(procfile_lineword(ff, 0, 1), NULL, 10);
836     p->io_logical_bytes_read = (p->io_logical_bytes_read_raw - last) * (1000000ULL * RATES_DETAIL) / (p->io_collected_usec - p->last_io_collected_usec);
837
838     last = p->io_logical_bytes_written_raw;
839     p->io_logical_bytes_written_raw = strtoull(procfile_lineword(ff, 1, 1), NULL, 10);
840     p->io_logical_bytes_written = (p->io_logical_bytes_written_raw - last) * (1000000ULL * RATES_DETAIL) / (p->io_collected_usec - p->last_io_collected_usec);
841
842     last = p->io_read_calls_raw;
843     p->io_read_calls_raw = strtoull(procfile_lineword(ff, 2, 1), NULL, 10);
844     p->io_read_calls = (p->io_read_calls_raw - last) * (1000000ULL * RATES_DETAIL) / (p->io_collected_usec - p->last_io_collected_usec);
845
846     last = p->io_write_calls_raw;
847     p->io_write_calls_raw = strtoull(procfile_lineword(ff, 3, 1), NULL, 10);
848     p->io_write_calls = (p->io_write_calls_raw - last) * (1000000ULL * RATES_DETAIL) / (p->io_collected_usec - p->last_io_collected_usec);
849
850     last = p->io_storage_bytes_read_raw;
851     p->io_storage_bytes_read_raw = strtoull(procfile_lineword(ff, 4, 1), NULL, 10);
852     p->io_storage_bytes_read = (p->io_storage_bytes_read_raw - last) * (1000000ULL * RATES_DETAIL) / (p->io_collected_usec - p->last_io_collected_usec);
853
854     last = p->io_storage_bytes_written_raw;
855     p->io_storage_bytes_written_raw = strtoull(procfile_lineword(ff, 5, 1), NULL, 10);
856     p->io_storage_bytes_written = (p->io_storage_bytes_written_raw - last) * (1000000ULL * RATES_DETAIL) / (p->io_collected_usec - p->last_io_collected_usec);
857
858     last = p->io_cancelled_write_bytes_raw;
859     p->io_cancelled_write_bytes_raw = strtoull(procfile_lineword(ff, 6, 1), NULL, 10);
860     p->io_cancelled_write_bytes = (p->io_cancelled_write_bytes_raw - last) * (1000000ULL * RATES_DETAIL) / (p->io_collected_usec - p->last_io_collected_usec);
861
862     if(unlikely(global_iterations_counter == 1)) {
863         p->io_logical_bytes_read        = 0;
864         p->io_logical_bytes_written     = 0;
865         p->io_read_calls                = 0;
866         p->io_write_calls               = 0;
867         p->io_storage_bytes_read        = 0;
868         p->io_storage_bytes_written     = 0;
869         p->io_cancelled_write_bytes     = 0;
870     }
871
872     return 1;
873
874 cleanup:
875     p->io_logical_bytes_read        = 0;
876     p->io_logical_bytes_written     = 0;
877     p->io_read_calls                = 0;
878     p->io_write_calls               = 0;
879     p->io_storage_bytes_read        = 0;
880     p->io_storage_bytes_written     = 0;
881     p->io_cancelled_write_bytes     = 0;
882     return 0;
883 }
884
885 unsigned long long global_utime = 0;
886 unsigned long long global_stime = 0;
887 unsigned long long global_gtime = 0;
888
889 int read_proc_stat() {
890     static char filename[FILENAME_MAX + 1] = "";
891     static procfile *ff = NULL;
892     static unsigned long long utime_raw = 0, stime_raw = 0, gtime_raw = 0, gntime_raw = 0, ntime_raw = 0, collected_usec = 0, last_collected_usec = 0;
893
894     if(unlikely(!ff)) {
895         snprintfz(filename, FILENAME_MAX, "%s/proc/stat", host_prefix);
896         ff = procfile_open(filename, " \t:", PROCFILE_FLAG_DEFAULT);
897         if(unlikely(!ff)) goto cleanup;
898     }
899
900     ff = procfile_readall(ff);
901     if(unlikely(!ff)) goto cleanup;
902
903     last_collected_usec = collected_usec;
904     collected_usec = time_usec();
905
906     file_counter++;
907
908     unsigned long long last;
909
910     last = utime_raw;
911     utime_raw = strtoull(procfile_lineword(ff, 0, 1), NULL, 10);
912     global_utime = (utime_raw - last) * (1000000ULL * RATES_DETAIL) / (collected_usec - last_collected_usec);
913
914     // nice time, on user time
915     last = ntime_raw;
916     ntime_raw = strtoull(procfile_lineword(ff, 0, 2), NULL, 10);
917     global_utime += (ntime_raw - last) * (1000000ULL * RATES_DETAIL) / (collected_usec - last_collected_usec);
918
919     last = stime_raw;
920     stime_raw = strtoull(procfile_lineword(ff, 0, 3), NULL, 10);
921     global_stime = (stime_raw - last) * (1000000ULL * RATES_DETAIL) / (collected_usec - last_collected_usec);
922
923     last = gtime_raw;
924     gtime_raw = strtoull(procfile_lineword(ff, 0, 10), NULL, 10);
925     global_gtime = (gtime_raw - last) * (1000000ULL * RATES_DETAIL) / (collected_usec - last_collected_usec);
926
927     if(enable_guest_charts) {
928         // guest nice time, on guest time
929         last = gntime_raw;
930         gntime_raw = strtoull(procfile_lineword(ff, 0, 11), NULL, 10);
931         global_gtime += (gntime_raw - last) * (1000000ULL * RATES_DETAIL) / (collected_usec - last_collected_usec);
932
933         // remove guest time from user time
934         global_utime -= (global_utime > global_gtime) ? global_gtime : global_utime;
935     }
936
937     if(unlikely(global_iterations_counter == 1)) {
938         global_utime = 0;
939         global_stime = 0;
940         global_gtime = 0;
941     }
942
943     return 1;
944
945 cleanup:
946     global_utime = 0;
947     global_stime = 0;
948     global_gtime = 0;
949     return 0;
950 }
951
952
953 // ----------------------------------------------------------------------------
954 // file descriptor
955 // this is used to keep a global list of all open files of the system
956 // it is needed in order to calculate the unique files processes have open
957
958 #define FILE_DESCRIPTORS_INCREASE_STEP 100
959
960 struct file_descriptor {
961     avl avl;
962 #ifdef NETDATA_INTERNAL_CHECKS
963     uint32_t magic;
964 #endif /* NETDATA_INTERNAL_CHECKS */
965     uint32_t hash;
966     const char *name;
967     int type;
968     int count;
969     int pos;
970 } *all_files = NULL;
971
972 int all_files_len = 0;
973 int all_files_size = 0;
974
975 int file_descriptor_compare(void* a, void* b) {
976 #ifdef NETDATA_INTERNAL_CHECKS
977     if(((struct file_descriptor *)a)->magic != 0x0BADCAFE || ((struct file_descriptor *)b)->magic != 0x0BADCAFE)
978         error("Corrupted index data detected. Please report this.");
979 #endif /* NETDATA_INTERNAL_CHECKS */
980
981     if(((struct file_descriptor *)a)->hash < ((struct file_descriptor *)b)->hash)
982         return -1;
983
984     else if(((struct file_descriptor *)a)->hash > ((struct file_descriptor *)b)->hash)
985         return 1;
986
987     else
988         return strcmp(((struct file_descriptor *)a)->name, ((struct file_descriptor *)b)->name);
989 }
990
991 int file_descriptor_iterator(avl *a) { if(a) {}; return 0; }
992
993 avl_tree all_files_index = {
994         NULL,
995         file_descriptor_compare
996 };
997
998 static struct file_descriptor *file_descriptor_find(const char *name, uint32_t hash) {
999     struct file_descriptor tmp;
1000     tmp.hash = (hash)?hash:simple_hash(name);
1001     tmp.name = name;
1002     tmp.count = 0;
1003     tmp.pos = 0;
1004 #ifdef NETDATA_INTERNAL_CHECKS
1005     tmp.magic = 0x0BADCAFE;
1006 #endif /* NETDATA_INTERNAL_CHECKS */
1007
1008     return (struct file_descriptor *)avl_search(&all_files_index, (avl *) &tmp);
1009 }
1010
1011 #define file_descriptor_add(fd) avl_insert(&all_files_index, (avl *)(fd))
1012 #define file_descriptor_remove(fd) avl_remove(&all_files_index, (avl *)(fd))
1013
1014 #define FILETYPE_OTHER 0
1015 #define FILETYPE_FILE 1
1016 #define FILETYPE_PIPE 2
1017 #define FILETYPE_SOCKET 3
1018 #define FILETYPE_INOTIFY 4
1019 #define FILETYPE_EVENTFD 5
1020 #define FILETYPE_EVENTPOLL 6
1021 #define FILETYPE_TIMERFD 7
1022 #define FILETYPE_SIGNALFD 8
1023
1024 void file_descriptor_not_used(int id)
1025 {
1026     if(id > 0 && id < all_files_size) {
1027
1028 #ifdef NETDATA_INTERNAL_CHECKS
1029         if(all_files[id].magic != 0x0BADCAFE) {
1030             error("Ignoring request to remove empty file id %d.", id);
1031             return;
1032         }
1033 #endif /* NETDATA_INTERNAL_CHECKS */
1034
1035         if(unlikely(debug))
1036             fprintf(stderr, "apps.plugin: decreasing slot %d (count = %d).\n", id, all_files[id].count);
1037
1038         if(all_files[id].count > 0) {
1039             all_files[id].count--;
1040
1041             if(!all_files[id].count) {
1042                 if(unlikely(debug))
1043                     fprintf(stderr, "apps.plugin:   >> slot %d is empty.\n", id);
1044
1045                 file_descriptor_remove(&all_files[id]);
1046 #ifdef NETDATA_INTERNAL_CHECKS
1047                 all_files[id].magic = 0x00000000;
1048 #endif /* NETDATA_INTERNAL_CHECKS */
1049                 all_files_len--;
1050             }
1051         }
1052         else
1053             error("Request to decrease counter of fd %d (%s), while the use counter is 0", id, all_files[id].name);
1054     }
1055     else    error("Request to decrease counter of fd %d, which is outside the array size (1 to %d)", id, all_files_size);
1056 }
1057
1058 int file_descriptor_find_or_add(const char *name)
1059 {
1060     static int last_pos = 0;
1061     uint32_t hash = simple_hash(name);
1062
1063     if(unlikely(debug))
1064         fprintf(stderr, "apps.plugin: adding or finding name '%s' with hash %u\n", name, hash);
1065
1066     struct file_descriptor *fd = file_descriptor_find(name, hash);
1067     if(fd) {
1068         // found
1069         if(unlikely(debug))
1070             fprintf(stderr, "apps.plugin:   >> found on slot %d\n", fd->pos);
1071
1072         fd->count++;
1073         return fd->pos;
1074     }
1075     // not found
1076
1077     // check we have enough memory to add it
1078     if(!all_files || all_files_len == all_files_size) {
1079         void *old = all_files;
1080         int i;
1081
1082         // there is no empty slot
1083         if(unlikely(debug))
1084             fprintf(stderr, "apps.plugin: extending fd array to %d entries\n", all_files_size + FILE_DESCRIPTORS_INCREASE_STEP);
1085
1086         all_files = reallocz(all_files, (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP) * sizeof(struct file_descriptor));
1087
1088         // if the address changed, we have to rebuild the index
1089         // since all pointers are now invalid
1090         if(old && old != (void *)all_files) {
1091             if(unlikely(debug))
1092                 fprintf(stderr, "apps.plugin:   >> re-indexing.\n");
1093
1094             all_files_index.root = NULL;
1095             for(i = 0; i < all_files_size; i++) {
1096                 if(!all_files[i].count) continue;
1097                 file_descriptor_add(&all_files[i]);
1098             }
1099
1100             if(unlikely(debug))
1101                 fprintf(stderr, "apps.plugin:   >> re-indexing done.\n");
1102         }
1103
1104         for(i = all_files_size; i < (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP); i++) {
1105             all_files[i].count = 0;
1106             all_files[i].name = NULL;
1107 #ifdef NETDATA_INTERNAL_CHECKS
1108             all_files[i].magic = 0x00000000;
1109 #endif /* NETDATA_INTERNAL_CHECKS */
1110             all_files[i].pos = i;
1111         }
1112
1113         if(!all_files_size) all_files_len = 1;
1114         all_files_size += FILE_DESCRIPTORS_INCREASE_STEP;
1115     }
1116
1117     if(unlikely(debug))
1118         fprintf(stderr, "apps.plugin:   >> searching for empty slot.\n");
1119
1120     // search for an empty slot
1121     int i, c;
1122     for(i = 0, c = last_pos ; i < all_files_size ; i++, c++) {
1123         if(c >= all_files_size) c = 0;
1124         if(c == 0) continue;
1125
1126         if(!all_files[c].count) {
1127             if(unlikely(debug))
1128                 fprintf(stderr, "apps.plugin:   >> Examining slot %d.\n", c);
1129
1130 #ifdef NETDATA_INTERNAL_CHECKS
1131             if(all_files[c].magic == 0x0BADCAFE && all_files[c].name && file_descriptor_find(all_files[c].name, all_files[c].hash))
1132                 error("fd on position %d is not cleared properly. It still has %s in it.\n", c, all_files[c].name);
1133 #endif /* NETDATA_INTERNAL_CHECKS */
1134
1135             if(unlikely(debug))
1136                 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);
1137
1138             if(all_files[c].name) freez((void *)all_files[c].name);
1139             all_files[c].name = NULL;
1140             last_pos = c;
1141             break;
1142         }
1143     }
1144     if(i == all_files_size) {
1145         fatal("We should find an empty slot, but there isn't any");
1146         exit(1);
1147     }
1148
1149     if(unlikely(debug))
1150         fprintf(stderr, "apps.plugin:   >> updating slot %d.\n", c);
1151
1152     all_files_len++;
1153
1154     // else we have an empty slot in 'c'
1155
1156     int type;
1157     if(name[0] == '/') type = FILETYPE_FILE;
1158     else if(strncmp(name, "pipe:", 5) == 0) type = FILETYPE_PIPE;
1159     else if(strncmp(name, "socket:", 7) == 0) type = FILETYPE_SOCKET;
1160     else if(strcmp(name, "anon_inode:inotify") == 0 || strcmp(name, "inotify") == 0) type = FILETYPE_INOTIFY;
1161     else if(strcmp(name, "anon_inode:[eventfd]") == 0) type = FILETYPE_EVENTFD;
1162     else if(strcmp(name, "anon_inode:[eventpoll]") == 0) type = FILETYPE_EVENTPOLL;
1163     else if(strcmp(name, "anon_inode:[timerfd]") == 0) type = FILETYPE_TIMERFD;
1164     else if(strcmp(name, "anon_inode:[signalfd]") == 0) type = FILETYPE_SIGNALFD;
1165     else if(strncmp(name, "anon_inode:", 11) == 0) {
1166         if(unlikely(debug))
1167             fprintf(stderr, "apps.plugin: FIXME: unknown anonymous inode: %s\n", name);
1168
1169         type = FILETYPE_OTHER;
1170     }
1171     else {
1172         if(unlikely(debug))
1173             fprintf(stderr, "apps.plugin: FIXME: cannot understand linkname: %s\n", name);
1174
1175         type = FILETYPE_OTHER;
1176     }
1177
1178     all_files[c].name = strdupz(name);
1179     all_files[c].hash = hash;
1180     all_files[c].type = type;
1181     all_files[c].pos  = c;
1182     all_files[c].count = 1;
1183 #ifdef NETDATA_INTERNAL_CHECKS
1184     all_files[c].magic = 0x0BADCAFE;
1185 #endif /* NETDATA_INTERNAL_CHECKS */
1186     file_descriptor_add(&all_files[c]);
1187
1188     if(unlikely(debug))
1189         fprintf(stderr, "apps.plugin: using fd position %d (name: %s)\n", c, all_files[c].name);
1190
1191     return c;
1192 }
1193
1194 int read_pid_file_descriptors(struct pid_stat *p) {
1195     char dirname[FILENAME_MAX+1];
1196
1197     snprintfz(dirname, FILENAME_MAX, "%s/proc/%d/fd", host_prefix, p->pid);
1198     DIR *fds = opendir(dirname);
1199     if(fds) {
1200         int c;
1201         struct dirent *de;
1202         char fdname[FILENAME_MAX + 1];
1203         char linkname[FILENAME_MAX + 1];
1204
1205         // make the array negative
1206         for(c = 0 ; c < p->fds_size ; c++)
1207             p->fds[c] = -p->fds[c];
1208
1209         while((de = readdir(fds))) {
1210             if(strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
1211                 continue;
1212
1213             // check if the fds array is small
1214             int fdid = atoi(de->d_name);
1215             if(fdid < 0) continue;
1216             if(fdid >= p->fds_size) {
1217                 // it is small, extend it
1218                 if(unlikely(debug))
1219                     fprintf(stderr, "apps.plugin: extending fd memory slots for %s from %d to %d\n", p->comm, p->fds_size, fdid + 100);
1220
1221                 p->fds = reallocz(p->fds, (fdid + 100) * sizeof(int));
1222                 if(!p->fds) {
1223                     fatal("Cannot re-allocate fds for %s", p->comm);
1224                     break;
1225                 }
1226
1227                 // and initialize it
1228                 for(c = p->fds_size ; c < (fdid + 100) ; c++) p->fds[c] = 0;
1229                 p->fds_size = fdid + 100;
1230             }
1231
1232             if(p->fds[fdid] == 0) {
1233                 // we don't know this fd, get it
1234
1235                 sprintf(fdname, "%s/proc/%d/fd/%s", host_prefix, p->pid, de->d_name);
1236                 ssize_t l = readlink(fdname, linkname, FILENAME_MAX);
1237                 if(l == -1) {
1238                     if(debug || (p->target && p->target->debug)) {
1239                         if(debug || (p->target && p->target->debug))
1240                             error("Cannot read link %s", fdname);
1241                     }
1242                     continue;
1243                 }
1244                 linkname[l] = '\0';
1245                 file_counter++;
1246
1247                 // if another process already has this, we will get
1248                 // the same id
1249                 p->fds[fdid] = file_descriptor_find_or_add(linkname);
1250             }
1251
1252             // else make it positive again, we need it
1253             // of course, the actual file may have changed, but we don't care so much
1254             // FIXME: we could compare the inode as returned by readdir dirent structure
1255             else p->fds[fdid] = -p->fds[fdid];
1256         }
1257         closedir(fds);
1258
1259         // remove all the negative file descriptors
1260         for(c = 0 ; c < p->fds_size ; c++) if(p->fds[c] < 0) {
1261             file_descriptor_not_used(-p->fds[c]);
1262             p->fds[c] = 0;
1263         }
1264     }
1265     else return 0;
1266
1267     return 1;
1268 }
1269
1270 // ----------------------------------------------------------------------------
1271
1272 int print_process_and_parents(struct pid_stat *p, unsigned long long time) {
1273     char *prefix = "\\_ ";
1274     int indent = 0;
1275
1276     if(p->parent)
1277         indent = print_process_and_parents(p->parent, p->stat_collected_usec);
1278     else
1279         prefix = " > ";
1280
1281     char buffer[indent + 1];
1282     int i;
1283
1284     for(i = 0; i < indent ;i++) buffer[i] = ' ';
1285     buffer[i] = '\0';
1286
1287     fprintf(stderr, "  %s %s%s (%d %s %lld"
1288         , buffer
1289         , prefix
1290         , p->comm
1291         , p->pid
1292         , p->updated?"running":"exited"
1293         , (long long)p->stat_collected_usec - (long long)time
1294         );
1295
1296     if(p->utime)   fprintf(stderr, " utime=%llu",   p->utime);
1297     if(p->stime)   fprintf(stderr, " stime=%llu",   p->stime);
1298     if(p->gtime)   fprintf(stderr, " gtime=%llu",   p->gtime);
1299     if(p->cutime)  fprintf(stderr, " cutime=%llu",  p->cutime);
1300     if(p->cstime)  fprintf(stderr, " cstime=%llu",  p->cstime);
1301     if(p->cgtime)  fprintf(stderr, " cgtime=%llu",  p->cgtime);
1302     if(p->minflt)  fprintf(stderr, " minflt=%llu",  p->minflt);
1303     if(p->cminflt) fprintf(stderr, " cminflt=%llu", p->cminflt);
1304     if(p->majflt)  fprintf(stderr, " majflt=%llu",  p->majflt);
1305     if(p->cmajflt) fprintf(stderr, " cmajflt=%llu", p->cmajflt);
1306     fprintf(stderr, ")\n");
1307
1308     return indent + 1;
1309 }
1310
1311 void print_process_tree(struct pid_stat *p, char *msg) {
1312     log_date(stderr);
1313     fprintf(stderr, "%s: process %s (%d, %s) with parents:\n", msg, p->comm, p->pid, p->updated?"running":"exited");
1314     print_process_and_parents(p, p->stat_collected_usec);
1315 }
1316
1317 void find_lost_child_debug(struct pid_stat *pe, unsigned long long lost, int type) {
1318     int found = 0;
1319     struct pid_stat *p = NULL;
1320
1321     for(p = root_of_pids; p ; p = p->next) {
1322         if(p == pe) continue;
1323
1324         switch(type) {
1325             case 1:
1326                 if(p->cminflt > lost) {
1327                     fprintf(stderr, " > process %d (%s) could use the lost exited child minflt %llu of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
1328                     found++;
1329                 }
1330                 break;
1331                 
1332             case 2:
1333                 if(p->cmajflt > lost) {
1334                     fprintf(stderr, " > process %d (%s) could use the lost exited child majflt %llu of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
1335                     found++;
1336                 }
1337                 break;
1338                 
1339             case 3:
1340                 if(p->cutime > lost) {
1341                     fprintf(stderr, " > process %d (%s) could use the lost exited child utime %llu of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
1342                     found++;
1343                 }
1344                 break;
1345
1346             case 4:
1347                 if(p->cstime > lost) {
1348                     fprintf(stderr, " > process %d (%s) could use the lost exited child stime %llu of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
1349                     found++;
1350                 }
1351                 break;
1352
1353             case 5:
1354                 if(p->cgtime > lost) {
1355                     fprintf(stderr, " > process %d (%s) could use the lost exited child gtime %llu of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
1356                     found++;
1357                 }
1358                 break;
1359         }
1360     }
1361
1362     if(!found) {
1363         switch(type) {
1364             case 1:
1365                 fprintf(stderr, " > cannot find any process to use the lost exited child minflt %llu of process %d (%s)\n", lost, pe->pid, pe->comm);
1366                 break;
1367                 
1368             case 2:
1369                 fprintf(stderr, " > cannot find any process to use the lost exited child majflt %llu of process %d (%s)\n", lost, pe->pid, pe->comm);
1370                 break;
1371                 
1372             case 3:
1373                 fprintf(stderr, " > cannot find any process to use the lost exited child utime %llu of process %d (%s)\n", lost, pe->pid, pe->comm);
1374                 break;
1375
1376             case 4:
1377                 fprintf(stderr, " > cannot find any process to use the lost exited child stime %llu of process %d (%s)\n", lost, pe->pid, pe->comm);
1378                 break;
1379
1380             case 5:
1381                 fprintf(stderr, " > cannot find any process to use the lost exited child gtime %llu of process %d (%s)\n", lost, pe->pid, pe->comm);
1382                 break;
1383         }
1384     }
1385 }
1386
1387 unsigned long long remove_exited_child_from_parent(unsigned long long *field, unsigned long long *pfield) {
1388     unsigned long long absorbed = 0;
1389
1390     if(*field > *pfield) {
1391         absorbed += *pfield;
1392         *field -= *pfield;
1393         *pfield = 0;
1394     }
1395     else {
1396         absorbed += *field;
1397         *pfield -= *field;
1398         *field = 0;
1399     }
1400
1401     return absorbed;
1402 }
1403
1404 void process_exited_processes() {
1405     struct pid_stat *p;
1406
1407     for(p = root_of_pids; p ; p = p->next) {
1408         if(p->updated || !p->stat_collected_usec)
1409             continue;
1410
1411         struct pid_stat *pp = p->parent;
1412
1413         unsigned long long utime  = (p->utime_raw + p->cutime_raw)   * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1414         unsigned long long stime  = (p->stime_raw + p->cstime_raw)   * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1415         unsigned long long gtime  = (p->gtime_raw + p->cgtime_raw)   * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1416         unsigned long long minflt = (p->minflt_raw + p->cminflt_raw) * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1417         unsigned long long majflt = (p->majflt_raw + p->cmajflt_raw) * (1000000ULL * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1418
1419         if(utime + stime + gtime + minflt + majflt == 0)
1420             continue;
1421
1422         if(unlikely(debug)) {
1423             log_date(stderr);
1424             fprintf(stderr, "Absorb %s (%d %s total resources: utime=%llu stime=%llu gtime=%llu minflt=%llu majflt=%llu)\n"
1425                 , p->comm
1426                 , p->pid
1427                 , p->updated?"running":"exited"
1428                 , utime
1429                 , stime
1430                 , gtime
1431                 , minflt
1432                 , majflt
1433                 );
1434             print_process_tree(p, "Searching parents");
1435         }
1436
1437         for(pp = p->parent; pp ; pp = pp->parent) {
1438             if(!pp->updated) continue;
1439
1440             unsigned long long absorbed;
1441             absorbed = remove_exited_child_from_parent(&utime,  &pp->cutime);
1442             if(unlikely(debug && absorbed))
1443                 fprintf(stderr, " > process %s (%d %s) absorbed %llu utime (remaining: %llu)\n", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, utime);
1444
1445             absorbed = remove_exited_child_from_parent(&stime,  &pp->cstime);
1446             if(unlikely(debug && absorbed))
1447                 fprintf(stderr, " > process %s (%d %s) absorbed %llu stime (remaining: %llu)\n", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, stime);
1448
1449             absorbed = remove_exited_child_from_parent(&gtime,  &pp->cgtime);
1450             if(unlikely(debug && absorbed))
1451                 fprintf(stderr, " > process %s (%d %s) absorbed %llu gtime (remaining: %llu)\n", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, gtime);
1452
1453             absorbed = remove_exited_child_from_parent(&minflt, &pp->cminflt);
1454             if(unlikely(debug && absorbed))
1455                 fprintf(stderr, " > process %s (%d %s) absorbed %llu minflt (remaining: %llu)\n", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, minflt);
1456
1457             absorbed = remove_exited_child_from_parent(&majflt, &pp->cmajflt);
1458             if(unlikely(debug && absorbed))
1459                 fprintf(stderr, " > process %s (%d %s) absorbed %llu majflt (remaining: %llu)\n", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, majflt);
1460         }
1461
1462         if(unlikely(utime + stime + gtime + minflt + majflt > 0)) {
1463             if(unlikely(debug)) {
1464                 if(utime)  find_lost_child_debug(p, utime,  3);
1465                 if(stime)  find_lost_child_debug(p, stime,  4);
1466                 if(gtime)  find_lost_child_debug(p, gtime,  5);
1467                 if(minflt) find_lost_child_debug(p, minflt, 1);
1468                 if(majflt) find_lost_child_debug(p, majflt, 2);
1469             }
1470
1471             p->keep = 1;
1472
1473             if(unlikely(debug))
1474                 fprintf(stderr, " > remaining resources - KEEP - for another loop: %s (%d %s total resources: utime=%llu stime=%llu gtime=%llu minflt=%llu majflt=%llu)\n"
1475                     , p->comm
1476                     , p->pid
1477                     , p->updated?"running":"exited"
1478                     , utime
1479                     , stime
1480                     , gtime
1481                     , minflt
1482                     , majflt
1483                     );
1484
1485             for(pp = p->parent; pp ; pp = pp->parent) {
1486                 if(pp->updated) break;
1487                 pp->keep = 1;
1488
1489                 if(unlikely(debug))
1490                     fprintf(stderr, " > - KEEP - parent for another loop: %s (%d %s)\n"
1491                         , pp->comm
1492                         , pp->pid
1493                         , pp->updated?"running":"exited"
1494                         );
1495             }
1496
1497             p->utime_raw   = utime  * (p->stat_collected_usec - p->last_stat_collected_usec) / (1000000ULL * RATES_DETAIL);
1498             p->stime_raw   = stime  * (p->stat_collected_usec - p->last_stat_collected_usec) / (1000000ULL * RATES_DETAIL);
1499             p->gtime_raw   = gtime  * (p->stat_collected_usec - p->last_stat_collected_usec) / (1000000ULL * RATES_DETAIL);
1500             p->minflt_raw  = minflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (1000000ULL * RATES_DETAIL);
1501             p->majflt_raw  = majflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (1000000ULL * RATES_DETAIL);
1502             p->cutime_raw = p->cstime_raw = p->cgtime_raw = p->cminflt_raw = p->cmajflt_raw = 0;
1503
1504             if(unlikely(debug))
1505                 fprintf(stderr, "\n");
1506         }
1507         else if(unlikely(debug)) {
1508             fprintf(stderr, " > totally absorbed - DONE - %s (%d %s)\n"
1509                 , p->comm
1510                 , p->pid
1511                 , p->updated?"running":"exited"
1512                 );
1513         }
1514     }
1515 }
1516
1517 void link_all_processes_to_their_parents(void) {
1518     struct pid_stat *p, *pp;
1519
1520     // link all children to their parents
1521     // and update children count on parents
1522     for(p = root_of_pids; p ; p = p->next) {
1523         // for each process found
1524
1525         p->sortlist = 0;
1526         p->parent = NULL;
1527
1528         if(unlikely(!p->ppid)) {
1529             p->parent = NULL;
1530             continue;
1531         }
1532
1533         pp = all_pids[p->ppid];
1534         if(likely(pp)) {
1535             p->parent = pp;
1536             pp->children_count++;
1537
1538             if(unlikely(debug || (p->target && p->target->debug)))
1539                 fprintf(stderr, "apps.plugin: \tchild %d (%s, %s) on target '%s' has parent %d (%s, %s). Parent: utime=%llu, stime=%llu, gtime=%llu, minflt=%llu, majflt=%llu, cutime=%llu, cstime=%llu, cgtime=%llu, cminflt=%llu, cmajflt=%llu\n", p->pid, p->comm, p->updated?"running":"exited", (p->target)?p->target->name:"UNSET", pp->pid, pp->comm, pp->updated?"running":"exited", pp->utime, pp->stime, pp->gtime, pp->minflt, pp->majflt, pp->cutime, pp->cstime, pp->cgtime, pp->cminflt, pp->cmajflt);
1540         }
1541         else {
1542             p->parent = NULL;
1543             error("pid %d %s states parent %d, but the later does not exist.", p->pid, p->comm, p->ppid);
1544         }
1545     }
1546 }
1547
1548 // ----------------------------------------------------------------------------
1549
1550 // 1. read all files in /proc
1551 // 2. for each numeric directory:
1552 //    i.   read /proc/pid/stat
1553 //    ii.  read /proc/pid/statm
1554 //    iii. read /proc/pid/io (requires root access)
1555 //    iii. read the entries in directory /proc/pid/fd (requires root access)
1556 //         for each entry:
1557 //         a. find or create a struct file_descriptor
1558 //         b. cleanup any old/unused file_descriptors
1559
1560 // after all these, some pids may be linked to targets, while others may not
1561
1562 // in case of errors, only 1 every 1000 errors is printed
1563 // to avoid filling up all disk space
1564 // if debug is enabled, all errors are printed
1565
1566 static int compar_pid(const void *pid1, const void *pid2) {
1567
1568     struct pid_stat *p1 = all_pids[*((pid_t *)pid1)];
1569     struct pid_stat *p2 = all_pids[*((pid_t *)pid2)];
1570
1571     if(p1->sortlist > p2->sortlist)
1572         return -1;
1573     else
1574         return 1;
1575 }
1576
1577 static inline int managed_log(struct pid_stat *p, uint32_t log, int status) {
1578     if(unlikely(!status)) {
1579         // error("command failed log %u, errno %d", log, errno);
1580
1581         if(unlikely(debug || errno != ENOENT)) {
1582             if(unlikely(debug || !(p->log_thrown & log))) {
1583                 p->log_thrown |= log;
1584                 switch(log) {
1585                     case PID_LOG_IO:
1586                         error("Cannot process %s/proc/%d/io (command '%s')", host_prefix, p->pid, p->comm);
1587                         break;
1588
1589                     case PID_LOG_STATM:
1590                         error("Cannot process %s/proc/%d/statm (command '%s')", host_prefix, p->pid, p->comm);
1591                         break;
1592
1593                     case PID_LOG_CMDLINE:
1594                         error("Cannot process %s/proc/%d/cmdline (command '%s')", host_prefix, p->pid, p->comm);
1595                         break;
1596
1597                     case PID_LOG_FDS:
1598                         error("Cannot process entries in %s/proc/%d/fd (command '%s')", host_prefix, p->pid, p->comm);
1599                         break;
1600
1601                     case PID_LOG_STAT:
1602                         break;
1603
1604                     default:
1605                         error("unhandled error for pid %d, command '%s'", p->pid, p->comm);
1606                         break;
1607                 }
1608             }
1609         }
1610         errno = 0;
1611     }
1612     else if(unlikely(p->log_thrown & log)) {
1613         // error("unsetting log %u on pid %d", log, p->pid);
1614         p->log_thrown &= ~log;
1615     }
1616
1617     return status;
1618 }
1619
1620 void collect_data_for_pid(pid_t pid) {
1621     if(unlikely(pid <= 0 || pid > pid_max)) {
1622         error("Invalid pid %d read (expected 1 to %d). Ignoring process.", pid, pid_max);
1623         return;
1624     }
1625
1626     struct pid_stat *p = get_pid_entry(pid);
1627     if(unlikely(!p || p->read)) return;
1628     p->read             = 1;
1629
1630     // fprintf(stderr, "Reading process %d (%s), sortlist %d\n", p->pid, p->comm, p->sortlist);
1631
1632     // --------------------------------------------------------------------
1633     // /proc/<pid>/stat
1634
1635     if(unlikely(!managed_log(p, PID_LOG_STAT, read_proc_pid_stat(p))))
1636         // there is no reason to proceed if we cannot get its status
1637         return;
1638
1639     read_proc_pid_ownership(p);
1640
1641     // check its parent pid
1642     if(unlikely(p->ppid < 0 || p->ppid > pid_max)) {
1643         error("Pid %d (command '%s') states invalid parent pid %d. Using 0.", pid, p->comm, p->ppid);
1644         p->ppid = 0;
1645     }
1646
1647     // --------------------------------------------------------------------
1648     // /proc/<pid>/io
1649
1650     managed_log(p, PID_LOG_IO, read_proc_pid_io(p));
1651
1652     // --------------------------------------------------------------------
1653     // /proc/<pid>/statm
1654
1655     if(unlikely(!managed_log(p, PID_LOG_STATM, read_proc_pid_statm(p))))
1656         // there is no reason to proceed if we cannot get its memory status
1657         return;
1658
1659     // --------------------------------------------------------------------
1660     // link it
1661
1662     // check if it is target
1663     // we do this only once, the first time this pid is loaded
1664     if(unlikely(p->new_entry)) {
1665         // /proc/<pid>/cmdline
1666         if(likely(proc_pid_cmdline_is_needed))
1667             managed_log(p, PID_LOG_CMDLINE, read_proc_pid_cmdline(p));
1668
1669         if(unlikely(debug))
1670             fprintf(stderr, "apps.plugin: \tJust added %d (%s)\n", pid, p->comm);
1671
1672         uint32_t hash = simple_hash(p->comm);
1673         size_t pclen  = strlen(p->comm);
1674
1675         struct target *w;
1676         for(w = apps_groups_root_target; w ; w = w->next) {
1677             // if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \t\tcomparing '%s' with '%s'\n", w->compare, p->comm);
1678
1679             // find it - 4 cases:
1680             // 1. the target is not a pattern
1681             // 2. the target has the prefix
1682             // 3. the target has the suffix
1683             // 4. the target is something inside cmdline
1684             if( (!w->starts_with && !w->ends_with && w->comparehash == hash && !strcmp(w->compare, p->comm))
1685                    || (w->starts_with && !w->ends_with && !strncmp(w->compare, p->comm, w->comparelen))
1686                    || (!w->starts_with && w->ends_with && pclen >= w->comparelen && !strcmp(w->compare, &p->comm[pclen - w->comparelen]))
1687                    || (proc_pid_cmdline_is_needed && w->starts_with && w->ends_with && strstr(p->cmdline, w->compare))
1688                     ) {
1689                 if(w->target) p->target = w->target;
1690                 else p->target = w;
1691
1692                 if(debug || (p->target && p->target->debug))
1693                     fprintf(stderr, "apps.plugin: \t\t%s linked to target %s\n", p->comm, p->target->name);
1694
1695                 break;
1696             }
1697         }
1698     }
1699
1700     // --------------------------------------------------------------------
1701     // /proc/<pid>/fd
1702
1703     if(enable_file_charts)
1704             managed_log(p, PID_LOG_FDS, read_pid_file_descriptors(p));
1705
1706     // --------------------------------------------------------------------
1707     // done!
1708
1709     if(unlikely(debug && include_exited_childs && all_pids_count && p->ppid && all_pids[p->ppid] && !all_pids[p->ppid]->read))
1710         fprintf(stderr, "Read process %d (%s) sortlisted %d, but its parent %d (%s) sortlisted %d, is not read\n", p->pid, p->comm, p->sortlist, all_pids[p->ppid]->pid, all_pids[p->ppid]->comm, all_pids[p->ppid]->sortlist);
1711
1712     // mark it as updated
1713     p->updated = 1;
1714     p->keep = 0;
1715     p->keeploops = 0;
1716 }
1717
1718 int collect_data_for_all_processes_from_proc(void) {
1719     struct pid_stat *p = NULL;
1720
1721     if(all_pids_count) {
1722         // read parents before childs
1723         // this is needed to prevent a situation where
1724         // a child is found running, but until we read
1725         // its parent, it has exited and its parent
1726         // has accumulated its resources
1727
1728         long slc = 0;
1729         for(p = root_of_pids; p ; p = p->next) {
1730             p->read             = 0;
1731             p->updated          = 0;
1732             p->new_entry        = 0;
1733             p->merged           = 0;
1734             p->children_count   = 0;
1735             p->parent           = NULL;
1736
1737             all_pids_sortlist[slc++] = p->pid;
1738         }
1739
1740         if(unlikely(slc != all_pids_count)) {
1741             error("Internal error: I was thinking I had %ld processes in my arrays, but it seems there are more.", all_pids_count);
1742             all_pids_count = slc;
1743         }
1744
1745         if(include_exited_childs) {
1746             qsort((void *)all_pids_sortlist, all_pids_count, sizeof(pid_t), compar_pid);
1747             for(slc = 0; slc < all_pids_count; slc++)
1748                 collect_data_for_pid(all_pids_sortlist[slc]);
1749         }
1750     }
1751
1752     char dirname[FILENAME_MAX + 1];
1753
1754     snprintfz(dirname, FILENAME_MAX, "%s/proc", host_prefix);
1755     DIR *dir = opendir(dirname);
1756     if(!dir) return 0;
1757
1758     struct dirent *file = NULL;
1759
1760     while((file = readdir(dir))) {
1761         char *endptr = file->d_name;
1762         pid_t pid = (pid_t) strtoul(file->d_name, &endptr, 10);
1763
1764         // make sure we read a valid number
1765         if(unlikely(endptr == file->d_name || *endptr != '\0'))
1766             continue;
1767
1768         collect_data_for_pid(pid);
1769     }
1770     closedir(dir);
1771
1772     // normally this is done
1773     // however we may have processes exited while we collected values
1774     // so let's find the exited ones
1775     // we do this by collecting the ownership of process
1776     // if we manage to get the ownership, the process still runs
1777
1778     read_proc_stat();
1779     link_all_processes_to_their_parents();
1780     process_exited_processes();
1781
1782     return 1;
1783 }
1784
1785 // ----------------------------------------------------------------------------
1786 // update statistics on the targets
1787
1788 // 1. link all childs to their parents
1789 // 2. go from bottom to top, marking as merged all childs to their parents
1790 //    this step links all parents without a target to the child target, if any
1791 // 3. link all top level processes (the ones not merged) to the default target
1792 // 4. go from top to bottom, linking all childs without a target, to their parent target
1793 //    after this step, all processes have a target
1794 // [5. for each killed pid (updated = 0), remove its usage from its target]
1795 // 6. zero all apps_groups_targets
1796 // 7. concentrate all values on the apps_groups_targets
1797 // 8. remove all killed processes
1798 // 9. find the unique file count for each target
1799 // check: update_apps_groups_statistics()
1800
1801 void cleanup_exited_pids(void) {
1802     int c;
1803     struct pid_stat *p = NULL;
1804
1805     for(p = root_of_pids; p ;) {
1806         if(!p->updated && (!p->keep || p->keeploops > 0)) {
1807 //          fprintf(stderr, "\tEXITED %d %s [parent %d %s, target %s] utime=%llu, stime=%llu, gtime=%llu, cutime=%llu, cstime=%llu, cgtime=%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->gtime, p->cutime, p->cstime, p->cgtime, p->minflt, p->majflt, p->cminflt, p->cmajflt);
1808
1809             if(unlikely(debug && (p->keep || p->keeploops)))
1810                 fprintf(stderr, " > CLEANUP cannot keep exited process %d (%s) anymore - removing it.\n", p->pid, p->comm);
1811
1812             for(c = 0 ; c < p->fds_size ; c++) if(p->fds[c] > 0) {
1813                 file_descriptor_not_used(p->fds[c]);
1814                 p->fds[c] = 0;
1815             }
1816
1817             pid_t r = p->pid;
1818             p = p->next;
1819             del_pid_entry(r);
1820         }
1821         else {
1822             if(unlikely(p->keep)) p->keeploops++;
1823             p->keep = 0;
1824             p = p->next;
1825         }
1826     }
1827 }
1828
1829 void apply_apps_groups_targets_inheritance(void) {
1830     struct pid_stat *p = NULL;
1831
1832     // children that do not have a target
1833     // inherit their target from their parent
1834     int found = 1, loops = 0;
1835     while(found) {
1836         if(unlikely(debug)) loops++;
1837         found = 0;
1838         for(p = root_of_pids; p ; p = p->next) {
1839             // if this process does not have a target
1840             // and it has a parent
1841             // and its parent has a target
1842             // then, set the parent's target to this process
1843             if(unlikely(!p->target && p->parent && p->parent->target)) {
1844                 p->target = p->parent->target;
1845                 found++;
1846
1847                 if(debug || (p->target && p->target->debug))
1848                     fprintf(stderr, "apps.plugin: \t\tTARGET INHERITANCE: %s is inherited by %d (%s) from its parent %d (%s).\n", p->target->name, p->pid, p->comm, p->parent->pid, p->parent->comm);
1849             }
1850         }
1851     }
1852
1853     // find all the procs with 0 childs and merge them to their parents
1854     // repeat, until nothing more can be done.
1855     int sortlist = 1;
1856     found = 1;
1857     while(found) {
1858         if(unlikely(debug)) loops++;
1859         found = 0;
1860
1861         for(p = root_of_pids; p ; p = p->next) {
1862             if(unlikely(!p->sortlist && !p->children_count))
1863                 p->sortlist = sortlist++;
1864
1865             // if this process does not have any children
1866             // and is not already merged
1867             // and has a parent
1868             // and its parent has children
1869             // and the target of this process and its parent is the same, or the parent does not have a target
1870             // and its parent is not init
1871             // then, mark them as merged.
1872             if(unlikely(
1873                     !p->children_count
1874                     && !p->merged
1875                     && p->parent
1876                     && p->parent->children_count
1877                     && (p->target == p->parent->target || !p->parent->target)
1878                     && p->ppid != 1
1879                 )) {
1880                 p->parent->children_count--;
1881                 p->merged = 1;
1882
1883                 // the parent inherits the child's target, if it does not have a target itself
1884                 if(unlikely(p->target && !p->parent->target)) {
1885                     p->parent->target = p->target;
1886
1887                     if(debug || (p->target && p->target->debug))
1888                         fprintf(stderr, "apps.plugin: \t\tTARGET INHERITANCE: %s is inherited by %d (%s) from its child %d (%s).\n", p->target->name, p->parent->pid, p->parent->comm, p->pid, p->comm);
1889                 }
1890
1891                 found++;
1892             }
1893         }
1894
1895         if(unlikely(debug))
1896             fprintf(stderr, "apps.plugin: TARGET INHERITANCE: merged %d processes\n", found);
1897     }
1898
1899     // init goes always to default target
1900     if(all_pids[1])
1901         all_pids[1]->target = apps_groups_default_target;
1902
1903     // give a default target on all top level processes
1904     if(unlikely(debug)) loops++;
1905     for(p = root_of_pids; p ; p = p->next) {
1906         // if the process is not merged itself
1907         // then is is a top level process
1908         if(unlikely(!p->merged && !p->target))
1909             p->target = apps_groups_default_target;
1910
1911         // make sure all processes have a sortlist
1912         if(unlikely(!p->sortlist))
1913             p->sortlist = sortlist++;
1914     }
1915
1916     if(all_pids[1])
1917         all_pids[1]->sortlist = sortlist++;
1918
1919     // give a target to all merged child processes
1920     found = 1;
1921     while(found) {
1922         if(unlikely(debug)) loops++;
1923         found = 0;
1924         for(p = root_of_pids; p ; p = p->next) {
1925             if(unlikely(!p->target && p->merged && p->parent && p->parent->target)) {
1926                 p->target = p->parent->target;
1927                 found++;
1928
1929                 if(debug || (p->target && p->target->debug))
1930                     fprintf(stderr, "apps.plugin: \t\tTARGET INHERITANCE: %s is inherited by %d (%s) from its parent %d (%s) at phase 2.\n", p->target->name, p->pid, p->comm, p->parent->pid, p->parent->comm);
1931             }
1932         }
1933     }
1934
1935     if(unlikely(debug))
1936         fprintf(stderr, "apps.plugin: apply_apps_groups_targets_inheritance() made %d loops on the process tree\n", loops);
1937 }
1938
1939 long zero_all_targets(struct target *root) {
1940     struct target *w;
1941     long count = 0;
1942
1943     for (w = root; w ; w = w->next) {
1944         count++;
1945
1946         if(w->fds) freez(w->fds);
1947         w->fds = NULL;
1948
1949         w->minflt = 0;
1950         w->majflt = 0;
1951         w->utime = 0;
1952         w->stime = 0;
1953         w->gtime = 0;
1954         w->cminflt = 0;
1955         w->cmajflt = 0;
1956         w->cutime = 0;
1957         w->cstime = 0;
1958         w->cgtime = 0;
1959         w->num_threads = 0;
1960         w->rss = 0;
1961         w->processes = 0;
1962
1963         w->statm_size = 0;
1964         w->statm_resident = 0;
1965         w->statm_share = 0;
1966         w->statm_text = 0;
1967         w->statm_lib = 0;
1968         w->statm_data = 0;
1969         w->statm_dirty = 0;
1970
1971         w->io_logical_bytes_read = 0;
1972         w->io_logical_bytes_written = 0;
1973         w->io_read_calls = 0;
1974         w->io_write_calls = 0;
1975         w->io_storage_bytes_read = 0;
1976         w->io_storage_bytes_written = 0;
1977         w->io_cancelled_write_bytes = 0;
1978     }
1979
1980     return count;
1981 }
1982
1983 void aggregate_pid_on_target(struct target *w, struct pid_stat *p, struct target *o) {
1984     (void)o;
1985
1986     if(unlikely(!w->fds))
1987         w->fds = callocz(sizeof(int), (size_t) all_files_size);
1988
1989     if(likely(p->updated)) {
1990         w->cutime  += p->cutime;
1991         w->cstime  += p->cstime;
1992         w->cgtime  += p->cgtime;
1993         w->cminflt += p->cminflt;
1994         w->cmajflt += p->cmajflt;
1995
1996         w->utime  += p->utime;
1997         w->stime  += p->stime;
1998         w->gtime  += p->gtime;
1999         w->minflt += p->minflt;
2000         w->majflt += p->majflt;
2001
2002         w->rss += p->rss;
2003
2004         w->statm_size += p->statm_size;
2005         w->statm_resident += p->statm_resident;
2006         w->statm_share += p->statm_share;
2007         w->statm_text += p->statm_text;
2008         w->statm_lib += p->statm_lib;
2009         w->statm_data += p->statm_data;
2010         w->statm_dirty += p->statm_dirty;
2011
2012         w->io_logical_bytes_read    += p->io_logical_bytes_read;
2013         w->io_logical_bytes_written += p->io_logical_bytes_written;
2014         w->io_read_calls            += p->io_read_calls;
2015         w->io_write_calls           += p->io_write_calls;
2016         w->io_storage_bytes_read    += p->io_storage_bytes_read;
2017         w->io_storage_bytes_written += p->io_storage_bytes_written;
2018         w->io_cancelled_write_bytes += p->io_cancelled_write_bytes;
2019
2020         w->processes++;
2021         w->num_threads += p->num_threads;
2022
2023         if(likely(w->fds)) {
2024             int c;
2025             for(c = 0; c < p->fds_size ;c++) {
2026                 if(p->fds[c] == 0) continue;
2027
2028                 if(likely(p->fds[c] < all_files_size)) {
2029                     if(w->fds) w->fds[p->fds[c]]++;
2030                 }
2031                 else
2032                     error("Invalid fd number %d", p->fds[c]);
2033             }
2034         }
2035
2036         if(unlikely(debug || w->debug))
2037             fprintf(stderr, "apps.plugin: \taggregating '%s' pid %d on target '%s' utime=%llu, stime=%llu, gtime=%llu, cutime=%llu, cstime=%llu, cgtime=%llu, minflt=%llu, majflt=%llu, cminflt=%llu, cmajflt=%llu\n", p->comm, p->pid, w->name, p->utime, p->stime, p->gtime, p->cutime, p->cstime, p->cgtime, p->minflt, p->majflt, p->cminflt, p->cmajflt);
2038     }
2039 }
2040
2041 void count_targets_fds(struct target *root) {
2042     int c;
2043     struct target *w;
2044
2045     for (w = root; w ; w = w->next) {
2046         if(!w->fds) continue;
2047
2048         w->openfiles = 0;
2049         w->openpipes = 0;
2050         w->opensockets = 0;
2051         w->openinotifies = 0;
2052         w->openeventfds = 0;
2053         w->opentimerfds = 0;
2054         w->opensignalfds = 0;
2055         w->openeventpolls = 0;
2056         w->openother = 0;
2057
2058         for(c = 1; c < all_files_size ;c++) {
2059             if(w->fds[c] > 0)
2060                 switch(all_files[c].type) {
2061                 case FILETYPE_FILE:
2062                     w->openfiles++;
2063                     break;
2064
2065                 case FILETYPE_PIPE:
2066                     w->openpipes++;
2067                     break;
2068
2069                 case FILETYPE_SOCKET:
2070                     w->opensockets++;
2071                     break;
2072
2073                 case FILETYPE_INOTIFY:
2074                     w->openinotifies++;
2075                     break;
2076
2077                 case FILETYPE_EVENTFD:
2078                     w->openeventfds++;
2079                     break;
2080
2081                 case FILETYPE_TIMERFD:
2082                     w->opentimerfds++;
2083                     break;
2084
2085                 case FILETYPE_SIGNALFD:
2086                     w->opensignalfds++;
2087                     break;
2088
2089                 case FILETYPE_EVENTPOLL:
2090                     w->openeventpolls++;
2091                     break;
2092
2093                 default:
2094                     w->openother++;
2095             }
2096         }
2097
2098         freez(w->fds);
2099         w->fds = NULL;
2100     }
2101 }
2102
2103 void calculate_netdata_statistics(void) {
2104     apply_apps_groups_targets_inheritance();
2105
2106     zero_all_targets(users_root_target);
2107     zero_all_targets(groups_root_target);
2108     apps_groups_targets = zero_all_targets(apps_groups_root_target);
2109
2110     // this has to be done, before the cleanup
2111     struct pid_stat *p = NULL;
2112     struct target *w = NULL, *o = NULL;
2113
2114     // concentrate everything on the apps_groups_targets
2115     for(p = root_of_pids; p ; p = p->next) {
2116
2117         // --------------------------------------------------------------------
2118         // apps_groups targets
2119         if(likely(p->target))
2120             aggregate_pid_on_target(p->target, p, NULL);
2121         else
2122             error("pid %d %s was left without a target!", p->pid, p->comm);
2123
2124
2125         // --------------------------------------------------------------------
2126         // user targets
2127         o = p->user_target;
2128         if(likely(p->user_target && p->user_target->uid == p->uid))
2129             w = p->user_target;
2130         else {
2131             if(unlikely(debug && p->user_target))
2132                     fprintf(stderr, "apps.plugin: \t\tpid %d (%s) switched user from %u (%s) to %u.\n", p->pid, p->comm, p->user_target->uid, p->user_target->name, p->uid);
2133
2134             w = p->user_target = get_users_target(p->uid);
2135         }
2136
2137         if(likely(w))
2138             aggregate_pid_on_target(w, p, o);
2139         else
2140             error("pid %d %s was left without a user target!", p->pid, p->comm);
2141
2142
2143         // --------------------------------------------------------------------
2144         // group targets
2145         o = p->group_target;
2146         if(likely(p->group_target && p->group_target->gid == p->gid))
2147             w = p->group_target;
2148         else {
2149             if(unlikely(debug && p->group_target))
2150                     fprintf(stderr, "apps.plugin: \t\tpid %d (%s) switched group from %u (%s) to %u.\n", p->pid, p->comm, p->group_target->gid, p->group_target->name, p->gid);
2151
2152             w = p->group_target = get_groups_target(p->gid);
2153         }
2154
2155         if(likely(w))
2156             aggregate_pid_on_target(w, p, o);
2157         else
2158             error("pid %d %s was left without a group target!", p->pid, p->comm);
2159
2160     }
2161
2162     count_targets_fds(apps_groups_root_target);
2163     count_targets_fds(users_root_target);
2164     count_targets_fds(groups_root_target);
2165
2166     cleanup_exited_pids();
2167 }
2168
2169 // ----------------------------------------------------------------------------
2170 // update chart dimensions
2171
2172 BUFFER *output = NULL;
2173 int print_calculated_number(char *str, calculated_number value) { (void)str; (void)value; return 0; }
2174
2175 static inline void send_BEGIN(const char *type, const char *id, unsigned long long usec) {
2176     // fprintf(stdout, "BEGIN %s.%s %llu\n", type, id, usec);
2177     buffer_strcat(output, "BEGIN ");
2178     buffer_strcat(output, type);
2179     buffer_strcat(output, ".");
2180     buffer_strcat(output, id);
2181     buffer_strcat(output, " ");
2182     buffer_print_llu(output, usec);
2183     buffer_strcat(output, "\n");
2184 }
2185
2186 static inline void send_SET(const char *name, unsigned long long value) {
2187     // fprintf(stdout, "SET %s = %llu\n", name, value);
2188     buffer_strcat(output, "SET ");
2189     buffer_strcat(output, name);
2190     buffer_strcat(output, " = ");
2191     buffer_print_llu(output, value);
2192     buffer_strcat(output, "\n");
2193 }
2194
2195 static inline void send_END(void) {
2196     // fprintf(stdout, "END\n");
2197     buffer_strcat(output, "END\n");
2198 }
2199
2200 double utime_fix_ratio = 1.0, stime_fix_ratio = 1.0, gtime_fix_ratio = 1.0, cutime_fix_ratio = 1.0, cstime_fix_ratio = 1.0, cgtime_fix_ratio = 1.0;
2201 double minflt_fix_ratio = 1.0, majflt_fix_ratio = 1.0, cminflt_fix_ratio = 1.0, cmajflt_fix_ratio = 1.0;
2202
2203 unsigned long long send_resource_usage_to_netdata() {
2204     static struct timeval last = { 0, 0 };
2205     static struct rusage me_last;
2206
2207     struct timeval now;
2208     struct rusage me;
2209
2210     unsigned long long usec;
2211     unsigned long long cpuuser;
2212     unsigned long long cpusyst;
2213
2214     if(!last.tv_sec) {
2215         gettimeofday(&last, NULL);
2216         getrusage(RUSAGE_SELF, &me_last);
2217
2218         // the first time, give a zero to allow
2219         // netdata calibrate to the current time
2220         // usec = update_every * 1000000ULL;
2221         usec = 0ULL;
2222         cpuuser = 0;
2223         cpusyst = 0;
2224     }
2225     else {
2226         gettimeofday(&now, NULL);
2227         getrusage(RUSAGE_SELF, &me);
2228
2229         usec = usec_dt(&now, &last);
2230         cpuuser = me.ru_utime.tv_sec * 1000000ULL + me.ru_utime.tv_usec;
2231         cpusyst = me.ru_stime.tv_sec * 1000000ULL + me.ru_stime.tv_usec;
2232
2233         bcopy(&now, &last, sizeof(struct timeval));
2234         bcopy(&me, &me_last, sizeof(struct rusage));
2235     }
2236
2237     buffer_sprintf(output,
2238         "BEGIN netdata.apps_cpu %llu\n"
2239         "SET user = %llu\n"
2240         "SET system = %llu\n"
2241         "END\n"
2242         "BEGIN netdata.apps_files %llu\n"
2243         "SET files = %llu\n"
2244         "SET pids = %ld\n"
2245         "SET fds = %d\n"
2246         "SET targets = %ld\n"
2247         "END\n"
2248         "BEGIN netdata.apps_fix %llu\n"
2249         "SET utime = %llu\n"
2250         "SET stime = %llu\n"
2251         "SET gtime = %llu\n"
2252         "SET minflt = %llu\n"
2253         "SET majflt = %llu\n"
2254         "END\n"
2255         , usec
2256         , cpuuser
2257         , cpusyst
2258         , usec
2259         , file_counter
2260         , all_pids_count
2261         , all_files_len
2262         , apps_groups_targets
2263         , usec
2264         , (unsigned long long)(utime_fix_ratio   * 100 * RATES_DETAIL)
2265         , (unsigned long long)(stime_fix_ratio   * 100 * RATES_DETAIL)
2266         , (unsigned long long)(gtime_fix_ratio   * 100 * RATES_DETAIL)
2267         , (unsigned long long)(minflt_fix_ratio  * 100 * RATES_DETAIL)
2268         , (unsigned long long)(majflt_fix_ratio  * 100 * RATES_DETAIL)
2269         );
2270
2271     if(include_exited_childs)
2272         buffer_sprintf(output,
2273             "BEGIN netdata.apps_children_fix %llu\n"
2274             "SET cutime = %llu\n"
2275             "SET cstime = %llu\n"
2276             "SET cgtime = %llu\n"
2277             "SET cminflt = %llu\n"
2278             "SET cmajflt = %llu\n"
2279             "END\n"
2280             , usec
2281             , (unsigned long long)(cutime_fix_ratio  * 100 * RATES_DETAIL)
2282             , (unsigned long long)(cstime_fix_ratio  * 100 * RATES_DETAIL)
2283             , (unsigned long long)(cgtime_fix_ratio  * 100 * RATES_DETAIL)
2284             , (unsigned long long)(cminflt_fix_ratio * 100 * RATES_DETAIL)
2285             , (unsigned long long)(cmajflt_fix_ratio * 100 * RATES_DETAIL)
2286             );
2287
2288     return usec;
2289 }
2290
2291 void normalize_data(struct target *root) {
2292     struct target *w;
2293
2294     // childs processing introduces spikes
2295     // here we try to eliminate them by disabling childs processing either for specific dimensions
2296     // or entirely. Of course, either way, we disable it just a single iteration.
2297
2298     unsigned long long max = processors * hz * RATES_DETAIL;
2299     unsigned long long utime = 0, cutime = 0, stime = 0, cstime = 0, gtime = 0, cgtime = 0, minflt = 0, cminflt = 0, majflt = 0, cmajflt = 0;
2300
2301     if(global_utime > max) global_utime = max;
2302     if(global_stime > max) global_stime = max;
2303     if(global_gtime > max) global_gtime = max;
2304
2305     for(w = root; w ; w = w->next) {
2306         if(w->target || (!w->processes && !w->exposed)) continue;
2307
2308         utime   += w->utime;
2309         stime   += w->stime;
2310         gtime   += w->gtime;
2311         cutime  += w->cutime;
2312         cstime  += w->cstime;
2313         cgtime  += w->cgtime;
2314
2315         minflt  += w->minflt;
2316         majflt  += w->majflt;
2317         cminflt += w->cminflt;
2318         cmajflt += w->cmajflt;
2319     }
2320
2321     if((global_utime || global_stime || global_gtime) && (utime || stime || gtime)) {
2322         if(global_utime + global_stime + global_gtime > utime + cutime + stime + cstime + gtime + cgtime) {
2323             // everything we collected fits
2324             utime_fix_ratio  =
2325             stime_fix_ratio  =
2326             gtime_fix_ratio  =
2327             cutime_fix_ratio =
2328             cstime_fix_ratio =
2329             cgtime_fix_ratio = 1.0; //(double)(global_utime + global_stime) / (double)(utime + cutime + stime + cstime);
2330         }
2331         else if(global_utime + global_stime > utime + stime) {
2332             // childrens resources are too high
2333             // lower only the children resources
2334             utime_fix_ratio  =
2335             stime_fix_ratio  =
2336             gtime_fix_ratio  = 1.0;
2337             cutime_fix_ratio =
2338             cstime_fix_ratio =
2339             cgtime_fix_ratio = (double)((global_utime + global_stime) - (utime + stime)) / (double)(cutime + cstime);
2340         }
2341         else {
2342             // even running processes are unrealistic
2343             // zero the children resources
2344             // lower the running processes resources
2345             utime_fix_ratio  =
2346             stime_fix_ratio  =
2347             gtime_fix_ratio  = (double)(global_utime + global_stime) / (double)(utime + stime);
2348             cutime_fix_ratio =
2349             cstime_fix_ratio =
2350             cgtime_fix_ratio = 0.0;
2351         }
2352     }
2353     else {
2354         utime_fix_ratio  =
2355         stime_fix_ratio  =
2356         gtime_fix_ratio  =
2357         cutime_fix_ratio =
2358         cstime_fix_ratio =
2359         cgtime_fix_ratio = 0.0;
2360     }
2361
2362     if(utime_fix_ratio  > 1.0) utime_fix_ratio  = 1.0;
2363     if(cutime_fix_ratio > 1.0) cutime_fix_ratio = 1.0;
2364     if(stime_fix_ratio  > 1.0) stime_fix_ratio  = 1.0;
2365     if(cstime_fix_ratio > 1.0) cstime_fix_ratio = 1.0;
2366     if(gtime_fix_ratio  > 1.0) gtime_fix_ratio  = 1.0;
2367     if(cgtime_fix_ratio > 1.0) cgtime_fix_ratio = 1.0;
2368
2369     // if(utime_fix_ratio  < 0.0) utime_fix_ratio  = 0.0;
2370     // if(cutime_fix_ratio < 0.0) cutime_fix_ratio = 0.0;
2371     // if(stime_fix_ratio  < 0.0) stime_fix_ratio  = 0.0;
2372     // if(cstime_fix_ratio < 0.0) cstime_fix_ratio = 0.0;
2373     // if(gtime_fix_ratio  < 0.0) gtime_fix_ratio  = 0.0;
2374     // if(cgtime_fix_ratio < 0.0) cgtime_fix_ratio = 0.0;
2375
2376     // FIXME
2377     // we use cpu time to normalize page faults
2378     // the problem is that to find the proper max values
2379     // for page faults we have to parse /proc/vmstat
2380     // which is quite big to do it again (netdata does it already)
2381     //
2382     // a better solution could be to somehow have netdata
2383     // do this normalization for us
2384
2385     if(utime || stime || gtime)
2386         majflt_fix_ratio =
2387         minflt_fix_ratio = (double)(utime * utime_fix_ratio + stime * stime_fix_ratio + gtime * gtime_fix_ratio) / (double)(utime + stime + gtime);
2388     else
2389         minflt_fix_ratio =
2390         majflt_fix_ratio = 1.0;
2391
2392     if(cutime || cstime || cgtime)
2393         cmajflt_fix_ratio =
2394         cminflt_fix_ratio = (double)(cutime * cutime_fix_ratio + cstime * cstime_fix_ratio + cgtime * cgtime_fix_ratio) / (double)(cutime + cstime + cgtime);
2395     else
2396         cminflt_fix_ratio =
2397         cmajflt_fix_ratio = 1.0;
2398
2399     // the report
2400
2401     if(unlikely(debug)) {
2402         fprintf(stderr,
2403             "SYSTEM: u=%llu s=%llu g=%llu "
2404             "COLLECTED: u=%llu s=%llu g=%llu cu=%llu cs=%llu cg=%llu "
2405             "DELTA: u=%lld s=%lld g=%lld "
2406             "FIX: u=%0.2f s=%0.2f g=%0.2f cu=%0.2f cs=%0.2f cg=%0.2f "
2407             "FINALLY: u=%llu s=%llu g=%llu cu=%llu cs=%llu cg=%llu "
2408             "\n"
2409             , global_utime
2410             , global_stime
2411             , global_gtime
2412             , utime
2413             , stime
2414             , gtime
2415             , cutime
2416             , cstime
2417             , cgtime
2418             , (long long)utime + (long long)cutime - (long long)global_utime
2419             , (long long)stime + (long long)cstime - (long long)global_stime
2420             , (long long)gtime + (long long)cgtime - (long long)global_gtime
2421             , utime_fix_ratio
2422             , stime_fix_ratio
2423             , gtime_fix_ratio
2424             , cutime_fix_ratio
2425             , cstime_fix_ratio
2426             , cgtime_fix_ratio
2427             , (unsigned long long)(utime * utime_fix_ratio)
2428             , (unsigned long long)(stime * stime_fix_ratio)
2429             , (unsigned long long)(gtime * gtime_fix_ratio)
2430             , (unsigned long long)(cutime * cutime_fix_ratio)
2431             , (unsigned long long)(cstime * cstime_fix_ratio)
2432             , (unsigned long long)(cgtime * cgtime_fix_ratio)
2433             );
2434     }
2435 }
2436
2437 void send_collected_data_to_netdata(struct target *root, const char *type, unsigned long long usec) {
2438     struct target *w;
2439
2440     send_BEGIN(type, "cpu", usec);
2441     for (w = root; w ; w = w->next) {
2442         if(unlikely(w->exposed))
2443             send_SET(w->name, (unsigned long long)(w->utime * utime_fix_ratio) + (unsigned long long)(w->stime * stime_fix_ratio) + (unsigned long long)(w->gtime * gtime_fix_ratio) + (include_exited_childs?((unsigned long long)(w->cutime * cutime_fix_ratio) + (unsigned long long)(w->cstime * cstime_fix_ratio) + (unsigned long long)(w->cgtime * cgtime_fix_ratio)):0ULL));
2444     }
2445     send_END();
2446
2447     send_BEGIN(type, "cpu_user", usec);
2448     for (w = root; w ; w = w->next) {
2449         if(unlikely(w->exposed))
2450             send_SET(w->name, (unsigned long long)(w->utime * utime_fix_ratio) + (include_exited_childs?((unsigned long long)(w->cutime * cutime_fix_ratio)):0ULL));
2451     }
2452     send_END();
2453
2454     send_BEGIN(type, "cpu_system", usec);
2455     for (w = root; w ; w = w->next) {
2456         if(unlikely(w->exposed))
2457             send_SET(w->name, (unsigned long long)(w->stime * stime_fix_ratio) + (include_exited_childs?((unsigned long long)(w->cstime * cstime_fix_ratio)):0ULL));
2458     }
2459     send_END();
2460
2461     if(show_guest_time) {
2462         send_BEGIN(type, "cpu_guest", usec);
2463         for (w = root; w ; w = w->next) {
2464             if(unlikely(w->exposed))
2465                 send_SET(w->name, (unsigned long long)(w->gtime * gtime_fix_ratio) + (include_exited_childs?((unsigned long long)(w->cgtime * cgtime_fix_ratio)):0ULL));
2466         }
2467         send_END();
2468     }
2469
2470     send_BEGIN(type, "threads", usec);
2471     for (w = root; w ; w = w->next) {
2472         if(unlikely(w->exposed))
2473             send_SET(w->name, w->num_threads);
2474     }
2475     send_END();
2476
2477     send_BEGIN(type, "processes", usec);
2478     for (w = root; w ; w = w->next) {
2479         if(unlikely(w->exposed))
2480             send_SET(w->name, w->processes);
2481     }
2482     send_END();
2483
2484     send_BEGIN(type, "mem", usec);
2485     for (w = root; w ; w = w->next) {
2486         if(unlikely(w->exposed))
2487             send_SET(w->name, (w->statm_resident > w->statm_share)?(w->statm_resident - w->statm_share):0ULL);
2488     }
2489     send_END();
2490
2491     send_BEGIN(type, "minor_faults", usec);
2492     for (w = root; w ; w = w->next) {
2493         if(unlikely(w->exposed))
2494             send_SET(w->name, (unsigned long long)(w->minflt * minflt_fix_ratio) + (include_exited_childs?((unsigned long long)(w->cminflt * cminflt_fix_ratio)):0ULL));
2495     }
2496     send_END();
2497
2498     send_BEGIN(type, "major_faults", usec);
2499     for (w = root; w ; w = w->next) {
2500         if(unlikely(w->exposed))
2501             send_SET(w->name, (unsigned long long)(w->majflt * majflt_fix_ratio) + (include_exited_childs?((unsigned long long)(w->cmajflt * cmajflt_fix_ratio)):0ULL));
2502     }
2503     send_END();
2504
2505     send_BEGIN(type, "lreads", usec);
2506     for (w = root; w ; w = w->next) {
2507         if(unlikely(w->exposed))
2508             send_SET(w->name, w->io_logical_bytes_read);
2509     }
2510     send_END();
2511
2512     send_BEGIN(type, "lwrites", usec);
2513     for (w = root; w ; w = w->next) {
2514         if(unlikely(w->exposed))
2515             send_SET(w->name, w->io_logical_bytes_written);
2516     }
2517     send_END();
2518
2519     send_BEGIN(type, "preads", usec);
2520     for (w = root; w ; w = w->next) {
2521         if(unlikely(w->exposed))
2522             send_SET(w->name, w->io_storage_bytes_read);
2523     }
2524     send_END();
2525
2526     send_BEGIN(type, "pwrites", usec);
2527     for (w = root; w ; w = w->next) {
2528         if(unlikely(w->exposed))
2529             send_SET(w->name, w->io_storage_bytes_written);
2530     }
2531     send_END();
2532
2533     if(enable_file_charts) {
2534         send_BEGIN(type, "files", usec);
2535         for (w = root; w; w = w->next) {
2536             if (unlikely(w->exposed))
2537                 send_SET(w->name, w->openfiles);
2538         }
2539         send_END();
2540
2541         send_BEGIN(type, "sockets", usec);
2542         for (w = root; w; w = w->next) {
2543             if (unlikely(w->exposed))
2544                 send_SET(w->name, w->opensockets);
2545         }
2546         send_END();
2547
2548         send_BEGIN(type, "pipes", usec);
2549         for (w = root; w; w = w->next) {
2550             if (unlikely(w->exposed))
2551                 send_SET(w->name, w->openpipes);
2552         }
2553         send_END();
2554     }
2555 }
2556
2557
2558 // ----------------------------------------------------------------------------
2559 // generate the charts
2560
2561 void send_charts_updates_to_netdata(struct target *root, const char *type, const char *title)
2562 {
2563     struct target *w;
2564     int newly_added = 0;
2565
2566     for(w = root ; w ; w = w->next) {
2567         if (w->target) continue;
2568
2569         if (!w->exposed && w->processes) {
2570             newly_added++;
2571             w->exposed = 1;
2572             if (debug || w->debug) fprintf(stderr, "apps.plugin: %s just added - regenerating charts.\n", w->name);
2573         }
2574     }
2575
2576     // nothing more to show
2577     if(!newly_added && show_guest_time == show_guest_time_old) return;
2578
2579     // we have something new to show
2580     // update the charts
2581     buffer_sprintf(output, "CHART %s.cpu '' '%s CPU Time (%d%% = %d core%s)' 'cpu time %%' cpu %s.cpu stacked 20001 %d\n", type, title, (processors * 100), processors, (processors>1)?"s":"", type, update_every);
2582     for (w = root; w ; w = w->next) {
2583         if(unlikely(w->exposed))
2584             buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu %s\n", w->name, hz * RATES_DETAIL / 100, w->hidden ? "hidden" : "");
2585     }
2586
2587     buffer_sprintf(output, "CHART %s.mem '' '%s Dedicated Memory (w/o shared)' 'MB' mem %s.mem stacked 20003 %d\n", type, title, type, update_every);
2588     for (w = root; w ; w = w->next) {
2589         if(unlikely(w->exposed))
2590             buffer_sprintf(output, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
2591     }
2592
2593     buffer_sprintf(output, "CHART %s.threads '' '%s Threads' 'threads' processes %s.threads stacked 20005 %d\n", type, title, type, update_every);
2594     for (w = root; w ; w = w->next) {
2595         if(unlikely(w->exposed))
2596             buffer_sprintf(output, "DIMENSION %s '' absolute 1 1\n", w->name);
2597     }
2598
2599     buffer_sprintf(output, "CHART %s.processes '' '%s Processes' 'processes' processes %s.processes stacked 20004 %d\n", type, title, type, update_every);
2600     for (w = root; w ; w = w->next) {
2601         if(unlikely(w->exposed))
2602             buffer_sprintf(output, "DIMENSION %s '' absolute 1 1\n", w->name);
2603     }
2604
2605     buffer_sprintf(output, "CHART %s.cpu_user '' '%s CPU User Time (%d%% = %d core%s)' 'cpu time %%' cpu %s.cpu_user stacked 20020 %d\n", type, title, (processors * 100), processors, (processors>1)?"s":"", type, update_every);
2606     for (w = root; w ; w = w->next) {
2607         if(unlikely(w->exposed))
2608             buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
2609     }
2610
2611     buffer_sprintf(output, "CHART %s.cpu_system '' '%s CPU System Time (%d%% = %d core%s)' 'cpu time %%' cpu %s.cpu_system stacked 20021 %d\n", type, title, (processors * 100), processors, (processors>1)?"s":"", type, update_every);
2612     for (w = root; w ; w = w->next) {
2613         if(unlikely(w->exposed))
2614             buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
2615     }
2616
2617     if(show_guest_time) {
2618         buffer_sprintf(output, "CHART %s.cpu_guest '' '%s CPU Guest Time (%d%% = %d core%s)' 'cpu time %%' cpu %s.cpu_system stacked 20022 %d\n", type, title, (processors * 100), processors, (processors > 1) ? "s" : "", type, update_every);
2619         for (w = root; w; w = w->next) {
2620             if(unlikely(w->exposed))
2621                 buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
2622         }
2623     }
2624
2625     buffer_sprintf(output, "CHART %s.major_faults '' '%s Major Page Faults (swap read)' 'page faults/s' swap %s.major_faults stacked 20010 %d\n", type, title, type, update_every);
2626     for (w = root; w ; w = w->next) {
2627         if(unlikely(w->exposed))
2628             buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
2629     }
2630
2631     buffer_sprintf(output, "CHART %s.minor_faults '' '%s Minor Page Faults' 'page faults/s' mem %s.minor_faults stacked 20011 %d\n", type, title, type, update_every);
2632     for (w = root; w ; w = w->next) {
2633         if(unlikely(w->exposed))
2634             buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
2635     }
2636
2637     buffer_sprintf(output, "CHART %s.lreads '' '%s Disk Logical Reads' 'kilobytes/s' disk %s.lreads stacked 20042 %d\n", type, title, type, update_every);
2638     for (w = root; w ; w = w->next) {
2639         if(unlikely(w->exposed))
2640             buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
2641     }
2642
2643     buffer_sprintf(output, "CHART %s.lwrites '' '%s I/O Logical Writes' 'kilobytes/s' disk %s.lwrites stacked 20042 %d\n", type, title, type, update_every);
2644     for (w = root; w ; w = w->next) {
2645         if(unlikely(w->exposed))
2646             buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
2647     }
2648
2649     buffer_sprintf(output, "CHART %s.preads '' '%s Disk Reads' 'kilobytes/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
2650     for (w = root; w ; w = w->next) {
2651         if(unlikely(w->exposed))
2652             buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
2653     }
2654
2655     buffer_sprintf(output, "CHART %s.pwrites '' '%s Disk Writes' 'kilobytes/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
2656     for (w = root; w ; w = w->next) {
2657         if(unlikely(w->exposed))
2658             buffer_sprintf(output, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
2659     }
2660
2661     if(enable_file_charts) {
2662         buffer_sprintf(output, "CHART %s.files '' '%s Open Files' 'open files' disk %s.files stacked 20050 %d\n", type,
2663                        title, type, update_every);
2664         for (w = root; w; w = w->next) {
2665             if (unlikely(w->exposed))
2666                 buffer_sprintf(output, "DIMENSION %s '' absolute 1 1\n", w->name);
2667         }
2668
2669         buffer_sprintf(output, "CHART %s.sockets '' '%s Open Sockets' 'open sockets' net %s.sockets stacked 20051 %d\n",
2670                        type, title, type, update_every);
2671         for (w = root; w; w = w->next) {
2672             if (unlikely(w->exposed))
2673                 buffer_sprintf(output, "DIMENSION %s '' absolute 1 1\n", w->name);
2674         }
2675
2676         buffer_sprintf(output, "CHART %s.pipes '' '%s Pipes' 'open pipes' processes %s.pipes stacked 20053 %d\n", type,
2677                        title, type, update_every);
2678         for (w = root; w; w = w->next) {
2679             if (unlikely(w->exposed))
2680                 buffer_sprintf(output, "DIMENSION %s '' absolute 1 1\n", w->name);
2681         }
2682     }
2683 }
2684
2685
2686 // ----------------------------------------------------------------------------
2687 // parse command line arguments
2688
2689 void parse_args(int argc, char **argv)
2690 {
2691     int i, freq = 0;
2692     char *name = NULL;
2693
2694     for(i = 1; i < argc; i++) {
2695         if(!freq) {
2696             int n = atoi(argv[i]);
2697             if(n > 0) {
2698                 freq = n;
2699                 continue;
2700             }
2701         }
2702
2703         if(strcmp("debug", argv[i]) == 0) {
2704             debug = 1;
2705             // debug_flags = 0xffffffff;
2706             continue;
2707         }
2708
2709         if(strcmp("no-childs", argv[i]) == 0 || strcmp("without-childs", argv[i]) == 0) {
2710             include_exited_childs = 0;
2711             continue;
2712         }
2713
2714         if(strcmp("with-childs", argv[i]) == 0) {
2715             include_exited_childs = 1;
2716             continue;
2717         }
2718
2719         if(strcmp("with-guest", argv[i]) == 0) {
2720             enable_guest_charts = 1;
2721             continue;
2722         }
2723
2724         if(strcmp("no-guest", argv[i]) == 0 || strcmp("without-guest", argv[i]) == 0) {
2725             enable_guest_charts = 0;
2726             continue;
2727         }
2728
2729         if(strcmp("with-files", argv[i]) == 0) {
2730             enable_file_charts = 1;
2731             continue;
2732         }
2733
2734         if(strcmp("no-files", argv[i]) == 0 || strcmp("without-files", argv[i]) == 0) {
2735             enable_file_charts = 0;
2736             continue;
2737         }
2738
2739         if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0) {
2740             fprintf(stderr,
2741                     "apps.plugin\n"
2742                     "(C) 2016 Costa Tsaousis"
2743                     "GPL v3+\n"
2744                     "This program is a data collector plugin for netdata.\n"
2745                     "\n"
2746                     "Valid command line options:\n"
2747                     "\n"
2748                     "SECONDS           set the data collection frequency\n"
2749                     "\n"
2750                     "debug             enable debugging (lot of output)\n"
2751                     "\n"
2752                     "with-childs\n"
2753                     "without-childs    enable / disable aggregating exited\n"
2754                     "                  children resources into parents\n"
2755                     "                  (default is enabled)\n"
2756                     "\n"
2757                     "with-guest\n"
2758                     "without-guest     enable / disable reporting guest charts\n"
2759                     "                  (default is disabled)\n"
2760                     "\n"
2761                     "with-files\n"
2762                     "without-files     enable / disable reporting files, sockets, pipes\n"
2763                     "                  (default is enabled)\n"
2764                     "\n"
2765                     "NAME              read apps_NAME.conf instead of\n"
2766                     "                  apps_groups.conf\n"
2767                     "                  (default NAME=groups)\n"
2768             );
2769             exit(1);
2770         }
2771
2772         if(!name) {
2773             name = argv[i];
2774             continue;
2775         }
2776
2777         error("Cannot understand option %s", argv[i]);
2778         exit(1);
2779     }
2780
2781     if(freq > 0) update_every = freq;
2782     if(!name) name = "groups";
2783
2784     if(read_apps_groups_conf(name)) {
2785         error("Cannot read process groups %s", name);
2786         exit(1);
2787     }
2788 }
2789
2790 int main(int argc, char **argv)
2791 {
2792     // debug_flags = D_PROCFILE;
2793
2794     // set the name for logging
2795     program_name = "apps.plugin";
2796
2797     info("started on pid %d", getpid());
2798
2799     // disable syslog for apps.plugin
2800     error_log_syslog = 0;
2801
2802     // set errors flood protection to 100 logs per hour
2803     error_log_errors_per_period = 100;
2804     error_log_throttle_period = 3600;
2805
2806     host_prefix = getenv("NETDATA_HOST_PREFIX");
2807     if(host_prefix == NULL) {
2808         // info("NETDATA_HOST_PREFIX is not passed from netdata");
2809         host_prefix = "";
2810     }
2811     // else info("Found NETDATA_HOST_PREFIX='%s'", host_prefix);
2812
2813     config_dir = getenv("NETDATA_CONFIG_DIR");
2814     if(config_dir == NULL) {
2815         // info("NETDATA_CONFIG_DIR is not passed from netdata");
2816         config_dir = CONFIG_DIR;
2817     }
2818     // else info("Found NETDATA_CONFIG_DIR='%s'", config_dir);
2819
2820 #ifdef NETDATA_INTERNAL_CHECKS
2821     if(debug_flags != 0) {
2822         struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
2823         if(setrlimit(RLIMIT_CORE, &rl) != 0)
2824             info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
2825         prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
2826     }
2827 #endif /* NETDATA_INTERNAL_CHECKS */
2828
2829     procfile_adaptive_initial_allocation = 1;
2830
2831     time_t started_t = time(NULL);
2832     time_t current_t;
2833     get_HZ();
2834     pid_max = get_system_pid_max();
2835     processors = get_system_cpus();
2836
2837     parse_args(argc, argv);
2838
2839     all_pids_sortlist = callocz(sizeof(pid_t), (size_t)pid_max);
2840     all_pids = callocz(sizeof(struct pid_stat *), (size_t) pid_max);
2841
2842     output = buffer_create(1024);
2843     buffer_sprintf(output,
2844         "CHART netdata.apps_cpu '' 'Apps Plugin CPU' 'milliseconds/s' apps.plugin netdata.apps_cpu stacked 140000 %1$d\n"
2845         "DIMENSION user '' incremental 1 1000\n"
2846         "DIMENSION system '' incremental 1 1000\n"
2847         "CHART netdata.apps_files '' 'Apps Plugin Files' 'files/s' apps.plugin netdata.apps_files line 140001 %1$d\n"
2848         "DIMENSION files '' incremental 1 1\n"
2849         "DIMENSION pids '' absolute 1 1\n"
2850         "DIMENSION fds '' absolute 1 1\n"
2851         "DIMENSION targets '' absolute 1 1\n"
2852         "CHART netdata.apps_fix '' 'Apps Plugin Normalization Ratios' 'percentage' apps.plugin netdata.apps_fix line 140002 %1$d\n"
2853         "DIMENSION utime '' absolute 1 %2$llu\n"
2854         "DIMENSION stime '' absolute 1 %2$llu\n"
2855         "DIMENSION gtime '' absolute 1 %2$llu\n"
2856         "DIMENSION minflt '' absolute 1 %2$llu\n"
2857         "DIMENSION majflt '' absolute 1 %2$llu\n"
2858         , update_every
2859         , RATES_DETAIL
2860         );
2861
2862     if(include_exited_childs)
2863         buffer_sprintf(output,
2864             "CHART netdata.apps_children_fix '' 'Apps Plugin Exited Children Normalization Ratios' 'percentage' apps.plugin netdata.apps_children_fix line 140003 %1$d\n"
2865             "DIMENSION cutime '' absolute 1 %2$llu\n"
2866             "DIMENSION cstime '' absolute 1 %2$llu\n"
2867             "DIMENSION cgtime '' absolute 1 %2$llu\n"
2868             "DIMENSION cminflt '' absolute 1 %2$llu\n"
2869             "DIMENSION cmajflt '' absolute 1 %2$llu\n"
2870             , update_every
2871             , RATES_DETAIL
2872             );
2873
2874 #ifndef PROFILING_MODE
2875     unsigned long long sunext = (time(NULL) - (time(NULL) % update_every) + update_every) * 1000000ULL;
2876     unsigned long long sunow;
2877 #endif /* PROFILING_MODE */
2878
2879     global_iterations_counter = 1;
2880     for(;1; global_iterations_counter++) {
2881 #ifndef PROFILING_MODE
2882         // delay until it is our time to run
2883         while((sunow = time_usec()) < sunext)
2884             sleep_usec(sunext - sunow);
2885
2886         // find the next time we need to run
2887         while(time_usec() > sunext)
2888             sunext += update_every * 1000000ULL;
2889 #endif /* PROFILING_MODE */
2890
2891         if(!collect_data_for_all_processes_from_proc()) {
2892             error("Cannot collect /proc data for running processes. Disabling apps.plugin...");
2893             printf("DISABLE\n");
2894             exit(1);
2895         }
2896
2897         calculate_netdata_statistics();
2898         normalize_data(apps_groups_root_target);
2899
2900         unsigned long long dt = send_resource_usage_to_netdata();
2901
2902         // this is smart enough to show only newly added apps, when needed
2903         send_charts_updates_to_netdata(apps_groups_root_target, "apps", "Apps");
2904         send_charts_updates_to_netdata(users_root_target, "users", "Users");
2905         send_charts_updates_to_netdata(groups_root_target, "groups", "User Groups");
2906
2907         send_collected_data_to_netdata(apps_groups_root_target, "apps", dt);
2908         send_collected_data_to_netdata(users_root_target, "users", dt);
2909         send_collected_data_to_netdata(groups_root_target, "groups", dt);
2910
2911         show_guest_time_old = show_guest_time;
2912
2913         //if(puts(buffer_tostring(output)) == EOF)
2914         if(write(STDOUT_FILENO, buffer_tostring(output), buffer_strlen(output)) == -1)
2915             fatal("Cannot send chart values to netdata.");
2916
2917         // fflush(stdout);
2918         buffer_flush(output);
2919
2920         if(unlikely(debug))
2921             fprintf(stderr, "apps.plugin: done Loop No %llu\n", global_iterations_counter);
2922
2923         current_t = time(NULL);
2924
2925 #ifndef PROFILING_MODE
2926         // restart check (14400 seconds)
2927         if(current_t - started_t > 14400) exit(0);
2928 #else
2929         if(current_t - started_t > 10) exit(0);
2930 #endif /* PROFILING_MODE */
2931     }
2932 }