4 * (C) Copyright 2016-2017 Costa Tsaousis <costa@tsaousis.gr>
5 * Released under GPL v3+
10 // ----------------------------------------------------------------------------
11 // per O/S configuration
13 // the minimum PID of the system
14 // this is also the pid of the init process
17 // if the way apps.plugin will work, will read the entire process list,
18 // including the resource utilization of each process, instantly
20 // when set to 0, apps.plugin builds a sort list of processes, in order
21 // to process children processes, before parent processes
22 #define ALL_PIDS_ARE_READ_INSTANTLY 0
25 // ----------------------------------------------------------------------------
28 #define MAX_COMPARE_NAME 100
30 #define MAX_CMDLINE 1024
33 // ----------------------------------------------------------------------------
34 // the rates we are going to send to netdata will have this detail a value of:
35 // - 1 will send just integer parts to netdata
36 // - 100 will send 2 decimal points
37 // - 1000 will send 3 decimal points
39 #define RATES_DETAIL 10000ULL
42 // ----------------------------------------------------------------------------
43 // to avoid reallocating too frequently, we can increase the number of spare
44 // file descriptors used by processes.
46 // having a lot of spares, increases the CPU utilization of the plugin.
47 #define MAX_SPARE_FDS 1
50 // ----------------------------------------------------------------------------
51 // command line options
56 enable_guest_charts = 0,
57 enable_file_charts = 1,
58 enable_users_charts = 1,
59 enable_groups_charts = 1,
60 include_exited_childs = 1;
63 // will be changed to getenv(NETDATA_CONFIG_DIR) if it exists
64 static char *config_dir = CONFIG_DIR;
66 // ----------------------------------------------------------------------------
68 // handled in code (automatically set)
71 show_guest_time = 0, // 1 when guest values are collected
72 show_guest_time_old = 0,
73 proc_pid_cmdline_is_needed = 0; // 1 when we need to read /proc/cmdline
76 // ----------------------------------------------------------------------------
80 global_iterations_counter = 1,
85 // ----------------------------------------------------------------------------
88 // With normalization we lower the collected metrics by a factor to make them
89 // match the total utilization of the system.
90 // The discrepancy exists because apps.plugin needs some time to collect all
91 // the metrics. This results in utilization that exceeds the total utilization
94 // With normalization we align the per-process utilization, to the total of
95 // the system. We first consume the exited children utilization and it the
96 // collected values is above the total, we proportionally scale each reported
99 // the total system time, as reported by /proc/stat
106 // the normalization ratios, as calculated by normalize_utilization()
107 double utime_fix_ratio = 1.0,
108 stime_fix_ratio = 1.0,
109 gtime_fix_ratio = 1.0,
110 minflt_fix_ratio = 1.0,
111 majflt_fix_ratio = 1.0,
112 cutime_fix_ratio = 1.0,
113 cstime_fix_ratio = 1.0,
114 cgtime_fix_ratio = 1.0,
115 cminflt_fix_ratio = 1.0,
116 cmajflt_fix_ratio = 1.0;
119 // ----------------------------------------------------------------------------
122 // target is the structure that processes are aggregated to be reported
125 // - Each entry in /etc/apps_groups.conf creates a target.
126 // - Each user and group used by a process in the system, creates a target.
129 char compare[MAX_COMPARE_NAME + 1];
130 uint32_t comparehash;
133 char id[MAX_NAME + 1];
136 char name[MAX_NAME + 1];
141 kernel_uint_t minflt;
142 kernel_uint_t cminflt;
143 kernel_uint_t majflt;
144 kernel_uint_t cmajflt;
148 kernel_uint_t cutime;
149 kernel_uint_t cstime;
150 kernel_uint_t cgtime;
151 kernel_uint_t num_threads;
152 // kernel_uint_t rss;
154 kernel_uint_t statm_size;
155 kernel_uint_t statm_resident;
156 kernel_uint_t statm_share;
157 // kernel_uint_t statm_text;
158 // kernel_uint_t statm_lib;
159 // kernel_uint_t statm_data;
160 // kernel_uint_t statm_dirty;
162 kernel_uint_t io_logical_bytes_read;
163 kernel_uint_t io_logical_bytes_written;
164 // kernel_uint_t io_read_calls;
165 // kernel_uint_t io_write_calls;
166 kernel_uint_t io_storage_bytes_read;
167 kernel_uint_t io_storage_bytes_written;
168 // kernel_uint_t io_cancelled_write_bytes;
173 kernel_uint_t openfiles;
174 kernel_uint_t openpipes;
175 kernel_uint_t opensockets;
176 kernel_uint_t openinotifies;
177 kernel_uint_t openeventfds;
178 kernel_uint_t opentimerfds;
179 kernel_uint_t opensignalfds;
180 kernel_uint_t openeventpolls;
181 kernel_uint_t openother;
183 unsigned int processes; // how many processes have been merged to this
184 int exposed; // if set, we have sent this to netdata
185 int hidden; // if set, we set the hidden flag on the dimension
188 int starts_with; // if set, the compare string matches only the
189 // beginning of the command
191 struct target *target; // the one that will be reported to netdata
196 *apps_groups_default_target = NULL, // the default target
197 *apps_groups_root_target = NULL, // apps_groups.conf defined
198 *users_root_target = NULL, // users
199 *groups_root_target = NULL; // user groups
202 apps_groups_targets_count = 0; // # of apps_groups.conf targets
205 // ----------------------------------------------------------------------------
208 // structure to store data for each process running
209 // see: man proc for the description of the fields
213 char comm[MAX_COMPARE_NAME + 1];
214 char cmdline[MAX_CMDLINE + 1];
226 // these are raw values collected
227 kernel_uint_t minflt_raw;
228 kernel_uint_t cminflt_raw;
229 kernel_uint_t majflt_raw;
230 kernel_uint_t cmajflt_raw;
231 kernel_uint_t utime_raw;
232 kernel_uint_t stime_raw;
233 kernel_uint_t gtime_raw; // guest_time
234 kernel_uint_t cutime_raw;
235 kernel_uint_t cstime_raw;
236 kernel_uint_t cgtime_raw; // cguest_time
239 kernel_uint_t minflt;
240 kernel_uint_t cminflt;
241 kernel_uint_t majflt;
242 kernel_uint_t cmajflt;
246 kernel_uint_t cutime;
247 kernel_uint_t cstime;
248 kernel_uint_t cgtime;
253 // int64_t itrealvalue;
254 // kernel_uint_t starttime;
255 // kernel_uint_t vsize;
256 // kernel_uint_t rss;
257 // kernel_uint_t rsslim;
258 // kernel_uint_t starcode;
259 // kernel_uint_t endcode;
260 // kernel_uint_t startstack;
261 // kernel_uint_t kstkesp;
262 // kernel_uint_t kstkeip;
265 // uint64_t sigignore;
266 // uint64_t sigcatch;
270 // int32_t exit_signal;
271 // int32_t processor;
272 // uint32_t rt_priority;
274 // kernel_uint_t delayacct_blkio_ticks;
279 kernel_uint_t statm_size;
280 kernel_uint_t statm_resident;
281 kernel_uint_t statm_share;
282 // kernel_uint_t statm_text;
283 // kernel_uint_t statm_lib;
284 // kernel_uint_t statm_data;
285 // kernel_uint_t statm_dirty;
287 kernel_uint_t io_logical_bytes_read_raw;
288 kernel_uint_t io_logical_bytes_written_raw;
289 // kernel_uint_t io_read_calls_raw;
290 // kernel_uint_t io_write_calls_raw;
291 kernel_uint_t io_storage_bytes_read_raw;
292 kernel_uint_t io_storage_bytes_written_raw;
293 // kernel_uint_t io_cancelled_write_bytes_raw;
295 kernel_uint_t io_logical_bytes_read;
296 kernel_uint_t io_logical_bytes_written;
297 // kernel_uint_t io_read_calls;
298 // kernel_uint_t io_write_calls;
299 kernel_uint_t io_storage_bytes_read;
300 kernel_uint_t io_storage_bytes_written;
301 // kernel_uint_t io_cancelled_write_bytes;
303 int *fds; // array of fds it uses
304 int fds_size; // the size of the fds array
306 int children_count; // number of processes directly referencing this
307 char keep:1; // 1 when we need to keep this process in memory even after it exited
308 int keeploops; // increases by 1 every time keep is 1 and updated 0
309 char updated:1; // 1 when the process is currently running
310 char merged:1; // 1 when it has been merged to its parent
311 char read:1; // 1 when we have already read this process for this iteration
313 int sortlist; // higher numbers = top on the process tree
314 // each process gets a unique number
316 struct target *target; // app_groups.conf targets
317 struct target *user_target; // uid based targets
318 struct target *group_target; // gid based targets
320 usec_t stat_collected_usec;
321 usec_t last_stat_collected_usec;
323 usec_t io_collected_usec;
324 usec_t last_io_collected_usec;
326 char *fds_dirname; // the full directory name in /proc/PID/fd
329 char *statm_filename;
331 char *cmdline_filename;
333 struct pid_stat *parent;
334 struct pid_stat *prev;
335 struct pid_stat *next;
338 // log each problem once per process
339 // log flood protection flags (log_thrown)
340 #define PID_LOG_IO 0x00000001
341 #define PID_LOG_STATM 0x00000002
342 #define PID_LOG_CMDLINE 0x00000004
343 #define PID_LOG_FDS 0x00000008
344 #define PID_LOG_STAT 0x00000010
346 static struct pid_stat
347 *root_of_pids = NULL, // global list of all processes running
348 **all_pids = NULL; // to avoid allocations, we pre-allocate the
349 // the entire pid space.
352 all_pids_count = 0; // the number of processes running
354 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
355 // Another pre-allocated list of all possible pids.
356 // We need it to pids and assign them a unique sortlist id, so that we
357 // read parents before children. This is needed to prevent a situation where
358 // a child is found running, but until we read its parent, it has exited and
359 // its parent has accumulated its resources.
361 *all_pids_sortlist = NULL;
364 // ----------------------------------------------------------------------------
367 // this is used to keep a global list of all open files of the system.
368 // it is needed in order to calculate the unique files processes have open.
370 #define FILE_DESCRIPTORS_INCREASE_STEP 100
372 // types for struct file_descriptor->type
373 typedef enum fd_filetype {
385 struct file_descriptor {
388 #ifdef NETDATA_INTERNAL_CHECKS
390 #endif /* NETDATA_INTERNAL_CHECKS */
404 // ----------------------------------------------------------------------------
405 // callback required by fatal()
407 void netdata_cleanup_and_exit(int ret) {
411 // ----------------------------------------------------------------------------
413 // aggregate all processes in groups, to have a limited number of dimensions
415 static struct target *get_users_target(uid_t uid) {
417 for(w = users_root_target ; w ; w = w->next)
418 if(w->uid == uid) return w;
420 w = callocz(sizeof(struct target), 1);
421 snprintfz(w->compare, MAX_COMPARE_NAME, "%u", uid);
422 w->comparehash = simple_hash(w->compare);
423 w->comparelen = strlen(w->compare);
425 snprintfz(w->id, MAX_NAME, "%u", uid);
426 w->idhash = simple_hash(w->id);
428 struct passwd *pw = getpwuid(uid);
430 snprintfz(w->name, MAX_NAME, "%u", uid);
432 snprintfz(w->name, MAX_NAME, "%s", pw->pw_name);
434 netdata_fix_chart_name(w->name);
438 w->next = users_root_target;
439 users_root_target = w;
442 fprintf(stderr, "apps.plugin: added uid %u ('%s') target\n", w->uid, w->name);
447 struct target *get_groups_target(gid_t gid)
450 for(w = groups_root_target ; w ; w = w->next)
451 if(w->gid == gid) return w;
453 w = callocz(sizeof(struct target), 1);
454 snprintfz(w->compare, MAX_COMPARE_NAME, "%u", gid);
455 w->comparehash = simple_hash(w->compare);
456 w->comparelen = strlen(w->compare);
458 snprintfz(w->id, MAX_NAME, "%u", gid);
459 w->idhash = simple_hash(w->id);
461 struct group *gr = getgrgid(gid);
463 snprintfz(w->name, MAX_NAME, "%u", gid);
465 snprintfz(w->name, MAX_NAME, "%s", gr->gr_name);
467 netdata_fix_chart_name(w->name);
471 w->next = groups_root_target;
472 groups_root_target = w;
475 fprintf(stderr, "apps.plugin: added gid %u ('%s') target\n", w->gid, w->name);
480 // find or create a new target
481 // there are targets that are just aggregated to other target (the second argument)
482 static struct target *get_apps_groups_target(const char *id, struct target *target, const char *name) {
483 int tdebug = 0, thidden = target?target->hidden:0, ends_with = 0;
484 const char *nid = id;
486 // extract the options
487 while(nid[0] == '-' || nid[0] == '+' || nid[0] == '*') {
488 if(nid[0] == '-') thidden = 1;
489 if(nid[0] == '+') tdebug = 1;
490 if(nid[0] == '*') ends_with = 1;
493 uint32_t hash = simple_hash(id);
495 // find if it already exists
496 struct target *w, *last = apps_groups_root_target;
497 for(w = apps_groups_root_target ; w ; w = w->next) {
498 if(w->idhash == hash && strncmp(nid, w->id, MAX_NAME) == 0)
504 // find an existing target
505 if(unlikely(!target)) {
506 while(*name == '-') {
507 if(*name == '-') thidden = 1;
511 for(target = apps_groups_root_target ; target != NULL ; target = target->next) {
512 if(!target->target && strcmp(name, target->name) == 0)
516 if(unlikely(debug)) {
518 fprintf(stderr, "apps.plugin: REUSING TARGET NAME '%s' on ID '%s'\n", target->name, target->id);
520 fprintf(stderr, "apps.plugin: NEW TARGET NAME '%s' on ID '%s'\n", name, id);
524 if(target && target->target)
525 fatal("Internal Error: request to link process '%s' to target '%s' which is linked to target '%s'", id, target->id, target->target->id);
527 w = callocz(sizeof(struct target), 1);
528 strncpyz(w->id, nid, MAX_NAME);
529 w->idhash = simple_hash(w->id);
531 if(unlikely(!target))
533 strncpyz(w->name, name, MAX_NAME);
536 strncpyz(w->name, nid, MAX_NAME);
538 strncpyz(w->compare, nid, MAX_COMPARE_NAME);
539 size_t len = strlen(w->compare);
540 if(w->compare[len - 1] == '*') {
541 w->compare[len - 1] = '\0';
544 w->ends_with = ends_with;
546 if(w->starts_with && w->ends_with)
547 proc_pid_cmdline_is_needed = 1;
549 w->comparehash = simple_hash(w->compare);
550 w->comparelen = strlen(w->compare);
556 // append it, to maintain the order in apps_groups.conf
557 if(last) last->next = w;
558 else apps_groups_root_target = w;
561 fprintf(stderr, "apps.plugin: ADDING TARGET ID '%s', process name '%s' (%s), aggregated on target '%s', options: %s %s\n"
563 , w->compare, (w->starts_with && w->ends_with)?"substring":((w->starts_with)?"prefix":((w->ends_with)?"suffix":"exact"))
564 , w->target?w->target->name:w->name
565 , (w->hidden)?"hidden":"-"
566 , (w->debug)?"debug":"-"
572 // read the apps_groups.conf file
573 static int read_apps_groups_conf(const char *file)
575 char filename[FILENAME_MAX + 1];
577 snprintfz(filename, FILENAME_MAX, "%s/apps_%s.conf", config_dir, file);
580 fprintf(stderr, "apps.plugin: process groups file: '%s'\n", filename);
582 // ----------------------------------------
584 procfile *ff = procfile_open(filename, " :\t", PROCFILE_FLAG_DEFAULT);
587 procfile_set_quotes(ff, "'\"");
589 ff = procfile_readall(ff);
593 size_t line, lines = procfile_lines(ff);
595 for(line = 0; line < lines ;line++) {
596 size_t word, words = procfile_linewords(ff, line);
599 char *name = procfile_lineword(ff, line, 0);
600 if(!name || !*name) continue;
602 // find a possibly existing target
603 struct target *w = NULL;
605 // loop through all words, skipping the first one (the name)
606 for(word = 0; word < words ;word++) {
607 char *s = procfile_lineword(ff, line, word);
608 if(!s || !*s) continue;
611 // is this the first word? skip it
612 if(s == name) continue;
615 struct target *n = get_apps_groups_target(s, w, name);
617 error("Cannot create target '%s' (line %zu, word %zu)", s, line, word);
621 // just some optimization
622 // to avoid searching for a target for each process
623 if(!w) w = n->target?n->target:n;
629 apps_groups_default_target = get_apps_groups_target("p+!o@w#e$i^r&7*5(-i)l-o_", NULL, "other"); // match nothing
630 if(!apps_groups_default_target)
631 fatal("Cannot create default target");
633 // allow the user to override group 'other'
634 if(apps_groups_default_target->target)
635 apps_groups_default_target = apps_groups_default_target->target;
641 // ----------------------------------------------------------------------------
642 // struct pid_stat management
644 static inline struct pid_stat *get_pid_entry(pid_t pid) {
645 if(unlikely(all_pids[pid]))
646 return all_pids[pid];
648 struct pid_stat *p = callocz(sizeof(struct pid_stat), 1);
649 p->fds = callocz(sizeof(int), MAX_SPARE_FDS);
650 p->fds_size = MAX_SPARE_FDS;
652 if(likely(root_of_pids))
653 root_of_pids->prev = p;
655 p->next = root_of_pids;
666 static inline void del_pid_entry(pid_t pid) {
667 struct pid_stat *p = all_pids[pid];
670 error("attempted to free pid %d that is not allocated.", pid);
675 fprintf(stderr, "apps.plugin: process %d %s exited, deleting it.\n", pid, p->comm);
677 if(root_of_pids == p)
678 root_of_pids = p->next;
680 if(p->next) p->next->prev = p->prev;
681 if(p->prev) p->prev->next = p->next;
684 freez(p->fds_dirname);
685 freez(p->stat_filename);
686 freez(p->statm_filename);
687 freez(p->io_filename);
688 freez(p->cmdline_filename);
691 all_pids[pid] = NULL;
695 // ----------------------------------------------------------------------------
697 static inline int managed_log(struct pid_stat *p, uint32_t log, int status) {
698 if(unlikely(!status)) {
699 // error("command failed log %u, errno %d", log, errno);
701 if(unlikely(debug || errno != ENOENT)) {
702 if(unlikely(debug || !(p->log_thrown & log))) {
703 p->log_thrown |= log;
706 error("Cannot process %s/proc/%d/io (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
710 error("Cannot process %s/proc/%d/statm (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
713 case PID_LOG_CMDLINE:
714 error("Cannot process %s/proc/%d/cmdline (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
718 error("Cannot process entries in %s/proc/%d/fd (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
725 error("unhandled error for pid %d, command '%s'", p->pid, p->comm);
732 else if(unlikely(p->log_thrown & log)) {
733 // error("unsetting log %u on pid %d", log, p->pid);
734 p->log_thrown &= ~log;
740 static inline void assign_target_to_pid(struct pid_stat *p) {
741 uint32_t hash = simple_hash(p->comm);
742 size_t pclen = strlen(p->comm);
745 for(w = apps_groups_root_target; w ; w = w->next) {
746 // if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \t\tcomparing '%s' with '%s'\n", w->compare, p->comm);
748 // find it - 4 cases:
749 // 1. the target is not a pattern
750 // 2. the target has the prefix
751 // 3. the target has the suffix
752 // 4. the target is something inside cmdline
754 if(unlikely(( (!w->starts_with && !w->ends_with && w->comparehash == hash && !strcmp(w->compare, p->comm))
755 || (w->starts_with && !w->ends_with && !strncmp(w->compare, p->comm, w->comparelen))
756 || (!w->starts_with && w->ends_with && pclen >= w->comparelen && !strcmp(w->compare, &p->comm[pclen - w->comparelen]))
757 || (proc_pid_cmdline_is_needed && w->starts_with && w->ends_with && strstr(p->cmdline, w->compare))
760 if(w->target) p->target = w->target;
763 if(debug || (p->target && p->target->debug))
764 fprintf(stderr, "apps.plugin: \t\t%s linked to target %s\n", p->comm, p->target->name);
772 // ----------------------------------------------------------------------------
773 // update pids from proc
775 static inline int read_proc_pid_cmdline(struct pid_stat *p) {
777 if(unlikely(!p->cmdline_filename)) {
778 char filename[FILENAME_MAX + 1];
779 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/cmdline", netdata_configured_host_prefix, p->pid);
780 p->cmdline_filename = strdupz(filename);
783 int fd = open(p->cmdline_filename, O_RDONLY, 0666);
784 if(unlikely(fd == -1)) goto cleanup;
786 ssize_t i, bytes = read(fd, p->cmdline, MAX_CMDLINE);
789 if(unlikely(bytes < 0)) goto cleanup;
791 p->cmdline[bytes] = '\0';
792 for(i = 0; i < bytes ; i++)
793 if(unlikely(!p->cmdline[i])) p->cmdline[i] = ' ';
796 fprintf(stderr, "Read file '%s' contents: %s\n", p->cmdline_filename, p->cmdline);
801 // copy the command to the command line
802 strncpyz(p->cmdline, p->comm, MAX_CMDLINE);
806 static inline int read_proc_pid_ownership(struct pid_stat *p, void *ptr) {
809 if(unlikely(!p->stat_filename)) {
810 error("pid %d does not have a stat_filename", p->pid);
814 // ----------------------------------------
818 if(stat(p->stat_filename, &st) != 0) {
819 error("Cannot stat file '%s'", p->stat_filename);
829 // ----------------------------------------------------------------------------
830 // macro to calculate the incremental rate of a value
831 // each parameter is accessed only ONCE - so it is safe to pass function calls
832 // or other macros as parameters
834 #define incremental_rate(rate_variable, last_kernel_variable, new_kernel_value, collected_usec, last_collected_usec) { \
835 kernel_uint_t _new_tmp = new_kernel_value; \
836 rate_variable = (_new_tmp - last_kernel_variable) * (USEC_PER_SEC * RATES_DETAIL) / (collected_usec - last_collected_usec); \
837 last_kernel_variable = _new_tmp; \
840 // the same macro for struct pid members
841 #define pid_incremental_rate(type, var, value) \
842 incremental_rate(var, var##_raw, value, p->type##_collected_usec, p->last_##type##_collected_usec)
845 // ----------------------------------------------------------------------------
847 static inline int read_proc_pid_stat(struct pid_stat *p, void *ptr) {
850 static procfile *ff = NULL;
852 if(unlikely(!p->stat_filename)) {
853 char filename[FILENAME_MAX + 1];
854 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/stat", netdata_configured_host_prefix, p->pid);
855 p->stat_filename = strdupz(filename);
858 int set_quotes = (!ff)?1:0;
860 ff = procfile_reopen(ff, p->stat_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
861 if(unlikely(!ff)) goto cleanup;
863 // if(set_quotes) procfile_set_quotes(ff, "()");
864 if(unlikely(set_quotes))
865 procfile_set_open_close(ff, "(", ")");
867 ff = procfile_readall(ff);
868 if(unlikely(!ff)) goto cleanup;
870 p->last_stat_collected_usec = p->stat_collected_usec;
871 p->stat_collected_usec = now_monotonic_usec();
874 // p->pid = str2pid_t(procfile_lineword(ff, 0, 0));
875 char *comm = procfile_lineword(ff, 0, 1);
876 // p->state = *(procfile_lineword(ff, 0, 2));
877 p->ppid = (int32_t)str2pid_t(procfile_lineword(ff, 0, 3));
878 // p->pgrp = (int32_t)str2pid_t(procfile_lineword(ff, 0, 4));
879 // p->session = (int32_t)str2pid_t(procfile_lineword(ff, 0, 5));
880 // p->tty_nr = (int32_t)str2pid_t(procfile_lineword(ff, 0, 6));
881 // p->tpgid = (int32_t)str2pid_t(procfile_lineword(ff, 0, 7));
882 // p->flags = str2uint64_t(procfile_lineword(ff, 0, 8));
884 if(strcmp(p->comm, comm)) {
885 if(unlikely(debug)) {
887 fprintf(stderr, "apps.plugin: \tpid %d (%s) changed name to '%s'\n", p->pid, p->comm, comm);
889 fprintf(stderr, "apps.plugin: \tJust added %d (%s)\n", p->pid, comm);
892 strncpyz(p->comm, comm, MAX_COMPARE_NAME);
894 // /proc/<pid>/cmdline
895 if(likely(proc_pid_cmdline_is_needed))
896 managed_log(p, PID_LOG_CMDLINE, read_proc_pid_cmdline(p));
898 assign_target_to_pid(p);
901 pid_incremental_rate(stat, p->minflt, str2kernel_uint_t(procfile_lineword(ff, 0, 9)));
902 pid_incremental_rate(stat, p->cminflt, str2kernel_uint_t(procfile_lineword(ff, 0, 10)));
903 pid_incremental_rate(stat, p->majflt, str2kernel_uint_t(procfile_lineword(ff, 0, 11)));
904 pid_incremental_rate(stat, p->cmajflt, str2kernel_uint_t(procfile_lineword(ff, 0, 12)));
905 pid_incremental_rate(stat, p->utime, str2kernel_uint_t(procfile_lineword(ff, 0, 13)));
906 pid_incremental_rate(stat, p->stime, str2kernel_uint_t(procfile_lineword(ff, 0, 14)));
907 pid_incremental_rate(stat, p->cutime, str2kernel_uint_t(procfile_lineword(ff, 0, 15)));
908 pid_incremental_rate(stat, p->cstime, str2kernel_uint_t(procfile_lineword(ff, 0, 16)));
910 // p->priority = str2kernel_uint_t(procfile_lineword(ff, 0, 17));
911 // p->nice = str2kernel_uint_t(procfile_lineword(ff, 0, 18));
912 p->num_threads = (int32_t)str2uint32_t(procfile_lineword(ff, 0, 19));
913 // p->itrealvalue = str2kernel_uint_t(procfile_lineword(ff, 0, 20));
914 // p->starttime = str2kernel_uint_t(procfile_lineword(ff, 0, 21));
915 // p->vsize = str2kernel_uint_t(procfile_lineword(ff, 0, 22));
916 // p->rss = str2kernel_uint_t(procfile_lineword(ff, 0, 23));
917 // p->rsslim = str2kernel_uint_t(procfile_lineword(ff, 0, 24));
918 // p->starcode = str2kernel_uint_t(procfile_lineword(ff, 0, 25));
919 // p->endcode = str2kernel_uint_t(procfile_lineword(ff, 0, 26));
920 // p->startstack = str2kernel_uint_t(procfile_lineword(ff, 0, 27));
921 // p->kstkesp = str2kernel_uint_t(procfile_lineword(ff, 0, 28));
922 // p->kstkeip = str2kernel_uint_t(procfile_lineword(ff, 0, 29));
923 // p->signal = str2kernel_uint_t(procfile_lineword(ff, 0, 30));
924 // p->blocked = str2kernel_uint_t(procfile_lineword(ff, 0, 31));
925 // p->sigignore = str2kernel_uint_t(procfile_lineword(ff, 0, 32));
926 // p->sigcatch = str2kernel_uint_t(procfile_lineword(ff, 0, 33));
927 // p->wchan = str2kernel_uint_t(procfile_lineword(ff, 0, 34));
928 // p->nswap = str2kernel_uint_t(procfile_lineword(ff, 0, 35));
929 // p->cnswap = str2kernel_uint_t(procfile_lineword(ff, 0, 36));
930 // p->exit_signal = str2kernel_uint_t(procfile_lineword(ff, 0, 37));
931 // p->processor = str2kernel_uint_t(procfile_lineword(ff, 0, 38));
932 // p->rt_priority = str2kernel_uint_t(procfile_lineword(ff, 0, 39));
933 // p->policy = str2kernel_uint_t(procfile_lineword(ff, 0, 40));
934 // p->delayacct_blkio_ticks = str2kernel_uint_t(procfile_lineword(ff, 0, 41));
936 if(enable_guest_charts) {
938 pid_incremental_rate(stat, p->gtime, str2kernel_uint_t(procfile_lineword(ff, 0, 42)));
939 pid_incremental_rate(stat, p->cgtime, str2kernel_uint_t(procfile_lineword(ff, 0, 43)));
941 if (show_guest_time || p->gtime || p->cgtime) {
942 p->utime -= (p->utime >= p->gtime) ? p->gtime : p->utime;
943 p->cutime -= (p->cutime >= p->cgtime) ? p->cgtime : p->cutime;
948 if(unlikely(debug || (p->target && p->target->debug)))
949 fprintf(stderr, "apps.plugin: READ PROC/PID/STAT: %s/proc/%d/stat, process: '%s' on target '%s' (dt=%llu) VALUES: utime=" KERNEL_UINT_FORMAT ", stime=" KERNEL_UINT_FORMAT ", cutime=" KERNEL_UINT_FORMAT ", cstime=" KERNEL_UINT_FORMAT ", minflt=" KERNEL_UINT_FORMAT ", majflt=" KERNEL_UINT_FORMAT ", cminflt=" KERNEL_UINT_FORMAT ", cmajflt=" KERNEL_UINT_FORMAT ", threads=%d\n", netdata_configured_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);
951 if(unlikely(global_iterations_counter == 1)) {
982 static inline int read_proc_pid_statm(struct pid_stat *p, void *ptr) {
985 static procfile *ff = NULL;
987 if(unlikely(!p->statm_filename)) {
988 char filename[FILENAME_MAX + 1];
989 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/statm", netdata_configured_host_prefix, p->pid);
990 p->statm_filename = strdupz(filename);
993 ff = procfile_reopen(ff, p->statm_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
994 if(unlikely(!ff)) goto cleanup;
996 ff = procfile_readall(ff);
997 if(unlikely(!ff)) goto cleanup;
1001 p->statm_size = str2kernel_uint_t(procfile_lineword(ff, 0, 0));
1002 p->statm_resident = str2kernel_uint_t(procfile_lineword(ff, 0, 1));
1003 p->statm_share = str2kernel_uint_t(procfile_lineword(ff, 0, 2));
1004 // p->statm_text = str2kernel_uint_t(procfile_lineword(ff, 0, 3));
1005 // p->statm_lib = str2kernel_uint_t(procfile_lineword(ff, 0, 4));
1006 // p->statm_data = str2kernel_uint_t(procfile_lineword(ff, 0, 5));
1007 // p->statm_dirty = str2kernel_uint_t(procfile_lineword(ff, 0, 6));
1013 p->statm_resident = 0;
1015 // p->statm_text = 0;
1016 // p->statm_lib = 0;
1017 // p->statm_data = 0;
1018 // p->statm_dirty = 0;
1022 static inline int read_proc_pid_io(struct pid_stat *p, void *ptr) {
1025 static procfile *ff = NULL;
1027 if(unlikely(!p->io_filename)) {
1028 char filename[FILENAME_MAX + 1];
1029 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/io", netdata_configured_host_prefix, p->pid);
1030 p->io_filename = strdupz(filename);
1034 ff = procfile_reopen(ff, p->io_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
1035 if(unlikely(!ff)) goto cleanup;
1037 ff = procfile_readall(ff);
1038 if(unlikely(!ff)) goto cleanup;
1042 p->last_io_collected_usec = p->io_collected_usec;
1043 p->io_collected_usec = now_monotonic_usec();
1045 pid_incremental_rate(io, p->io_logical_bytes_read, str2kernel_uint_t(procfile_lineword(ff, 0, 1)));
1046 pid_incremental_rate(io, p->io_logical_bytes_written, str2kernel_uint_t(procfile_lineword(ff, 1, 1)));
1047 // pid_incremental_rate(io, p->io_read_calls, str2kernel_uint_t(procfile_lineword(ff, 2, 1)));
1048 // pid_incremental_rate(io, p->io_write_calls, str2kernel_uint_t(procfile_lineword(ff, 3, 1)));
1049 pid_incremental_rate(io, p->io_storage_bytes_read, str2kernel_uint_t(procfile_lineword(ff, 4, 1)));
1050 pid_incremental_rate(io, p->io_storage_bytes_written, str2kernel_uint_t(procfile_lineword(ff, 5, 1)));
1051 // pid_incremental_rate(io, p->io_cancelled_write_bytes, str2kernel_uint_t(procfile_lineword(ff, 6, 1)));
1053 if(unlikely(global_iterations_counter == 1)) {
1054 p->io_logical_bytes_read = 0;
1055 p->io_logical_bytes_written = 0;
1056 // p->io_read_calls = 0;
1057 // p->io_write_calls = 0;
1058 p->io_storage_bytes_read = 0;
1059 p->io_storage_bytes_written = 0;
1060 // p->io_cancelled_write_bytes = 0;
1066 p->io_logical_bytes_read = 0;
1067 p->io_logical_bytes_written = 0;
1068 // p->io_read_calls = 0;
1069 // p->io_write_calls = 0;
1070 p->io_storage_bytes_read = 0;
1071 p->io_storage_bytes_written = 0;
1072 // p->io_cancelled_write_bytes = 0;
1076 static inline int read_proc_stat() {
1077 static char filename[FILENAME_MAX + 1] = "";
1078 static procfile *ff = NULL;
1079 static kernel_uint_t utime_raw = 0, stime_raw = 0, gtime_raw = 0, gntime_raw = 0, ntime_raw = 0;
1080 static usec_t collected_usec = 0, last_collected_usec = 0;
1083 snprintfz(filename, FILENAME_MAX, "%s/proc/stat", netdata_configured_host_prefix);
1084 ff = procfile_open(filename, " \t:", PROCFILE_FLAG_DEFAULT);
1085 if(unlikely(!ff)) goto cleanup;
1088 ff = procfile_readall(ff);
1089 if(unlikely(!ff)) goto cleanup;
1091 last_collected_usec = collected_usec;
1092 collected_usec = now_monotonic_usec();
1096 // temporary - it is added global_ntime;
1097 kernel_uint_t global_ntime = 0;
1099 incremental_rate(global_utime, utime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 1)), collected_usec, last_collected_usec);
1100 incremental_rate(global_ntime, ntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 2)), collected_usec, last_collected_usec);
1101 incremental_rate(global_stime, stime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 3)), collected_usec, last_collected_usec);
1102 incremental_rate(global_gtime, gtime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 10)), collected_usec, last_collected_usec);
1104 global_utime += global_ntime;
1106 if(enable_guest_charts) {
1107 // temporary - it is added global_ntime;
1108 kernel_uint_t global_gntime = 0;
1110 // guest nice time, on guest time
1111 incremental_rate(global_gntime, gntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 11)), collected_usec, last_collected_usec);
1113 global_gtime += global_gntime;
1115 // remove guest time from user time
1116 global_utime -= (global_utime > global_gtime) ? global_gtime : global_utime;
1119 if(unlikely(global_iterations_counter == 1)) {
1135 // ----------------------------------------------------------------------------
1137 int file_descriptor_compare(void* a, void* b) {
1138 #ifdef NETDATA_INTERNAL_CHECKS
1139 if(((struct file_descriptor *)a)->magic != 0x0BADCAFE || ((struct file_descriptor *)b)->magic != 0x0BADCAFE)
1140 error("Corrupted index data detected. Please report this.");
1141 #endif /* NETDATA_INTERNAL_CHECKS */
1143 if(((struct file_descriptor *)a)->hash < ((struct file_descriptor *)b)->hash)
1146 else if(((struct file_descriptor *)a)->hash > ((struct file_descriptor *)b)->hash)
1150 return strcmp(((struct file_descriptor *)a)->name, ((struct file_descriptor *)b)->name);
1153 int file_descriptor_iterator(avl *a) { if(a) {}; return 0; }
1155 avl_tree all_files_index = {
1157 file_descriptor_compare
1160 static struct file_descriptor *file_descriptor_find(const char *name, uint32_t hash) {
1161 struct file_descriptor tmp;
1162 tmp.hash = (hash)?hash:simple_hash(name);
1166 #ifdef NETDATA_INTERNAL_CHECKS
1167 tmp.magic = 0x0BADCAFE;
1168 #endif /* NETDATA_INTERNAL_CHECKS */
1170 return (struct file_descriptor *)avl_search(&all_files_index, (avl *) &tmp);
1173 #define file_descriptor_add(fd) avl_insert(&all_files_index, (avl *)(fd))
1174 #define file_descriptor_remove(fd) avl_remove(&all_files_index, (avl *)(fd))
1176 // ----------------------------------------------------------------------------
1178 static inline void file_descriptor_not_used(int id)
1180 if(id > 0 && id < all_files_size) {
1182 #ifdef NETDATA_INTERNAL_CHECKS
1183 if(all_files[id].magic != 0x0BADCAFE) {
1184 error("Ignoring request to remove empty file id %d.", id);
1187 #endif /* NETDATA_INTERNAL_CHECKS */
1190 fprintf(stderr, "apps.plugin: decreasing slot %d (count = %d).\n", id, all_files[id].count);
1192 if(all_files[id].count > 0) {
1193 all_files[id].count--;
1195 if(!all_files[id].count) {
1197 fprintf(stderr, "apps.plugin: >> slot %d is empty.\n", id);
1199 if(unlikely(file_descriptor_remove(&all_files[id]) != (void *)&all_files[id]))
1200 error("INTERNAL ERROR: removal of unused fd from index, removed a different fd");
1202 #ifdef NETDATA_INTERNAL_CHECKS
1203 all_files[id].magic = 0x00000000;
1204 #endif /* NETDATA_INTERNAL_CHECKS */
1209 error("Request to decrease counter of fd %d (%s), while the use counter is 0", id, all_files[id].name);
1211 else error("Request to decrease counter of fd %d, which is outside the array size (1 to %d)", id, all_files_size);
1214 static inline void all_files_grow() {
1215 void *old = all_files;
1218 // there is no empty slot
1220 fprintf(stderr, "apps.plugin: extending fd array to %d entries\n", all_files_size + FILE_DESCRIPTORS_INCREASE_STEP);
1222 all_files = reallocz(all_files, (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP) * sizeof(struct file_descriptor));
1224 // if the address changed, we have to rebuild the index
1225 // since all pointers are now invalid
1227 if(unlikely(old && old != (void *)all_files)) {
1229 fprintf(stderr, "apps.plugin: >> re-indexing.\n");
1231 all_files_index.root = NULL;
1232 for(i = 0; i < all_files_size; i++) {
1233 if(!all_files[i].count) continue;
1234 if(unlikely(file_descriptor_add(&all_files[i]) != (void *)&all_files[i]))
1235 error("INTERNAL ERROR: duplicate indexing of fd during realloc.");
1239 fprintf(stderr, "apps.plugin: >> re-indexing done.\n");
1242 // initialize the newly added entries
1244 for(i = all_files_size; i < (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP); i++) {
1245 all_files[i].count = 0;
1246 all_files[i].name = NULL;
1247 #ifdef NETDATA_INTERNAL_CHECKS
1248 all_files[i].magic = 0x00000000;
1249 #endif /* NETDATA_INTERNAL_CHECKS */
1250 all_files[i].pos = i;
1253 if(unlikely(!all_files_size)) all_files_len = 1;
1254 all_files_size += FILE_DESCRIPTORS_INCREASE_STEP;
1257 static inline int file_descriptor_set_on_empty_slot(const char *name, uint32_t hash, FD_FILETYPE type) {
1258 // check we have enough memory to add it
1259 if(!all_files || all_files_len == all_files_size)
1263 fprintf(stderr, "apps.plugin: >> searching for empty slot.\n");
1265 // search for an empty slot
1267 static int last_pos = 0;
1269 for(i = 0, c = last_pos ; i < all_files_size ; i++, c++) {
1270 if(c >= all_files_size) c = 0;
1271 if(c == 0) continue;
1273 if(!all_files[c].count) {
1275 fprintf(stderr, "apps.plugin: >> Examining slot %d.\n", c);
1277 #ifdef NETDATA_INTERNAL_CHECKS
1278 if(all_files[c].magic == 0x0BADCAFE && all_files[c].name && file_descriptor_find(all_files[c].name, all_files[c].hash))
1279 error("fd on position %d is not cleared properly. It still has %s in it.\n", c, all_files[c].name);
1280 #endif /* NETDATA_INTERNAL_CHECKS */
1283 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);
1285 freez((void *)all_files[c].name);
1286 all_files[c].name = NULL;
1294 if(i == all_files_size) {
1295 fatal("We should find an empty slot, but there isn't any");
1298 // else we have an empty slot in 'c'
1301 fprintf(stderr, "apps.plugin: >> updating slot %d.\n", c);
1303 all_files[c].name = strdupz(name);
1304 all_files[c].hash = hash;
1305 all_files[c].type = type;
1306 all_files[c].pos = c;
1307 all_files[c].count = 1;
1308 #ifdef NETDATA_INTERNAL_CHECKS
1309 all_files[c].magic = 0x0BADCAFE;
1310 #endif /* NETDATA_INTERNAL_CHECKS */
1311 if(unlikely(file_descriptor_add(&all_files[c]) != (void *)&all_files[c]))
1312 error("INTERNAL ERROR: duplicate indexing of fd.");
1315 fprintf(stderr, "apps.plugin: using fd position %d (name: %s)\n", c, all_files[c].name);
1320 static inline int file_descriptor_find_or_add(const char *name)
1322 uint32_t hash = simple_hash(name);
1325 fprintf(stderr, "apps.plugin: adding or finding name '%s' with hash %u\n", name, hash);
1327 struct file_descriptor *fd = file_descriptor_find(name, hash);
1331 fprintf(stderr, "apps.plugin: >> found on slot %d\n", fd->pos);
1339 if(likely(name[0] == '/')) type = FILETYPE_FILE;
1340 else if(likely(strncmp(name, "pipe:", 5) == 0)) type = FILETYPE_PIPE;
1341 else if(likely(strncmp(name, "socket:", 7) == 0)) type = FILETYPE_SOCKET;
1342 else if(likely(strncmp(name, "anon_inode:", 11) == 0)) {
1343 const char *t = &name[11];
1345 if(strcmp(t, "inotify") == 0) type = FILETYPE_INOTIFY;
1346 else if(strcmp(t, "[eventfd]") == 0) type = FILETYPE_EVENTFD;
1347 else if(strcmp(t, "[eventpoll]") == 0) type = FILETYPE_EVENTPOLL;
1348 else if(strcmp(t, "[timerfd]") == 0) type = FILETYPE_TIMERFD;
1349 else if(strcmp(t, "[signalfd]") == 0) type = FILETYPE_SIGNALFD;
1352 fprintf(stderr, "apps.plugin: FIXME: unknown anonymous inode: %s\n", name);
1354 type = FILETYPE_OTHER;
1357 else if(likely(strcmp(name, "inotify") == 0)) type = FILETYPE_INOTIFY;
1360 fprintf(stderr, "apps.plugin: FIXME: cannot understand linkname: %s\n", name);
1362 type = FILETYPE_OTHER;
1365 return file_descriptor_set_on_empty_slot(name, hash, type);
1368 static inline void make_all_pid_fds_negative(struct pid_stat *p) {
1369 int *fd = p->fds, *end = &p->fds[p->fds_size];
1376 static inline void cleanup_negative_pid_fds(struct pid_stat *p) {
1377 int *fd = p->fds, *fdend = &p->fds[p->fds_size];
1380 if(unlikely(*fd < 0)) {
1381 file_descriptor_not_used(-(*fd));
1389 static inline void zero_pid_fds(struct pid_stat *p, int first, int size) {
1390 int *fd = &p->fds[first], *end = &p->fds[first + size];
1391 while(fd < end) *fd++ = 0;
1394 static inline int read_pid_file_descriptors(struct pid_stat *p, void *ptr) {
1397 if(unlikely(!p->fds_dirname)) {
1398 char dirname[FILENAME_MAX+1];
1399 snprintfz(dirname, FILENAME_MAX, "%s/proc/%d/fd", netdata_configured_host_prefix, p->pid);
1400 p->fds_dirname = strdupz(dirname);
1403 DIR *fds = opendir(p->fds_dirname);
1404 if(unlikely(!fds)) return 0;
1407 char fdname[FILENAME_MAX + 1];
1408 char linkname[FILENAME_MAX + 1];
1410 // we make all pid fds negative, so that
1411 // we can detect unused file descriptors
1412 // at the end, to free them
1413 make_all_pid_fds_negative(p);
1415 while((de = readdir(fds))) {
1416 // we need only files with numeric names
1418 if(unlikely(de->d_name[0] < '0' || de->d_name[0] > '9'))
1422 int fdid = (int) str2l(de->d_name);
1423 if(unlikely(fdid < 0)) continue;
1425 // check if the fds array is small
1426 if(unlikely(fdid >= p->fds_size)) {
1427 // it is small, extend it
1431 , "apps.plugin: extending fd memory slots for %s from %d to %d\n"
1434 , fdid + MAX_SPARE_FDS
1437 p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(int));
1439 // and initialize it
1440 zero_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
1441 p->fds_size = fdid + MAX_SPARE_FDS;
1444 if(unlikely(p->fds[fdid] == 0)) {
1445 // we don't know this fd, get it
1447 sprintf(fdname, "%s/proc/%d/fd/%s", netdata_configured_host_prefix, p->pid, de->d_name);
1448 ssize_t l = readlink(fdname, linkname, FILENAME_MAX);
1449 if(unlikely(l == -1)) {
1450 if(debug || (p->target && p->target->debug)) {
1451 if(debug || (p->target && p->target->debug))
1452 error("Cannot read link %s", fdname);
1461 // if another process already has this, we will get
1463 p->fds[fdid] = file_descriptor_find_or_add(linkname);
1466 // else make it positive again, we need it
1467 // of course, the actual file may have changed, but we don't care so much
1468 // FIXME: we could compare the inode as returned by readdir dirent structure
1469 // UPDATE: no we cannot use inodes - under /proc inodes don't change when the link is changed
1472 p->fds[fdid] = -p->fds[fdid];
1476 cleanup_negative_pid_fds(p);
1481 // ----------------------------------------------------------------------------
1483 static inline int print_process_and_parents(struct pid_stat *p, usec_t time) {
1484 char *prefix = "\\_ ";
1488 indent = print_process_and_parents(p->parent, p->stat_collected_usec);
1492 char buffer[indent + 1];
1495 for(i = 0; i < indent ;i++) buffer[i] = ' ';
1498 fprintf(stderr, " %s %s%s (%d %s %llu"
1503 , p->updated?"running":"exited"
1504 , p->stat_collected_usec - time
1507 if(p->utime) fprintf(stderr, " utime=" KERNEL_UINT_FORMAT, p->utime);
1508 if(p->stime) fprintf(stderr, " stime=" KERNEL_UINT_FORMAT, p->stime);
1509 if(p->gtime) fprintf(stderr, " gtime=" KERNEL_UINT_FORMAT, p->gtime);
1510 if(p->cutime) fprintf(stderr, " cutime=" KERNEL_UINT_FORMAT, p->cutime);
1511 if(p->cstime) fprintf(stderr, " cstime=" KERNEL_UINT_FORMAT, p->cstime);
1512 if(p->cgtime) fprintf(stderr, " cgtime=" KERNEL_UINT_FORMAT, p->cgtime);
1513 if(p->minflt) fprintf(stderr, " minflt=" KERNEL_UINT_FORMAT, p->minflt);
1514 if(p->cminflt) fprintf(stderr, " cminflt=" KERNEL_UINT_FORMAT, p->cminflt);
1515 if(p->majflt) fprintf(stderr, " majflt=" KERNEL_UINT_FORMAT, p->majflt);
1516 if(p->cmajflt) fprintf(stderr, " cmajflt=" KERNEL_UINT_FORMAT, p->cmajflt);
1517 fprintf(stderr, ")\n");
1522 static inline void print_process_tree(struct pid_stat *p, char *msg) {
1524 fprintf(stderr, "%s: process %s (%d, %s) with parents:\n", msg, p->comm, p->pid, p->updated?"running":"exited");
1525 print_process_and_parents(p, p->stat_collected_usec);
1528 static inline void find_lost_child_debug(struct pid_stat *pe, kernel_uint_t lost, int type) {
1530 struct pid_stat *p = NULL;
1532 for(p = root_of_pids; p ; p = p->next) {
1533 if(p == pe) continue;
1537 if(p->cminflt > lost) {
1538 fprintf(stderr, " > process %d (%s) could use the lost exited child minflt " KERNEL_UINT_FORMAT " of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
1544 if(p->cmajflt > lost) {
1545 fprintf(stderr, " > process %d (%s) could use the lost exited child majflt " KERNEL_UINT_FORMAT " of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
1551 if(p->cutime > lost) {
1552 fprintf(stderr, " > process %d (%s) could use the lost exited child utime " KERNEL_UINT_FORMAT " of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
1558 if(p->cstime > lost) {
1559 fprintf(stderr, " > process %d (%s) could use the lost exited child stime " KERNEL_UINT_FORMAT " of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
1565 if(p->cgtime > lost) {
1566 fprintf(stderr, " > process %d (%s) could use the lost exited child gtime " KERNEL_UINT_FORMAT " of process %d (%s)\n", p->pid, p->comm, lost, pe->pid, pe->comm);
1576 fprintf(stderr, " > cannot find any process to use the lost exited child minflt " KERNEL_UINT_FORMAT " of process %d (%s)\n", lost, pe->pid, pe->comm);
1580 fprintf(stderr, " > cannot find any process to use the lost exited child majflt " KERNEL_UINT_FORMAT " of process %d (%s)\n", lost, pe->pid, pe->comm);
1584 fprintf(stderr, " > cannot find any process to use the lost exited child utime " KERNEL_UINT_FORMAT " of process %d (%s)\n", lost, pe->pid, pe->comm);
1588 fprintf(stderr, " > cannot find any process to use the lost exited child stime " KERNEL_UINT_FORMAT " of process %d (%s)\n", lost, pe->pid, pe->comm);
1592 fprintf(stderr, " > cannot find any process to use the lost exited child gtime " KERNEL_UINT_FORMAT " of process %d (%s)\n", lost, pe->pid, pe->comm);
1598 static inline kernel_uint_t remove_exited_child_from_parent(kernel_uint_t *field, kernel_uint_t *pfield) {
1599 kernel_uint_t absorbed = 0;
1601 if(*field > *pfield) {
1602 absorbed += *pfield;
1615 static inline void process_exited_processes() {
1618 for(p = root_of_pids; p ; p = p->next) {
1619 if(p->updated || !p->stat_collected_usec)
1622 kernel_uint_t utime = (p->utime_raw + p->cutime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1623 kernel_uint_t stime = (p->stime_raw + p->cstime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1624 kernel_uint_t gtime = (p->gtime_raw + p->cgtime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1625 kernel_uint_t minflt = (p->minflt_raw + p->cminflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1626 kernel_uint_t majflt = (p->majflt_raw + p->cmajflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1628 if(utime + stime + gtime + minflt + majflt == 0)
1631 if(unlikely(debug)) {
1633 fprintf(stderr, "Absorb %s (%d %s total resources: utime=" KERNEL_UINT_FORMAT " stime=" KERNEL_UINT_FORMAT " gtime=" KERNEL_UINT_FORMAT " minflt=" KERNEL_UINT_FORMAT " majflt=" KERNEL_UINT_FORMAT ")\n"
1636 , p->updated?"running":"exited"
1643 print_process_tree(p, "Searching parents");
1646 struct pid_stat *pp;
1647 for(pp = p->parent; pp ; pp = pp->parent) {
1648 if(!pp->updated) continue;
1650 kernel_uint_t absorbed;
1651 absorbed = remove_exited_child_from_parent(&utime, &pp->cutime);
1652 if(unlikely(debug && absorbed))
1653 fprintf(stderr, " > process %s (%d %s) absorbed " KERNEL_UINT_FORMAT " utime (remaining: " KERNEL_UINT_FORMAT ")\n", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, utime);
1655 absorbed = remove_exited_child_from_parent(&stime, &pp->cstime);
1656 if(unlikely(debug && absorbed))
1657 fprintf(stderr, " > process %s (%d %s) absorbed " KERNEL_UINT_FORMAT " stime (remaining: " KERNEL_UINT_FORMAT ")\n", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, stime);
1659 absorbed = remove_exited_child_from_parent(>ime, &pp->cgtime);
1660 if(unlikely(debug && absorbed))
1661 fprintf(stderr, " > process %s (%d %s) absorbed " KERNEL_UINT_FORMAT " gtime (remaining: " KERNEL_UINT_FORMAT ")\n", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, gtime);
1663 absorbed = remove_exited_child_from_parent(&minflt, &pp->cminflt);
1664 if(unlikely(debug && absorbed))
1665 fprintf(stderr, " > process %s (%d %s) absorbed " KERNEL_UINT_FORMAT " minflt (remaining: " KERNEL_UINT_FORMAT ")\n", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, minflt);
1667 absorbed = remove_exited_child_from_parent(&majflt, &pp->cmajflt);
1668 if(unlikely(debug && absorbed))
1669 fprintf(stderr, " > process %s (%d %s) absorbed " KERNEL_UINT_FORMAT " majflt (remaining: " KERNEL_UINT_FORMAT ")\n", pp->comm, pp->pid, pp->updated?"running":"exited", absorbed, majflt);
1672 if(unlikely(utime + stime + gtime + minflt + majflt > 0)) {
1673 if(unlikely(debug)) {
1674 if(utime) find_lost_child_debug(p, utime, 3);
1675 if(stime) find_lost_child_debug(p, stime, 4);
1676 if(gtime) find_lost_child_debug(p, gtime, 5);
1677 if(minflt) find_lost_child_debug(p, minflt, 1);
1678 if(majflt) find_lost_child_debug(p, majflt, 2);
1684 fprintf(stderr, " > remaining resources - KEEP - for another loop: %s (%d %s total resources: utime=" KERNEL_UINT_FORMAT " stime=" KERNEL_UINT_FORMAT " gtime=" KERNEL_UINT_FORMAT " minflt=" KERNEL_UINT_FORMAT " majflt=" KERNEL_UINT_FORMAT ")\n"
1687 , p->updated?"running":"exited"
1695 for(pp = p->parent; pp ; pp = pp->parent) {
1696 if(pp->updated) break;
1700 fprintf(stderr, " > - KEEP - parent for another loop: %s (%d %s)\n"
1703 , pp->updated?"running":"exited"
1707 p->utime_raw = utime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1708 p->stime_raw = stime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1709 p->gtime_raw = gtime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1710 p->minflt_raw = minflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1711 p->majflt_raw = majflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1712 p->cutime_raw = p->cstime_raw = p->cgtime_raw = p->cminflt_raw = p->cmajflt_raw = 0;
1715 fprintf(stderr, "\n");
1717 else if(unlikely(debug)) {
1718 fprintf(stderr, " > totally absorbed - DONE - %s (%d %s)\n"
1721 , p->updated?"running":"exited"
1727 static inline void link_all_processes_to_their_parents(void) {
1728 struct pid_stat *p, *pp;
1730 // link all children to their parents
1731 // and update children count on parents
1732 for(p = root_of_pids; p ; p = p->next) {
1733 // for each process found
1738 if(unlikely(!p->ppid)) {
1743 pp = all_pids[p->ppid];
1746 pp->children_count++;
1748 if(unlikely(debug || (p->target && p->target->debug)))
1749 fprintf(stderr, "apps.plugin: \tchild %d (%s, %s) on target '%s' has parent %d (%s, %s). Parent: utime=" KERNEL_UINT_FORMAT ", stime=" KERNEL_UINT_FORMAT ", gtime=" KERNEL_UINT_FORMAT ", minflt=" KERNEL_UINT_FORMAT ", majflt=" KERNEL_UINT_FORMAT ", cutime=" KERNEL_UINT_FORMAT ", cstime=" KERNEL_UINT_FORMAT ", cgtime=" KERNEL_UINT_FORMAT ", cminflt=" KERNEL_UINT_FORMAT ", cmajflt=" KERNEL_UINT_FORMAT "\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);
1753 error("pid %d %s states parent %d, but the later does not exist.", p->pid, p->comm, p->ppid);
1758 // ----------------------------------------------------------------------------
1760 // 1. read all files in /proc
1761 // 2. for each numeric directory:
1762 // i. read /proc/pid/stat
1763 // ii. read /proc/pid/statm
1764 // iii. read /proc/pid/io (requires root access)
1765 // iii. read the entries in directory /proc/pid/fd (requires root access)
1767 // a. find or create a struct file_descriptor
1768 // b. cleanup any old/unused file_descriptors
1770 // after all these, some pids may be linked to targets, while others may not
1772 // in case of errors, only 1 every 1000 errors is printed
1773 // to avoid filling up all disk space
1774 // if debug is enabled, all errors are printed
1776 static int compar_pid(const void *pid1, const void *pid2) {
1778 struct pid_stat *p1 = all_pids[*((pid_t *)pid1)];
1779 struct pid_stat *p2 = all_pids[*((pid_t *)pid2)];
1781 if(p1->sortlist > p2->sortlist)
1787 static inline int collect_data_for_pid(pid_t pid, void *ptr) {
1788 if(unlikely(pid < INIT_PID || pid > pid_max)) {
1789 error("Invalid pid %d read (expected %d to %d). Ignoring process.", pid, INIT_PID, pid_max);
1793 struct pid_stat *p = get_pid_entry(pid);
1794 if(unlikely(!p || p->read)) return 0;
1797 // fprintf(stderr, "Reading process %d (%s), sortlist %d\n", p->pid, p->comm, p->sortlist);
1799 // --------------------------------------------------------------------
1802 if(unlikely(!managed_log(p, PID_LOG_STAT, read_proc_pid_stat(p, ptr))))
1803 // there is no reason to proceed if we cannot get its status
1806 read_proc_pid_ownership(p, ptr);
1808 // check its parent pid
1809 if(unlikely(p->ppid < 0 || p->ppid > pid_max)) {
1810 error("Pid %d (command '%s') states invalid parent pid %d. Using 0.", pid, p->comm, p->ppid);
1814 // --------------------------------------------------------------------
1817 managed_log(p, PID_LOG_IO, read_proc_pid_io(p, ptr));
1819 // --------------------------------------------------------------------
1820 // /proc/<pid>/statm
1822 if(unlikely(!managed_log(p, PID_LOG_STATM, read_proc_pid_statm(p, ptr))))
1823 // there is no reason to proceed if we cannot get its memory status
1826 // --------------------------------------------------------------------
1829 if(enable_file_charts)
1830 managed_log(p, PID_LOG_FDS, read_pid_file_descriptors(p, ptr));
1832 // --------------------------------------------------------------------
1835 if(unlikely(debug && include_exited_childs && all_pids_count && p->ppid && all_pids[p->ppid] && !all_pids[p->ppid]->read))
1836 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);
1838 // mark it as updated
1846 static int collect_data_for_all_processes(void) {
1847 struct pid_stat *p = NULL;
1849 if(all_pids_count) {
1851 for(p = root_of_pids; p ; p = p->next) {
1852 p->read = 0; // mark it as not read, so that collect_data_for_pid() will read it
1855 p->children_count = 0;
1858 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
1859 all_pids_sortlist[slc++] = p->pid;
1863 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
1864 if(unlikely(slc != all_pids_count)) {
1865 error("Internal error: I was thinking I had %zu processes in my arrays, but it seems there are more.", all_pids_count);
1866 all_pids_count = slc;
1869 if(include_exited_childs) {
1870 // Read parents before childs
1871 // This is needed to prevent a situation where
1872 // a child is found running, but until we read
1873 // its parent, it has exited and its parent
1874 // has accumulated its resources.
1876 qsort((void *)all_pids_sortlist, (size_t)all_pids_count, sizeof(pid_t), compar_pid);
1878 // we forward read all running processes
1879 // collect_data_for_pid() is smart enough,
1880 // not to read the same pid twice per iteration
1881 for(slc = 0; slc < all_pids_count; slc++)
1882 collect_data_for_pid(all_pids_sortlist[slc], NULL);
1887 char dirname[FILENAME_MAX + 1];
1889 snprintfz(dirname, FILENAME_MAX, "%s/proc", netdata_configured_host_prefix);
1890 DIR *dir = opendir(dirname);
1893 struct dirent *de = NULL;
1895 while((de = readdir(dir))) {
1896 char *endptr = de->d_name;
1898 if(unlikely(de->d_type != DT_DIR || de->d_name[0] < '0' || de->d_name[0] > '9'))
1901 pid_t pid = (pid_t) strtoul(de->d_name, &endptr, 10);
1903 // make sure we read a valid number
1904 if(unlikely(endptr == de->d_name || *endptr != '\0'))
1907 collect_data_for_pid(pid, NULL);
1914 // we need /proc/stat to normalize the cpu consumption of the exited childs
1917 // build the process tree
1918 link_all_processes_to_their_parents();
1920 // normally this is done
1921 // however we may have processes exited while we collected values
1922 // so let's find the exited ones
1923 // we do this by collecting the ownership of process
1924 // if we manage to get the ownership, the process still runs
1925 process_exited_processes();
1930 // ----------------------------------------------------------------------------
1931 // update statistics on the targets
1933 // 1. link all childs to their parents
1934 // 2. go from bottom to top, marking as merged all childs to their parents
1935 // this step links all parents without a target to the child target, if any
1936 // 3. link all top level processes (the ones not merged) to the default target
1937 // 4. go from top to bottom, linking all childs without a target, to their parent target
1938 // after this step, all processes have a target
1939 // [5. for each killed pid (updated = 0), remove its usage from its target]
1940 // 6. zero all apps_groups_targets
1941 // 7. concentrate all values on the apps_groups_targets
1942 // 8. remove all killed processes
1943 // 9. find the unique file count for each target
1944 // check: update_apps_groups_statistics()
1946 static void cleanup_exited_pids(void) {
1948 struct pid_stat *p = NULL;
1950 for(p = root_of_pids; p ;) {
1951 if(!p->updated && (!p->keep || p->keeploops > 0)) {
1952 if(unlikely(debug && (p->keep || p->keeploops)))
1953 fprintf(stderr, " > CLEANUP cannot keep exited process %d (%s) anymore - removing it.\n", p->pid, p->comm);
1955 for(c = 0; c < p->fds_size; c++)
1957 file_descriptor_not_used(p->fds[c]);
1966 if(unlikely(p->keep)) p->keeploops++;
1973 static void apply_apps_groups_targets_inheritance(void) {
1974 struct pid_stat *p = NULL;
1976 // children that do not have a target
1977 // inherit their target from their parent
1978 int found = 1, loops = 0;
1980 if(unlikely(debug)) loops++;
1982 for(p = root_of_pids; p ; p = p->next) {
1983 // if this process does not have a target
1984 // and it has a parent
1985 // and its parent has a target
1986 // then, set the parent's target to this process
1987 if(unlikely(!p->target && p->parent && p->parent->target)) {
1988 p->target = p->parent->target;
1991 if(debug || (p->target && p->target->debug))
1992 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);
1997 // find all the procs with 0 childs and merge them to their parents
1998 // repeat, until nothing more can be done.
2002 if(unlikely(debug)) loops++;
2005 for(p = root_of_pids; p ; p = p->next) {
2006 if(unlikely(!p->sortlist && !p->children_count))
2007 p->sortlist = sortlist++;
2009 // if this process does not have any children
2010 // and is not already merged
2012 // and its parent has children
2013 // and the target of this process and its parent is the same, or the parent does not have a target
2014 // and its parent is not init
2015 // then, mark them as merged.
2020 && p->parent->children_count
2021 && (p->target == p->parent->target || !p->parent->target)
2022 && p->ppid != INIT_PID
2024 p->parent->children_count--;
2027 // the parent inherits the child's target, if it does not have a target itself
2028 if(unlikely(p->target && !p->parent->target)) {
2029 p->parent->target = p->target;
2031 if(debug || (p->target && p->target->debug))
2032 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);
2040 fprintf(stderr, "apps.plugin: TARGET INHERITANCE: merged %d processes\n", found);
2043 // init goes always to default target
2044 if(all_pids[INIT_PID])
2045 all_pids[INIT_PID]->target = apps_groups_default_target;
2047 // give a default target on all top level processes
2048 if(unlikely(debug)) loops++;
2049 for(p = root_of_pids; p ; p = p->next) {
2050 // if the process is not merged itself
2051 // then is is a top level process
2052 if(unlikely(!p->merged && !p->target))
2053 p->target = apps_groups_default_target;
2055 // make sure all processes have a sortlist
2056 if(unlikely(!p->sortlist))
2057 p->sortlist = sortlist++;
2061 all_pids[1]->sortlist = sortlist++;
2063 // give a target to all merged child processes
2066 if(unlikely(debug)) loops++;
2068 for(p = root_of_pids; p ; p = p->next) {
2069 if(unlikely(!p->target && p->merged && p->parent && p->parent->target)) {
2070 p->target = p->parent->target;
2073 if(debug || (p->target && p->target->debug))
2074 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);
2080 fprintf(stderr, "apps.plugin: apply_apps_groups_targets_inheritance() made %d loops on the process tree\n", loops);
2083 static size_t zero_all_targets(struct target *root) {
2087 for (w = root; w ; w = w->next) {
2105 w->statm_resident = 0;
2107 // w->statm_text = 0;
2108 // w->statm_lib = 0;
2109 // w->statm_data = 0;
2110 // w->statm_dirty = 0;
2112 w->io_logical_bytes_read = 0;
2113 w->io_logical_bytes_written = 0;
2114 // w->io_read_calls = 0;
2115 // w->io_write_calls = 0;
2116 w->io_storage_bytes_read = 0;
2117 w->io_storage_bytes_written = 0;
2118 // w->io_cancelled_write_bytes = 0;
2120 // zero file counters
2122 memset(w->target_fds, 0, sizeof(int) * w->target_fds_size);
2126 w->openinotifies = 0;
2127 w->openeventfds = 0;
2128 w->opentimerfds = 0;
2129 w->opensignalfds = 0;
2130 w->openeventpolls = 0;
2138 static inline void reallocate_target_fds(struct target *w) {
2142 if(unlikely(!w->target_fds || w->target_fds_size < all_files_size)) {
2143 w->target_fds = reallocz(w->target_fds, sizeof(int) * all_files_size);
2144 memset(&w->target_fds[w->target_fds_size], 0, sizeof(int) * (all_files_size - w->target_fds_size));
2145 w->target_fds_size = all_files_size;
2149 static inline void aggregate_fd_on_target(int fd, struct target *w) {
2153 if(unlikely(w->target_fds[fd])) {
2154 // it is already aggregated
2155 // just increase its usage counter
2156 w->target_fds[fd]++;
2160 // increase its usage counter
2161 // so that we will not add it again
2162 w->target_fds[fd]++;
2164 switch(all_files[fd].type) {
2173 case FILETYPE_SOCKET:
2177 case FILETYPE_INOTIFY:
2181 case FILETYPE_EVENTFD:
2185 case FILETYPE_TIMERFD:
2189 case FILETYPE_SIGNALFD:
2193 case FILETYPE_EVENTPOLL:
2194 w->openeventpolls++;
2197 case FILETYPE_OTHER:
2203 static inline void aggregate_pid_fds_on_targets(struct pid_stat *p) {
2205 if(unlikely(!p->updated)) {
2206 // the process is not running
2210 struct target *w = p->target, *u = p->user_target, *g = p->group_target;
2212 reallocate_target_fds(w);
2213 reallocate_target_fds(u);
2214 reallocate_target_fds(g);
2216 int c, size = p->fds_size, *fds = p->fds;
2217 for(c = 0; c < size ;c++) {
2220 if(likely(fd <= 0 || fd >= all_files_size))
2223 aggregate_fd_on_target(fd, w);
2224 aggregate_fd_on_target(fd, u);
2225 aggregate_fd_on_target(fd, g);
2229 static inline void aggregate_pid_on_target(struct target *w, struct pid_stat *p, struct target *o) {
2232 if(unlikely(!p->updated)) {
2233 // the process is not running
2238 error("pid %d %s was left without a target!", p->pid, p->comm);
2242 w->cutime += p->cutime;
2243 w->cstime += p->cstime;
2244 w->cgtime += p->cgtime;
2245 w->cminflt += p->cminflt;
2246 w->cmajflt += p->cmajflt;
2248 w->utime += p->utime;
2249 w->stime += p->stime;
2250 w->gtime += p->gtime;
2251 w->minflt += p->minflt;
2252 w->majflt += p->majflt;
2254 // w->rss += p->rss;
2256 w->statm_size += p->statm_size;
2257 w->statm_resident += p->statm_resident;
2258 w->statm_share += p->statm_share;
2259 // w->statm_text += p->statm_text;
2260 // w->statm_lib += p->statm_lib;
2261 // w->statm_data += p->statm_data;
2262 // w->statm_dirty += p->statm_dirty;
2264 w->io_logical_bytes_read += p->io_logical_bytes_read;
2265 w->io_logical_bytes_written += p->io_logical_bytes_written;
2266 // w->io_read_calls += p->io_read_calls;
2267 // w->io_write_calls += p->io_write_calls;
2268 w->io_storage_bytes_read += p->io_storage_bytes_read;
2269 w->io_storage_bytes_written += p->io_storage_bytes_written;
2270 // w->io_cancelled_write_bytes += p->io_cancelled_write_bytes;
2273 w->num_threads += p->num_threads;
2275 if(unlikely(debug || w->debug))
2276 fprintf(stderr, "apps.plugin: \taggregating '%s' pid %d on target '%s' utime=" KERNEL_UINT_FORMAT ", stime=" KERNEL_UINT_FORMAT ", gtime=" KERNEL_UINT_FORMAT ", cutime=" KERNEL_UINT_FORMAT ", cstime=" KERNEL_UINT_FORMAT ", cgtime=" KERNEL_UINT_FORMAT ", minflt=" KERNEL_UINT_FORMAT ", majflt=" KERNEL_UINT_FORMAT ", cminflt=" KERNEL_UINT_FORMAT ", cmajflt=" KERNEL_UINT_FORMAT "\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);
2279 static void calculate_netdata_statistics(void) {
2281 apply_apps_groups_targets_inheritance();
2283 zero_all_targets(users_root_target);
2284 zero_all_targets(groups_root_target);
2285 apps_groups_targets_count = zero_all_targets(apps_groups_root_target);
2287 // this has to be done, before the cleanup
2288 struct pid_stat *p = NULL;
2289 struct target *w = NULL, *o = NULL;
2291 // concentrate everything on the targets
2292 for(p = root_of_pids; p ; p = p->next) {
2294 // --------------------------------------------------------------------
2295 // apps_groups target
2297 aggregate_pid_on_target(p->target, p, NULL);
2300 // --------------------------------------------------------------------
2304 if(likely(p->user_target && p->user_target->uid == p->uid))
2307 if(unlikely(debug && p->user_target))
2308 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);
2310 w = p->user_target = get_users_target(p->uid);
2313 aggregate_pid_on_target(w, p, o);
2316 // --------------------------------------------------------------------
2317 // user group target
2319 o = p->group_target;
2320 if(likely(p->group_target && p->group_target->gid == p->gid))
2321 w = p->group_target;
2323 if(unlikely(debug && p->group_target))
2324 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);
2326 w = p->group_target = get_groups_target(p->gid);
2329 aggregate_pid_on_target(w, p, o);
2332 // --------------------------------------------------------------------
2333 // aggregate all file descriptors
2335 if(enable_file_charts)
2336 aggregate_pid_fds_on_targets(p);
2339 cleanup_exited_pids();
2342 // ----------------------------------------------------------------------------
2343 // update chart dimensions
2345 int print_calculated_number(char *str, calculated_number value) { (void)str; (void)value; return 0; }
2347 static inline void send_BEGIN(const char *type, const char *id, usec_t usec) {
2348 fprintf(stdout, "BEGIN %s.%s %llu\n", type, id, usec);
2351 static inline void send_SET(const char *name, kernel_uint_t value) {
2352 fprintf(stdout, "SET %s = " KERNEL_UINT_FORMAT "\n", name, value);
2355 static inline void send_END(void) {
2356 fprintf(stdout, "END\n");
2359 static usec_t send_resource_usage_to_netdata() {
2360 static struct timeval last = { 0, 0 };
2361 static struct rusage me_last;
2371 now_monotonic_timeval(&last);
2372 getrusage(RUSAGE_SELF, &me_last);
2374 // the first time, give a zero to allow
2375 // netdata calibrate to the current time
2376 // usec = update_every * USEC_PER_SEC;
2382 now_monotonic_timeval(&now);
2383 getrusage(RUSAGE_SELF, &me);
2385 usec = dt_usec(&now, &last);
2386 cpuuser = me.ru_utime.tv_sec * USEC_PER_SEC + me.ru_utime.tv_usec;
2387 cpusyst = me.ru_stime.tv_sec * USEC_PER_SEC + me.ru_stime.tv_usec;
2389 memmove(&last, &now, sizeof(struct timeval));
2390 memmove(&me_last, &me, sizeof(struct rusage));
2393 static char created_charts = 0;
2394 if(unlikely(!created_charts)) {
2398 , "CHART netdata.apps_cpu '' 'Apps Plugin CPU' 'milliseconds/s' apps.plugin netdata.apps_cpu stacked 140000 %1$d\n"
2399 "DIMENSION user '' incremental 1 1000\n"
2400 "DIMENSION system '' incremental 1 1000\n"
2401 "CHART netdata.apps_files '' 'Apps Plugin Files' 'files/s' apps.plugin netdata.apps_files line 140001 %1$d\n"
2402 "DIMENSION calls '' incremental 1 1\n"
2403 "DIMENSION files '' incremental 1 1\n"
2404 "DIMENSION pids '' absolute 1 1\n"
2405 "DIMENSION fds '' absolute 1 1\n"
2406 "DIMENSION targets '' absolute 1 1\n"
2407 "CHART netdata.apps_fix '' 'Apps Plugin Normalization Ratios' 'percentage' apps.plugin netdata.apps_fix line 140002 %1$d\n"
2408 "DIMENSION utime '' absolute 1 %2$llu\n"
2409 "DIMENSION stime '' absolute 1 %2$llu\n"
2410 "DIMENSION gtime '' absolute 1 %2$llu\n"
2411 "DIMENSION minflt '' absolute 1 %2$llu\n"
2412 "DIMENSION majflt '' absolute 1 %2$llu\n"
2417 if(include_exited_childs)
2419 , "CHART netdata.apps_children_fix '' 'Apps Plugin Exited Children Normalization Ratios' 'percentage' apps.plugin netdata.apps_children_fix line 140003 %1$d\n"
2420 "DIMENSION cutime '' absolute 1 %2$llu\n"
2421 "DIMENSION cstime '' absolute 1 %2$llu\n"
2422 "DIMENSION cgtime '' absolute 1 %2$llu\n"
2423 "DIMENSION cminflt '' absolute 1 %2$llu\n"
2424 "DIMENSION cmajflt '' absolute 1 %2$llu\n"
2431 "BEGIN netdata.apps_cpu %llu\n"
2433 "SET system = %llu\n"
2435 "BEGIN netdata.apps_files %llu\n"
2440 "SET targets = %zu\n"
2442 "BEGIN netdata.apps_fix %llu\n"
2457 , apps_groups_targets_count
2459 , (unsigned int)(utime_fix_ratio * 100 * RATES_DETAIL)
2460 , (unsigned int)(stime_fix_ratio * 100 * RATES_DETAIL)
2461 , (unsigned int)(gtime_fix_ratio * 100 * RATES_DETAIL)
2462 , (unsigned int)(minflt_fix_ratio * 100 * RATES_DETAIL)
2463 , (unsigned int)(majflt_fix_ratio * 100 * RATES_DETAIL)
2466 if(include_exited_childs)
2468 "BEGIN netdata.apps_children_fix %llu\n"
2472 "SET cminflt = %u\n"
2473 "SET cmajflt = %u\n"
2476 , (unsigned int)(cutime_fix_ratio * 100 * RATES_DETAIL)
2477 , (unsigned int)(cstime_fix_ratio * 100 * RATES_DETAIL)
2478 , (unsigned int)(cgtime_fix_ratio * 100 * RATES_DETAIL)
2479 , (unsigned int)(cminflt_fix_ratio * 100 * RATES_DETAIL)
2480 , (unsigned int)(cmajflt_fix_ratio * 100 * RATES_DETAIL)
2486 static void normalize_utilization(struct target *root) {
2489 // childs processing introduces spikes
2490 // here we try to eliminate them by disabling childs processing either for specific dimensions
2491 // or entirely. Of course, either way, we disable it just a single iteration.
2493 kernel_uint_t max_time = processors * hz * RATES_DETAIL;
2494 kernel_uint_t utime = 0, cutime = 0, stime = 0, cstime = 0, gtime = 0, cgtime = 0, minflt = 0, cminflt = 0, majflt = 0, cmajflt = 0;
2496 if(global_utime > max_time) global_utime = max_time;
2497 if(global_stime > max_time) global_stime = max_time;
2498 if(global_gtime > max_time) global_gtime = max_time;
2500 for(w = root; w ; w = w->next) {
2501 if(w->target || (!w->processes && !w->exposed)) continue;
2506 cutime += w->cutime;
2507 cstime += w->cstime;
2508 cgtime += w->cgtime;
2510 minflt += w->minflt;
2511 majflt += w->majflt;
2512 cminflt += w->cminflt;
2513 cmajflt += w->cmajflt;
2516 if((global_utime || global_stime || global_gtime) && (utime || stime || gtime)) {
2517 if(global_utime + global_stime + global_gtime > utime + cutime + stime + cstime + gtime + cgtime) {
2518 // everything we collected fits
2524 cgtime_fix_ratio = 1.0; //(double)(global_utime + global_stime) / (double)(utime + cutime + stime + cstime);
2526 else if(global_utime + global_stime > utime + stime) {
2527 // childrens resources are too high
2528 // lower only the children resources
2531 gtime_fix_ratio = 1.0;
2534 cgtime_fix_ratio = (double)((global_utime + global_stime) - (utime + stime)) / (double)(cutime + cstime);
2537 // even running processes are unrealistic
2538 // zero the children resources
2539 // lower the running processes resources
2542 gtime_fix_ratio = (double)(global_utime + global_stime) / (double)(utime + stime);
2545 cgtime_fix_ratio = 0.0;
2554 cgtime_fix_ratio = 0.0;
2557 if(utime_fix_ratio > 1.0) utime_fix_ratio = 1.0;
2558 if(cutime_fix_ratio > 1.0) cutime_fix_ratio = 1.0;
2559 if(stime_fix_ratio > 1.0) stime_fix_ratio = 1.0;
2560 if(cstime_fix_ratio > 1.0) cstime_fix_ratio = 1.0;
2561 if(gtime_fix_ratio > 1.0) gtime_fix_ratio = 1.0;
2562 if(cgtime_fix_ratio > 1.0) cgtime_fix_ratio = 1.0;
2564 // if(utime_fix_ratio < 0.0) utime_fix_ratio = 0.0;
2565 // if(cutime_fix_ratio < 0.0) cutime_fix_ratio = 0.0;
2566 // if(stime_fix_ratio < 0.0) stime_fix_ratio = 0.0;
2567 // if(cstime_fix_ratio < 0.0) cstime_fix_ratio = 0.0;
2568 // if(gtime_fix_ratio < 0.0) gtime_fix_ratio = 0.0;
2569 // if(cgtime_fix_ratio < 0.0) cgtime_fix_ratio = 0.0;
2572 // we use cpu time to normalize page faults
2573 // the problem is that to find the proper max values
2574 // for page faults we have to parse /proc/vmstat
2575 // which is quite big to do it again (netdata does it already)
2577 // a better solution could be to somehow have netdata
2578 // do this normalization for us
2580 if(utime || stime || gtime)
2582 minflt_fix_ratio = (double)(utime * utime_fix_ratio + stime * stime_fix_ratio + gtime * gtime_fix_ratio) / (double)(utime + stime + gtime);
2585 majflt_fix_ratio = 1.0;
2587 if(cutime || cstime || cgtime)
2589 cminflt_fix_ratio = (double)(cutime * cutime_fix_ratio + cstime * cstime_fix_ratio + cgtime * cgtime_fix_ratio) / (double)(cutime + cstime + cgtime);
2592 cmajflt_fix_ratio = 1.0;
2596 if(unlikely(debug)) {
2598 "SYSTEM: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
2599 "COLLECTED: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " cu=" KERNEL_UINT_FORMAT " cs=" KERNEL_UINT_FORMAT " cg=" KERNEL_UINT_FORMAT " "
2600 "DELTA: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
2601 "FIX: u=%0.2f s=%0.2f g=%0.2f cu=%0.2f cs=%0.2f cg=%0.2f "
2602 "FINALLY: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " cu=" KERNEL_UINT_FORMAT " cs=" KERNEL_UINT_FORMAT " cg=" KERNEL_UINT_FORMAT " "
2613 , utime + cutime - global_utime
2614 , stime + cstime - global_stime
2615 , gtime + cgtime - global_gtime
2622 , (kernel_uint_t)(utime * utime_fix_ratio)
2623 , (kernel_uint_t)(stime * stime_fix_ratio)
2624 , (kernel_uint_t)(gtime * gtime_fix_ratio)
2625 , (kernel_uint_t)(cutime * cutime_fix_ratio)
2626 , (kernel_uint_t)(cstime * cstime_fix_ratio)
2627 , (kernel_uint_t)(cgtime * cgtime_fix_ratio)
2632 static void send_collected_data_to_netdata(struct target *root, const char *type, usec_t usec) {
2635 send_BEGIN(type, "cpu", usec);
2636 for (w = root; w ; w = w->next) {
2637 if(unlikely(w->exposed))
2638 send_SET(w->name, (kernel_uint_t)(w->utime * utime_fix_ratio) + (kernel_uint_t)(w->stime * stime_fix_ratio) + (kernel_uint_t)(w->gtime * gtime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cutime * cutime_fix_ratio) + (kernel_uint_t)(w->cstime * cstime_fix_ratio) + (kernel_uint_t)(w->cgtime * cgtime_fix_ratio)):0ULL));
2642 send_BEGIN(type, "cpu_user", usec);
2643 for (w = root; w ; w = w->next) {
2644 if(unlikely(w->exposed))
2645 send_SET(w->name, (kernel_uint_t)(w->utime * utime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cutime * cutime_fix_ratio)):0ULL));
2649 send_BEGIN(type, "cpu_system", usec);
2650 for (w = root; w ; w = w->next) {
2651 if(unlikely(w->exposed))
2652 send_SET(w->name, (kernel_uint_t)(w->stime * stime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cstime * cstime_fix_ratio)):0ULL));
2656 if(show_guest_time) {
2657 send_BEGIN(type, "cpu_guest", usec);
2658 for (w = root; w ; w = w->next) {
2659 if(unlikely(w->exposed))
2660 send_SET(w->name, (kernel_uint_t)(w->gtime * gtime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cgtime * cgtime_fix_ratio)):0ULL));
2665 send_BEGIN(type, "threads", usec);
2666 for (w = root; w ; w = w->next) {
2667 if(unlikely(w->exposed))
2668 send_SET(w->name, w->num_threads);
2672 send_BEGIN(type, "processes", usec);
2673 for (w = root; w ; w = w->next) {
2674 if(unlikely(w->exposed))
2675 send_SET(w->name, w->processes);
2679 send_BEGIN(type, "mem", usec);
2680 for (w = root; w ; w = w->next) {
2681 if(unlikely(w->exposed))
2682 send_SET(w->name, (w->statm_resident > w->statm_share)?(w->statm_resident - w->statm_share):0ULL);
2686 send_BEGIN(type, "vmem", usec);
2687 for (w = root; w ; w = w->next) {
2688 if(unlikely(w->exposed))
2689 send_SET(w->name, w->statm_size);
2693 send_BEGIN(type, "minor_faults", usec);
2694 for (w = root; w ; w = w->next) {
2695 if(unlikely(w->exposed))
2696 send_SET(w->name, (kernel_uint_t)(w->minflt * minflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cminflt * cminflt_fix_ratio)):0ULL));
2700 send_BEGIN(type, "major_faults", usec);
2701 for (w = root; w ; w = w->next) {
2702 if(unlikely(w->exposed))
2703 send_SET(w->name, (kernel_uint_t)(w->majflt * majflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cmajflt * cmajflt_fix_ratio)):0ULL));
2707 send_BEGIN(type, "lreads", usec);
2708 for (w = root; w ; w = w->next) {
2709 if(unlikely(w->exposed))
2710 send_SET(w->name, w->io_logical_bytes_read);
2714 send_BEGIN(type, "lwrites", usec);
2715 for (w = root; w ; w = w->next) {
2716 if(unlikely(w->exposed))
2717 send_SET(w->name, w->io_logical_bytes_written);
2721 send_BEGIN(type, "preads", usec);
2722 for (w = root; w ; w = w->next) {
2723 if(unlikely(w->exposed))
2724 send_SET(w->name, w->io_storage_bytes_read);
2728 send_BEGIN(type, "pwrites", usec);
2729 for (w = root; w ; w = w->next) {
2730 if(unlikely(w->exposed))
2731 send_SET(w->name, w->io_storage_bytes_written);
2735 if(enable_file_charts) {
2736 send_BEGIN(type, "files", usec);
2737 for (w = root; w; w = w->next) {
2738 if (unlikely(w->exposed))
2739 send_SET(w->name, w->openfiles);
2743 send_BEGIN(type, "sockets", usec);
2744 for (w = root; w; w = w->next) {
2745 if (unlikely(w->exposed))
2746 send_SET(w->name, w->opensockets);
2750 send_BEGIN(type, "pipes", usec);
2751 for (w = root; w; w = w->next) {
2752 if (unlikely(w->exposed))
2753 send_SET(w->name, w->openpipes);
2760 // ----------------------------------------------------------------------------
2761 // generate the charts
2763 static void send_charts_updates_to_netdata(struct target *root, const char *type, const char *title)
2766 int newly_added = 0;
2768 for(w = root ; w ; w = w->next) {
2769 if (w->target) continue;
2771 if (!w->exposed && w->processes) {
2774 if (debug || w->debug) fprintf(stderr, "apps.plugin: %s just added - regenerating charts.\n", w->name);
2778 // nothing more to show
2779 if(!newly_added && show_guest_time == show_guest_time_old) return;
2781 // we have something new to show
2782 // update the charts
2783 fprintf(stdout, "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);
2784 for (w = root; w ; w = w->next) {
2785 if(unlikely(w->exposed))
2786 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu %s\n", w->name, hz * RATES_DETAIL / 100, w->hidden ? "hidden" : "");
2789 fprintf(stdout, "CHART %s.mem '' '%s Real Memory (w/o shared)' 'MB' mem %s.mem stacked 20003 %d\n", type, title, type, update_every);
2790 for (w = root; w ; w = w->next) {
2791 if(unlikely(w->exposed))
2792 fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
2795 fprintf(stdout, "CHART %s.vmem '' '%s Virtual Memory Size' 'MB' mem %s.vmem stacked 20004 %d\n", type, title, type, update_every);
2796 for (w = root; w ; w = w->next) {
2797 if(unlikely(w->exposed))
2798 fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
2801 fprintf(stdout, "CHART %s.threads '' '%s Threads' 'threads' processes %s.threads stacked 20005 %d\n", type, title, type, update_every);
2802 for (w = root; w ; w = w->next) {
2803 if(unlikely(w->exposed))
2804 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
2807 fprintf(stdout, "CHART %s.processes '' '%s Processes' 'processes' processes %s.processes stacked 20004 %d\n", type, title, type, update_every);
2808 for (w = root; w ; w = w->next) {
2809 if(unlikely(w->exposed))
2810 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
2813 fprintf(stdout, "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);
2814 for (w = root; w ; w = w->next) {
2815 if(unlikely(w->exposed))
2816 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
2819 fprintf(stdout, "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);
2820 for (w = root; w ; w = w->next) {
2821 if(unlikely(w->exposed))
2822 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
2825 if(show_guest_time) {
2826 fprintf(stdout, "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);
2827 for (w = root; w; w = w->next) {
2828 if(unlikely(w->exposed))
2829 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
2833 fprintf(stdout, "CHART %s.major_faults '' '%s Major Page Faults (swap read)' 'page faults/s' swap %s.major_faults stacked 20010 %d\n", type, title, type, update_every);
2834 for (w = root; w ; w = w->next) {
2835 if(unlikely(w->exposed))
2836 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
2839 fprintf(stdout, "CHART %s.minor_faults '' '%s Minor Page Faults' 'page faults/s' mem %s.minor_faults stacked 20011 %d\n", type, title, type, update_every);
2840 for (w = root; w ; w = w->next) {
2841 if(unlikely(w->exposed))
2842 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
2845 fprintf(stdout, "CHART %s.lreads '' '%s Disk Logical Reads' 'kilobytes/s' disk %s.lreads stacked 20042 %d\n", type, title, type, update_every);
2846 for (w = root; w ; w = w->next) {
2847 if(unlikely(w->exposed))
2848 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
2851 fprintf(stdout, "CHART %s.lwrites '' '%s I/O Logical Writes' 'kilobytes/s' disk %s.lwrites stacked 20042 %d\n", type, title, type, update_every);
2852 for (w = root; w ; w = w->next) {
2853 if(unlikely(w->exposed))
2854 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
2857 fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'kilobytes/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
2858 for (w = root; w ; w = w->next) {
2859 if(unlikely(w->exposed))
2860 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
2863 fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'kilobytes/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
2864 for (w = root; w ; w = w->next) {
2865 if(unlikely(w->exposed))
2866 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
2869 if(enable_file_charts) {
2870 fprintf(stdout, "CHART %s.files '' '%s Open Files' 'open files' disk %s.files stacked 20050 %d\n", type,
2871 title, type, update_every);
2872 for (w = root; w; w = w->next) {
2873 if (unlikely(w->exposed))
2874 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
2877 fprintf(stdout, "CHART %s.sockets '' '%s Open Sockets' 'open sockets' net %s.sockets stacked 20051 %d\n",
2878 type, title, type, update_every);
2879 for (w = root; w; w = w->next) {
2880 if (unlikely(w->exposed))
2881 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
2884 fprintf(stdout, "CHART %s.pipes '' '%s Pipes' 'open pipes' processes %s.pipes stacked 20053 %d\n", type,
2885 title, type, update_every);
2886 for (w = root; w; w = w->next) {
2887 if (unlikely(w->exposed))
2888 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
2894 // ----------------------------------------------------------------------------
2895 // parse command line arguments
2897 int check_proc_1_io() {
2900 procfile *ff = procfile_open("/proc/1/io", NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
2901 if(!ff) goto cleanup;
2903 ff = procfile_readall(ff);
2904 if(!ff) goto cleanup;
2913 static void parse_args(int argc, char **argv)
2918 for(i = 1; i < argc; i++) {
2920 int n = (int)str2l(argv[i]);
2927 if(strcmp("version", argv[i]) == 0 || strcmp("-v", argv[i]) == 0) {
2928 printf("apps.plugin %s\n", VERSION);
2932 if(strcmp("test-permissions", argv[i]) == 0 || strcmp("-t", argv[i]) == 0) {
2933 if(!check_proc_1_io()) {
2934 perror("Tried to read /proc/1/io and it failed");
2941 if(strcmp("debug", argv[i]) == 0) {
2943 // debug_flags = 0xffffffff;
2947 if(strcmp("no-childs", argv[i]) == 0 || strcmp("without-childs", argv[i]) == 0) {
2948 include_exited_childs = 0;
2952 if(strcmp("with-childs", argv[i]) == 0) {
2953 include_exited_childs = 1;
2957 if(strcmp("with-guest", argv[i]) == 0) {
2958 enable_guest_charts = 1;
2962 if(strcmp("no-guest", argv[i]) == 0 || strcmp("without-guest", argv[i]) == 0) {
2963 enable_guest_charts = 0;
2967 if(strcmp("with-files", argv[i]) == 0) {
2968 enable_file_charts = 1;
2972 if(strcmp("no-files", argv[i]) == 0 || strcmp("without-files", argv[i]) == 0) {
2973 enable_file_charts = 0;
2977 if(strcmp("no-users", argv[i]) == 0 || strcmp("without-users", argv[i]) == 0) {
2978 enable_users_charts = 0;
2982 if(strcmp("no-groups", argv[i]) == 0 || strcmp("without-groups", argv[i]) == 0) {
2983 enable_groups_charts = 0;
2987 if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0) {
2990 " netdata apps.plugin %s\n"
2991 " Copyright (C) 2016-2017 Costa Tsaousis <costa@tsaousis.gr>\n"
2992 " Released under GNU General Public License v3 or later.\n"
2993 " All rights reserved.\n"
2995 " This program is a data collector plugin for netdata.\n"
2997 " Valid command line options:\n"
2999 " SECONDS set the data collection frequency\n"
3001 " debug enable debugging (lot of output)\n"
3004 " without-childs enable / disable aggregating exited\n"
3005 " children resources into parents\n"
3006 " (default is enabled)\n"
3009 " without-guest enable / disable reporting guest charts\n"
3010 " (default is disabled)\n"
3013 " without-files enable / disable reporting files, sockets, pipes\n"
3014 " (default is enabled)\n"
3016 " NAME read apps_NAME.conf instead of\n"
3017 " apps_groups.conf\n"
3018 " (default NAME=groups)\n"
3020 " version print program version and exit\n"
3032 error("Cannot understand option %s", argv[i]);
3036 if(freq > 0) update_every = freq;
3037 if(!name) name = "groups";
3039 if(read_apps_groups_conf(name)) {
3040 error("Cannot read process groups '%s/apps_%s.conf'. There are no internal defaults. Failing.", config_dir, name);
3045 static int am_i_running_as_root() {
3046 uid_t uid = getuid(), euid = geteuid();
3048 if(uid == 0 || euid == 0) {
3049 if(debug) info("I am running with escalated privileges, uid = %u, euid = %u.", uid, euid);
3053 if(debug) info("I am not running with escalated privileges, uid = %u, euid = %u.", uid, euid);
3057 #ifdef HAVE_CAPABILITY
3058 static int check_capabilities() {
3059 cap_t caps = cap_get_proc();
3061 error("Cannot get current capabilities.");
3065 info("Received my capabilities from the system.");
3069 cap_flag_value_t cfv = CAP_CLEAR;
3070 if(cap_get_flag(caps, CAP_DAC_READ_SEARCH, CAP_EFFECTIVE, &cfv) == -1) {
3071 error("Cannot find if CAP_DAC_READ_SEARCH is effective.");
3075 if(cfv != CAP_SET) {
3076 error("apps.plugin should run with CAP_DAC_READ_SEARCH.");
3080 info("apps.plugin runs with CAP_DAC_READ_SEARCH.");
3084 if(cap_get_flag(caps, CAP_SYS_PTRACE, CAP_EFFECTIVE, &cfv) == -1) {
3085 error("Cannot find if CAP_SYS_PTRACE is effective.");
3089 if(cfv != CAP_SET) {
3090 error("apps.plugin should run with CAP_SYS_PTRACE.");
3094 info("apps.plugin runs with CAP_SYS_PTRACE.");
3102 static int check_capabilities() {
3107 int main(int argc, char **argv) {
3108 // debug_flags = D_PROCFILE;
3110 // set the name for logging
3111 program_name = "apps.plugin";
3113 // disable syslog for apps.plugin
3114 error_log_syslog = 0;
3116 // set errors flood protection to 100 logs per hour
3117 error_log_errors_per_period = 100;
3118 error_log_throttle_period = 3600;
3120 netdata_configured_host_prefix = getenv("NETDATA_HOST_PREFIX");
3121 if(netdata_configured_host_prefix == NULL) {
3122 // info("NETDATA_HOST_PREFIX is not passed from netdata");
3123 netdata_configured_host_prefix = "";
3125 // else info("Found NETDATA_HOST_PREFIX='%s'", netdata_configured_host_prefix);
3127 config_dir = getenv("NETDATA_CONFIG_DIR");
3128 if(config_dir == NULL) {
3129 // info("NETDATA_CONFIG_DIR is not passed from netdata");
3130 config_dir = CONFIG_DIR;
3132 // else info("Found NETDATA_CONFIG_DIR='%s'", config_dir);
3134 #ifdef NETDATA_INTERNAL_CHECKS
3135 if(debug_flags != 0) {
3136 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
3137 if(setrlimit(RLIMIT_CORE, &rl) != 0)
3138 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
3139 #ifdef HAVE_SYS_PRCTL_H
3140 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
3143 #endif /* NETDATA_INTERNAL_CHECKS */
3145 procfile_adaptive_initial_allocation = 1;
3147 time_t started_t = now_monotonic_sec();
3149 get_system_pid_max();
3152 parse_args(argc, argv);
3154 if(!check_capabilities() && !am_i_running_as_root() && !check_proc_1_io()) {
3155 uid_t uid = getuid(), euid = geteuid();
3156 #ifdef HAVE_CAPABILITY
3157 error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
3158 "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
3159 "To enable capabilities run: sudo setcap cap_dac_read_search,cap_sys_ptrace+ep %s; "
3160 "To enable setuid to root run: sudo chown root %s; sudo chmod 4755 %s; "
3161 , uid, euid, argv[0], argv[0], argv[0]
3164 error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
3165 "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
3166 "Your system does not support capabilities. "
3167 "To enable setuid to root run: sudo chown root %s; sudo chmod 4755 %s; "
3168 , uid, euid, argv[0], argv[0]
3173 info("started on pid %d", getpid());
3175 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
3176 all_pids_sortlist = callocz(sizeof(pid_t), (size_t)pid_max);
3179 all_pids = callocz(sizeof(struct pid_stat *), (size_t) pid_max);
3181 usec_t step = update_every * USEC_PER_SEC;
3182 global_iterations_counter = 1;
3184 heartbeat_init(&hb);
3185 for(;1; global_iterations_counter++) {
3187 #ifdef NETDATA_PROFILING
3188 #warning "compiling for profiling"
3189 static int profiling_count=0;
3191 if(unlikely(profiling_count > 1000)) exit(0);
3193 heartbeat_next(&hb, step);
3196 if(!collect_data_for_all_processes()) {
3197 error("Cannot collect /proc data for running processes. Disabling apps.plugin...");
3198 printf("DISABLE\n");
3202 calculate_netdata_statistics();
3203 normalize_utilization(apps_groups_root_target);
3205 usec_t dt = send_resource_usage_to_netdata();
3207 // this is smart enough to show only newly added apps, when needed
3208 send_charts_updates_to_netdata(apps_groups_root_target, "apps", "Apps");
3210 if(likely(enable_users_charts))
3211 send_charts_updates_to_netdata(users_root_target, "users", "Users");
3213 if(likely(enable_groups_charts))
3214 send_charts_updates_to_netdata(groups_root_target, "groups", "User Groups");
3216 send_collected_data_to_netdata(apps_groups_root_target, "apps", dt);
3218 if(likely(enable_users_charts))
3219 send_collected_data_to_netdata(users_root_target, "users", dt);
3221 if(likely(enable_groups_charts))
3222 send_collected_data_to_netdata(groups_root_target, "groups", dt);
3226 show_guest_time_old = show_guest_time;
3229 fprintf(stderr, "apps.plugin: done Loop No %zu\n", global_iterations_counter);
3231 // restart check (14400 seconds)
3232 if(now_monotonic_sec() - started_t > 14400) exit(0);