4 * (C) Copyright 2016-2017 Costa Tsaousis <costa@tsaousis.gr>
5 * Released under GPL v3+
14 // ----------------------------------------------------------------------------
15 // per O/S configuration
17 // the minimum PID of the system
18 // this is also the pid of the init process
21 // if the way apps.plugin will work, will read the entire process list,
22 // including the resource utilization of each process, instantly
24 // when set to 0, apps.plugin builds a sort list of processes, in order
25 // to process children processes, before parent processes
27 #define ALL_PIDS_ARE_READ_INSTANTLY 1
29 #define ALL_PIDS_ARE_READ_INSTANTLY 0
32 // ----------------------------------------------------------------------------
35 #define MAX_COMPARE_NAME 100
37 #define MAX_CMDLINE 1024
40 // ----------------------------------------------------------------------------
41 // the rates we are going to send to netdata will have this detail a value of:
42 // - 1 will send just integer parts to netdata
43 // - 100 will send 2 decimal points
44 // - 1000 will send 3 decimal points
46 #define RATES_DETAIL 10000ULL
49 // ----------------------------------------------------------------------------
50 // to avoid reallocating too frequently, we can increase the number of spare
51 // file descriptors used by processes.
53 // having a lot of spares, increases the CPU utilization of the plugin.
54 #define MAX_SPARE_FDS 1
57 // ----------------------------------------------------------------------------
58 // command line options
63 enable_guest_charts = 0,
64 enable_file_charts = 1,
65 enable_users_charts = 1,
66 enable_groups_charts = 1,
67 include_exited_childs = 1;
70 // will be changed to getenv(NETDATA_CONFIG_DIR) if it exists
71 static char *config_dir = CONFIG_DIR;
73 // ----------------------------------------------------------------------------
75 // handled in code (automatically set)
78 show_guest_time = 0, // 1 when guest values are collected
79 show_guest_time_old = 0,
80 proc_pid_cmdline_is_needed = 0; // 1 when we need to read /proc/cmdline
83 // ----------------------------------------------------------------------------
87 global_iterations_counter = 1,
92 // ----------------------------------------------------------------------------
95 // With normalization we lower the collected metrics by a factor to make them
96 // match the total utilization of the system.
97 // The discrepancy exists because apps.plugin needs some time to collect all
98 // the metrics. This results in utilization that exceeds the total utilization
101 // With normalization we align the per-process utilization, to the total of
102 // the system. We first consume the exited children utilization and it the
103 // collected values is above the total, we proportionally scale each reported
106 // the total system time, as reported by /proc/stat
113 // the normalization ratios, as calculated by normalize_utilization()
114 double utime_fix_ratio = 1.0,
115 stime_fix_ratio = 1.0,
116 gtime_fix_ratio = 1.0,
117 minflt_fix_ratio = 1.0,
118 majflt_fix_ratio = 1.0,
119 cutime_fix_ratio = 1.0,
120 cstime_fix_ratio = 1.0,
121 cgtime_fix_ratio = 1.0,
122 cminflt_fix_ratio = 1.0,
123 cmajflt_fix_ratio = 1.0;
126 // ----------------------------------------------------------------------------
129 // target is the structure that processes are aggregated to be reported
132 // - Each entry in /etc/apps_groups.conf creates a target.
133 // - Each user and group used by a process in the system, creates a target.
136 char compare[MAX_COMPARE_NAME + 1];
137 uint32_t comparehash;
140 char id[MAX_NAME + 1];
143 char name[MAX_NAME + 1];
148 kernel_uint_t minflt;
149 kernel_uint_t cminflt;
150 kernel_uint_t majflt;
151 kernel_uint_t cmajflt;
155 kernel_uint_t cutime;
156 kernel_uint_t cstime;
157 kernel_uint_t cgtime;
158 kernel_uint_t num_threads;
159 // kernel_uint_t rss;
161 kernel_uint_t statm_size;
162 kernel_uint_t statm_resident;
163 kernel_uint_t statm_share;
164 // kernel_uint_t statm_text;
165 // kernel_uint_t statm_lib;
166 // kernel_uint_t statm_data;
167 // kernel_uint_t statm_dirty;
169 kernel_uint_t io_logical_bytes_read;
170 kernel_uint_t io_logical_bytes_written;
171 // kernel_uint_t io_read_calls;
172 // kernel_uint_t io_write_calls;
173 kernel_uint_t io_storage_bytes_read;
174 kernel_uint_t io_storage_bytes_written;
175 // kernel_uint_t io_cancelled_write_bytes;
180 kernel_uint_t openfiles;
181 kernel_uint_t openpipes;
182 kernel_uint_t opensockets;
183 kernel_uint_t openinotifies;
184 kernel_uint_t openeventfds;
185 kernel_uint_t opentimerfds;
186 kernel_uint_t opensignalfds;
187 kernel_uint_t openeventpolls;
188 kernel_uint_t openother;
190 unsigned int processes; // how many processes have been merged to this
191 int exposed; // if set, we have sent this to netdata
192 int hidden; // if set, we set the hidden flag on the dimension
195 int starts_with; // if set, the compare string matches only the
196 // beginning of the command
198 struct target *target; // the one that will be reported to netdata
203 *apps_groups_default_target = NULL, // the default target
204 *apps_groups_root_target = NULL, // apps_groups.conf defined
205 *users_root_target = NULL, // users
206 *groups_root_target = NULL; // user groups
209 apps_groups_targets_count = 0; // # of apps_groups.conf targets
212 // ----------------------------------------------------------------------------
215 // structure to store data for each process running
216 // see: man proc for the description of the fields
220 char comm[MAX_COMPARE_NAME + 1];
221 char cmdline[MAX_CMDLINE + 1];
233 // these are raw values collected
234 kernel_uint_t minflt_raw;
235 kernel_uint_t cminflt_raw;
236 kernel_uint_t majflt_raw;
237 kernel_uint_t cmajflt_raw;
238 kernel_uint_t utime_raw;
239 kernel_uint_t stime_raw;
240 kernel_uint_t gtime_raw; // guest_time
241 kernel_uint_t cutime_raw;
242 kernel_uint_t cstime_raw;
243 kernel_uint_t cgtime_raw; // cguest_time
246 kernel_uint_t minflt;
247 kernel_uint_t cminflt;
248 kernel_uint_t majflt;
249 kernel_uint_t cmajflt;
253 kernel_uint_t cutime;
254 kernel_uint_t cstime;
255 kernel_uint_t cgtime;
260 // int64_t itrealvalue;
261 // kernel_uint_t starttime;
262 // kernel_uint_t vsize;
263 // kernel_uint_t rss;
264 // kernel_uint_t rsslim;
265 // kernel_uint_t starcode;
266 // kernel_uint_t endcode;
267 // kernel_uint_t startstack;
268 // kernel_uint_t kstkesp;
269 // kernel_uint_t kstkeip;
272 // uint64_t sigignore;
273 // uint64_t sigcatch;
277 // int32_t exit_signal;
278 // int32_t processor;
279 // uint32_t rt_priority;
281 // kernel_uint_t delayacct_blkio_ticks;
286 kernel_uint_t statm_size;
287 kernel_uint_t statm_resident;
288 kernel_uint_t statm_share;
289 // kernel_uint_t statm_text;
290 // kernel_uint_t statm_lib;
291 // kernel_uint_t statm_data;
292 // kernel_uint_t statm_dirty;
294 kernel_uint_t io_logical_bytes_read_raw;
295 kernel_uint_t io_logical_bytes_written_raw;
296 // kernel_uint_t io_read_calls_raw;
297 // kernel_uint_t io_write_calls_raw;
298 kernel_uint_t io_storage_bytes_read_raw;
299 kernel_uint_t io_storage_bytes_written_raw;
300 // kernel_uint_t io_cancelled_write_bytes_raw;
302 kernel_uint_t io_logical_bytes_read;
303 kernel_uint_t io_logical_bytes_written;
304 // kernel_uint_t io_read_calls;
305 // kernel_uint_t io_write_calls;
306 kernel_uint_t io_storage_bytes_read;
307 kernel_uint_t io_storage_bytes_written;
308 // kernel_uint_t io_cancelled_write_bytes;
310 int *fds; // array of fds it uses
311 int fds_size; // the size of the fds array
313 int children_count; // number of processes directly referencing this
314 char keep:1; // 1 when we need to keep this process in memory even after it exited
315 int keeploops; // increases by 1 every time keep is 1 and updated 0
316 char updated:1; // 1 when the process is currently running
317 char merged:1; // 1 when it has been merged to its parent
318 char read:1; // 1 when we have already read this process for this iteration
320 int sortlist; // higher numbers = top on the process tree
321 // each process gets a unique number
323 struct target *target; // app_groups.conf targets
324 struct target *user_target; // uid based targets
325 struct target *group_target; // gid based targets
327 usec_t stat_collected_usec;
328 usec_t last_stat_collected_usec;
330 usec_t io_collected_usec;
331 usec_t last_io_collected_usec;
333 char *fds_dirname; // the full directory name in /proc/PID/fd
336 char *statm_filename;
338 char *cmdline_filename;
340 struct pid_stat *parent;
341 struct pid_stat *prev;
342 struct pid_stat *next;
345 // log each problem once per process
346 // log flood protection flags (log_thrown)
347 #define PID_LOG_IO 0x00000001
348 #define PID_LOG_STATM 0x00000002
349 #define PID_LOG_CMDLINE 0x00000004
350 #define PID_LOG_FDS 0x00000008
351 #define PID_LOG_STAT 0x00000010
353 static struct pid_stat
354 *root_of_pids = NULL, // global list of all processes running
355 **all_pids = NULL; // to avoid allocations, we pre-allocate the
356 // the entire pid space.
359 all_pids_count = 0; // the number of processes running
361 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
362 // Another pre-allocated list of all possible pids.
363 // We need it to pids and assign them a unique sortlist id, so that we
364 // read parents before children. This is needed to prevent a situation where
365 // a child is found running, but until we read its parent, it has exited and
366 // its parent has accumulated its resources.
368 *all_pids_sortlist = NULL;
371 // ----------------------------------------------------------------------------
374 // this is used to keep a global list of all open files of the system.
375 // it is needed in order to calculate the unique files processes have open.
377 #define FILE_DESCRIPTORS_INCREASE_STEP 100
379 // types for struct file_descriptor->type
380 typedef enum fd_filetype {
392 struct file_descriptor {
395 #ifdef NETDATA_INTERNAL_CHECKS
397 #endif /* NETDATA_INTERNAL_CHECKS */
411 // ----------------------------------------------------------------------------
412 // callback required by fatal()
414 void netdata_cleanup_and_exit(int ret) {
418 // ----------------------------------------------------------------------------
420 // aggregate all processes in groups, to have a limited number of dimensions
422 static struct target *get_users_target(uid_t uid) {
424 for(w = users_root_target ; w ; w = w->next)
425 if(w->uid == uid) return w;
427 w = callocz(sizeof(struct target), 1);
428 snprintfz(w->compare, MAX_COMPARE_NAME, "%u", uid);
429 w->comparehash = simple_hash(w->compare);
430 w->comparelen = strlen(w->compare);
432 snprintfz(w->id, MAX_NAME, "%u", uid);
433 w->idhash = simple_hash(w->id);
435 struct passwd *pw = getpwuid(uid);
437 snprintfz(w->name, MAX_NAME, "%u", uid);
439 snprintfz(w->name, MAX_NAME, "%s", pw->pw_name);
441 netdata_fix_chart_name(w->name);
445 w->next = users_root_target;
446 users_root_target = w;
449 fprintf(stderr, "apps.plugin: added uid %u ('%s') target\n", w->uid, w->name);
454 struct target *get_groups_target(gid_t gid)
457 for(w = groups_root_target ; w ; w = w->next)
458 if(w->gid == gid) return w;
460 w = callocz(sizeof(struct target), 1);
461 snprintfz(w->compare, MAX_COMPARE_NAME, "%u", gid);
462 w->comparehash = simple_hash(w->compare);
463 w->comparelen = strlen(w->compare);
465 snprintfz(w->id, MAX_NAME, "%u", gid);
466 w->idhash = simple_hash(w->id);
468 struct group *gr = getgrgid(gid);
470 snprintfz(w->name, MAX_NAME, "%u", gid);
472 snprintfz(w->name, MAX_NAME, "%s", gr->gr_name);
474 netdata_fix_chart_name(w->name);
478 w->next = groups_root_target;
479 groups_root_target = w;
482 fprintf(stderr, "apps.plugin: added gid %u ('%s') target\n", w->gid, w->name);
487 // find or create a new target
488 // there are targets that are just aggregated to other target (the second argument)
489 static struct target *get_apps_groups_target(const char *id, struct target *target, const char *name) {
490 int tdebug = 0, thidden = target?target->hidden:0, ends_with = 0;
491 const char *nid = id;
493 // extract the options
494 while(nid[0] == '-' || nid[0] == '+' || nid[0] == '*') {
495 if(nid[0] == '-') thidden = 1;
496 if(nid[0] == '+') tdebug = 1;
497 if(nid[0] == '*') ends_with = 1;
500 uint32_t hash = simple_hash(id);
502 // find if it already exists
503 struct target *w, *last = apps_groups_root_target;
504 for(w = apps_groups_root_target ; w ; w = w->next) {
505 if(w->idhash == hash && strncmp(nid, w->id, MAX_NAME) == 0)
511 // find an existing target
512 if(unlikely(!target)) {
513 while(*name == '-') {
514 if(*name == '-') thidden = 1;
518 for(target = apps_groups_root_target ; target != NULL ; target = target->next) {
519 if(!target->target && strcmp(name, target->name) == 0)
523 if(unlikely(debug)) {
525 fprintf(stderr, "apps.plugin: REUSING TARGET NAME '%s' on ID '%s'\n", target->name, target->id);
527 fprintf(stderr, "apps.plugin: NEW TARGET NAME '%s' on ID '%s'\n", name, id);
531 if(target && target->target)
532 fatal("Internal Error: request to link process '%s' to target '%s' which is linked to target '%s'", id, target->id, target->target->id);
534 w = callocz(sizeof(struct target), 1);
535 strncpyz(w->id, nid, MAX_NAME);
536 w->idhash = simple_hash(w->id);
538 if(unlikely(!target))
540 strncpyz(w->name, name, MAX_NAME);
543 strncpyz(w->name, nid, MAX_NAME);
545 strncpyz(w->compare, nid, MAX_COMPARE_NAME);
546 size_t len = strlen(w->compare);
547 if(w->compare[len - 1] == '*') {
548 w->compare[len - 1] = '\0';
551 w->ends_with = ends_with;
553 if(w->starts_with && w->ends_with)
554 proc_pid_cmdline_is_needed = 1;
556 w->comparehash = simple_hash(w->compare);
557 w->comparelen = strlen(w->compare);
563 // append it, to maintain the order in apps_groups.conf
564 if(last) last->next = w;
565 else apps_groups_root_target = w;
568 fprintf(stderr, "apps.plugin: ADDING TARGET ID '%s', process name '%s' (%s), aggregated on target '%s', options: %s %s\n"
570 , w->compare, (w->starts_with && w->ends_with)?"substring":((w->starts_with)?"prefix":((w->ends_with)?"suffix":"exact"))
571 , w->target?w->target->name:w->name
572 , (w->hidden)?"hidden":"-"
573 , (w->debug)?"debug":"-"
579 // read the apps_groups.conf file
580 static int read_apps_groups_conf(const char *file)
582 char filename[FILENAME_MAX + 1];
584 snprintfz(filename, FILENAME_MAX, "%s/apps_%s.conf", config_dir, file);
587 fprintf(stderr, "apps.plugin: process groups file: '%s'\n", filename);
589 // ----------------------------------------
591 procfile *ff = procfile_open(filename, " :\t", PROCFILE_FLAG_DEFAULT);
594 procfile_set_quotes(ff, "'\"");
596 ff = procfile_readall(ff);
600 size_t line, lines = procfile_lines(ff);
602 for(line = 0; line < lines ;line++) {
603 size_t word, words = procfile_linewords(ff, line);
606 char *name = procfile_lineword(ff, line, 0);
607 if(!name || !*name) continue;
609 // find a possibly existing target
610 struct target *w = NULL;
612 // loop through all words, skipping the first one (the name)
613 for(word = 0; word < words ;word++) {
614 char *s = procfile_lineword(ff, line, word);
615 if(!s || !*s) continue;
618 // is this the first word? skip it
619 if(s == name) continue;
622 struct target *n = get_apps_groups_target(s, w, name);
624 error("Cannot create target '%s' (line %zu, word %zu)", s, line, word);
628 // just some optimization
629 // to avoid searching for a target for each process
630 if(!w) w = n->target?n->target:n;
636 apps_groups_default_target = get_apps_groups_target("p+!o@w#e$i^r&7*5(-i)l-o_", NULL, "other"); // match nothing
637 if(!apps_groups_default_target)
638 fatal("Cannot create default target");
640 // allow the user to override group 'other'
641 if(apps_groups_default_target->target)
642 apps_groups_default_target = apps_groups_default_target->target;
648 // ----------------------------------------------------------------------------
649 // struct pid_stat management
651 static inline struct pid_stat *get_pid_entry(pid_t pid) {
652 if(unlikely(all_pids[pid]))
653 return all_pids[pid];
655 struct pid_stat *p = callocz(sizeof(struct pid_stat), 1);
656 p->fds = callocz(sizeof(int), MAX_SPARE_FDS);
657 p->fds_size = MAX_SPARE_FDS;
659 if(likely(root_of_pids))
660 root_of_pids->prev = p;
662 p->next = root_of_pids;
673 static inline void del_pid_entry(pid_t pid) {
674 struct pid_stat *p = all_pids[pid];
677 error("attempted to free pid %d that is not allocated.", pid);
682 fprintf(stderr, "apps.plugin: process %d %s exited, deleting it.\n", pid, p->comm);
684 if(root_of_pids == p)
685 root_of_pids = p->next;
687 if(p->next) p->next->prev = p->prev;
688 if(p->prev) p->prev->next = p->next;
691 freez(p->fds_dirname);
692 freez(p->stat_filename);
693 freez(p->statm_filename);
694 freez(p->io_filename);
695 freez(p->cmdline_filename);
698 all_pids[pid] = NULL;
702 // ----------------------------------------------------------------------------
704 static inline int managed_log(struct pid_stat *p, uint32_t log, int status) {
705 if(unlikely(!status)) {
706 // error("command failed log %u, errno %d", log, errno);
708 if(unlikely(debug || errno != ENOENT)) {
709 if(unlikely(debug || !(p->log_thrown & log))) {
710 p->log_thrown |= log;
713 error("Cannot process %s/proc/%d/io (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
717 error("Cannot process %s/proc/%d/statm (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
720 case PID_LOG_CMDLINE:
721 error("Cannot process %s/proc/%d/cmdline (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
725 error("Cannot process entries in %s/proc/%d/fd (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
732 error("unhandled error for pid %d, command '%s'", p->pid, p->comm);
739 else if(unlikely(p->log_thrown & log)) {
740 // error("unsetting log %u on pid %d", log, p->pid);
741 p->log_thrown &= ~log;
747 static inline void assign_target_to_pid(struct pid_stat *p) {
748 uint32_t hash = simple_hash(p->comm);
749 size_t pclen = strlen(p->comm);
752 for(w = apps_groups_root_target; w ; w = w->next) {
753 // if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \t\tcomparing '%s' with '%s'\n", w->compare, p->comm);
755 // find it - 4 cases:
756 // 1. the target is not a pattern
757 // 2. the target has the prefix
758 // 3. the target has the suffix
759 // 4. the target is something inside cmdline
761 if(unlikely(( (!w->starts_with && !w->ends_with && w->comparehash == hash && !strcmp(w->compare, p->comm))
762 || (w->starts_with && !w->ends_with && !strncmp(w->compare, p->comm, w->comparelen))
763 || (!w->starts_with && w->ends_with && pclen >= w->comparelen && !strcmp(w->compare, &p->comm[pclen - w->comparelen]))
764 || (proc_pid_cmdline_is_needed && w->starts_with && w->ends_with && strstr(p->cmdline, w->compare))
767 if(w->target) p->target = w->target;
770 if(debug || (p->target && p->target->debug))
771 fprintf(stderr, "apps.plugin: \t\t%s linked to target %s\n", p->comm, p->target->name);
779 // ----------------------------------------------------------------------------
780 // update pids from proc
782 static inline int read_proc_pid_cmdline(struct pid_stat *p) {
785 size_t i, bytes = MAX_CMDLINE;
790 mib[2] = KERN_PROC_ARGS;
792 if (unlikely(sysctl(mib, 4, p->cmdline, &bytes, NULL, 0)))
795 if(unlikely(!p->cmdline_filename)) {
796 char filename[FILENAME_MAX + 1];
797 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/cmdline", netdata_configured_host_prefix, p->pid);
798 p->cmdline_filename = strdupz(filename);
801 int fd = open(p->cmdline_filename, O_RDONLY, 0666);
802 if(unlikely(fd == -1)) goto cleanup;
804 ssize_t i, bytes = read(fd, p->cmdline, MAX_CMDLINE);
807 if(unlikely(bytes < 0)) goto cleanup;
810 p->cmdline[bytes] = '\0';
811 for(i = 0; i < bytes ; i++)
812 if(unlikely(!p->cmdline[i])) p->cmdline[i] = ' ';
815 fprintf(stderr, "Read file '%s' contents: %s\n", p->cmdline_filename, p->cmdline);
820 // copy the command to the command line
821 strncpyz(p->cmdline, p->comm, MAX_CMDLINE);
825 static inline int read_proc_pid_ownership(struct pid_stat *p, void *ptr) {
828 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
830 p->uid = proc_info->ki_uid;
831 p->gid = proc_info->ki_groups[0];
835 if(unlikely(!p->stat_filename)) {
836 error("pid %d does not have a stat_filename", p->pid);
840 // ----------------------------------------
844 if(stat(p->stat_filename, &st) != 0) {
845 error("Cannot stat file '%s'", p->stat_filename);
856 // ----------------------------------------------------------------------------
857 // macro to calculate the incremental rate of a value
858 // each parameter is accessed only ONCE - so it is safe to pass function calls
859 // or other macros as parameters
861 #define incremental_rate(rate_variable, last_kernel_variable, new_kernel_value, collected_usec, last_collected_usec) { \
862 kernel_uint_t _new_tmp = new_kernel_value; \
863 rate_variable = (_new_tmp - last_kernel_variable) * (USEC_PER_SEC * RATES_DETAIL) / (collected_usec - last_collected_usec); \
864 last_kernel_variable = _new_tmp; \
867 // the same macro for struct pid members
868 #define pid_incremental_rate(type, var, value) \
869 incremental_rate(var, var##_raw, value, p->type##_collected_usec, p->last_##type##_collected_usec)
872 // ----------------------------------------------------------------------------
874 static inline int read_proc_pid_stat(struct pid_stat *p, void *ptr) {
878 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
880 if (unlikely(proc_info->ki_tdflags & TDF_IDLETD))
883 static procfile *ff = NULL;
885 if(unlikely(!p->stat_filename)) {
886 char filename[FILENAME_MAX + 1];
887 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/stat", netdata_configured_host_prefix, p->pid);
888 p->stat_filename = strdupz(filename);
891 int set_quotes = (!ff)?1:0;
893 ff = procfile_reopen(ff, p->stat_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
894 if(unlikely(!ff)) goto cleanup;
896 // if(set_quotes) procfile_set_quotes(ff, "()");
897 if(unlikely(set_quotes))
898 procfile_set_open_close(ff, "(", ")");
900 ff = procfile_readall(ff);
901 if(unlikely(!ff)) goto cleanup;
904 p->last_stat_collected_usec = p->stat_collected_usec;
905 p->stat_collected_usec = now_monotonic_usec();
909 char *comm = proc_info->ki_comm;
910 p->ppid = proc_info->ki_ppid;
912 // p->pid = str2pid_t(procfile_lineword(ff, 0, 0));
913 char *comm = procfile_lineword(ff, 0, 1);
914 // p->state = *(procfile_lineword(ff, 0, 2));
915 p->ppid = (int32_t)str2pid_t(procfile_lineword(ff, 0, 3));
916 // p->pgrp = (int32_t)str2pid_t(procfile_lineword(ff, 0, 4));
917 // p->session = (int32_t)str2pid_t(procfile_lineword(ff, 0, 5));
918 // p->tty_nr = (int32_t)str2pid_t(procfile_lineword(ff, 0, 6));
919 // p->tpgid = (int32_t)str2pid_t(procfile_lineword(ff, 0, 7));
920 // p->flags = str2uint64_t(procfile_lineword(ff, 0, 8));
923 if(strcmp(p->comm, comm)) {
924 if(unlikely(debug)) {
926 fprintf(stderr, "apps.plugin: \tpid %d (%s) changed name to '%s'\n", p->pid, p->comm, comm);
928 fprintf(stderr, "apps.plugin: \tJust added %d (%s)\n", p->pid, comm);
931 strncpyz(p->comm, comm, MAX_COMPARE_NAME);
933 // /proc/<pid>/cmdline
934 if(likely(proc_pid_cmdline_is_needed))
935 managed_log(p, PID_LOG_CMDLINE, read_proc_pid_cmdline(p));
937 assign_target_to_pid(p);
941 pid_incremental_rate(stat, p->minflt, (kernel_uint_t)proc_info->ki_rusage.ru_minflt);
942 pid_incremental_rate(stat, p->cminflt, (kernel_uint_t)proc_info->ki_rusage_ch.ru_minflt);
943 pid_incremental_rate(stat, p->majflt, (kernel_uint_t)proc_info->ki_rusage.ru_majflt);
944 pid_incremental_rate(stat, p->cmajflt, (kernel_uint_t)proc_info->ki_rusage_ch.ru_majflt);
945 pid_incremental_rate(stat, p->utime, (kernel_uint_t)proc_info->ki_rusage.ru_utime.tv_sec * 100 + proc_info->ki_rusage.ru_utime.tv_usec / 10000);
946 pid_incremental_rate(stat, p->stime, (kernel_uint_t)proc_info->ki_rusage.ru_stime.tv_sec * 100 + proc_info->ki_rusage.ru_stime.tv_usec / 10000);
947 pid_incremental_rate(stat, p->cutime, (kernel_uint_t)proc_info->ki_rusage_ch.ru_utime.tv_sec * 100 + proc_info->ki_rusage_ch.ru_utime.tv_usec / 10000);
948 pid_incremental_rate(stat, p->cstime, (kernel_uint_t)proc_info->ki_rusage_ch.ru_stime.tv_sec * 100 + proc_info->ki_rusage_ch.ru_utime.tv_usec / 10000);
950 p->num_threads = proc_info->ki_numthreads;
952 if(enable_guest_charts) {
953 enable_guest_charts = 0;
954 info("Guest charts aren't supported by FreeBSD");
957 pid_incremental_rate(stat, p->minflt, str2kernel_uint_t(procfile_lineword(ff, 0, 9)));
958 pid_incremental_rate(stat, p->cminflt, str2kernel_uint_t(procfile_lineword(ff, 0, 10)));
959 pid_incremental_rate(stat, p->majflt, str2kernel_uint_t(procfile_lineword(ff, 0, 11)));
960 pid_incremental_rate(stat, p->cmajflt, str2kernel_uint_t(procfile_lineword(ff, 0, 12)));
961 pid_incremental_rate(stat, p->utime, str2kernel_uint_t(procfile_lineword(ff, 0, 13)));
962 pid_incremental_rate(stat, p->stime, str2kernel_uint_t(procfile_lineword(ff, 0, 14)));
963 pid_incremental_rate(stat, p->cutime, str2kernel_uint_t(procfile_lineword(ff, 0, 15)));
964 pid_incremental_rate(stat, p->cstime, str2kernel_uint_t(procfile_lineword(ff, 0, 16)));
965 // p->priority = str2kernel_uint_t(procfile_lineword(ff, 0, 17));
966 // p->nice = str2kernel_uint_t(procfile_lineword(ff, 0, 18));
967 p->num_threads = (int32_t)str2uint32_t(procfile_lineword(ff, 0, 19));
968 // p->itrealvalue = str2kernel_uint_t(procfile_lineword(ff, 0, 20));
969 // p->starttime = str2kernel_uint_t(procfile_lineword(ff, 0, 21));
970 // p->vsize = str2kernel_uint_t(procfile_lineword(ff, 0, 22));
971 // p->rss = str2kernel_uint_t(procfile_lineword(ff, 0, 23));
972 // p->rsslim = str2kernel_uint_t(procfile_lineword(ff, 0, 24));
973 // p->starcode = str2kernel_uint_t(procfile_lineword(ff, 0, 25));
974 // p->endcode = str2kernel_uint_t(procfile_lineword(ff, 0, 26));
975 // p->startstack = str2kernel_uint_t(procfile_lineword(ff, 0, 27));
976 // p->kstkesp = str2kernel_uint_t(procfile_lineword(ff, 0, 28));
977 // p->kstkeip = str2kernel_uint_t(procfile_lineword(ff, 0, 29));
978 // p->signal = str2kernel_uint_t(procfile_lineword(ff, 0, 30));
979 // p->blocked = str2kernel_uint_t(procfile_lineword(ff, 0, 31));
980 // p->sigignore = str2kernel_uint_t(procfile_lineword(ff, 0, 32));
981 // p->sigcatch = str2kernel_uint_t(procfile_lineword(ff, 0, 33));
982 // p->wchan = str2kernel_uint_t(procfile_lineword(ff, 0, 34));
983 // p->nswap = str2kernel_uint_t(procfile_lineword(ff, 0, 35));
984 // p->cnswap = str2kernel_uint_t(procfile_lineword(ff, 0, 36));
985 // p->exit_signal = str2kernel_uint_t(procfile_lineword(ff, 0, 37));
986 // p->processor = str2kernel_uint_t(procfile_lineword(ff, 0, 38));
987 // p->rt_priority = str2kernel_uint_t(procfile_lineword(ff, 0, 39));
988 // p->policy = str2kernel_uint_t(procfile_lineword(ff, 0, 40));
989 // p->delayacct_blkio_ticks = str2kernel_uint_t(procfile_lineword(ff, 0, 41));
991 if(enable_guest_charts) {
993 pid_incremental_rate(stat, p->gtime, str2kernel_uint_t(procfile_lineword(ff, 0, 42)));
994 pid_incremental_rate(stat, p->cgtime, str2kernel_uint_t(procfile_lineword(ff, 0, 43)));
996 if (show_guest_time || p->gtime || p->cgtime) {
997 p->utime -= (p->utime >= p->gtime) ? p->gtime : p->utime;
998 p->cutime -= (p->cutime >= p->cgtime) ? p->cgtime : p->cutime;
1004 if(unlikely(debug || (p->target && p->target->debug)))
1005 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);
1007 if(unlikely(global_iterations_counter == 1)) {
1038 static inline int read_proc_pid_statm(struct pid_stat *p, void *ptr) {
1041 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
1043 static procfile *ff = NULL;
1045 if(unlikely(!p->statm_filename)) {
1046 char filename[FILENAME_MAX + 1];
1047 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/statm", netdata_configured_host_prefix, p->pid);
1048 p->statm_filename = strdupz(filename);
1051 ff = procfile_reopen(ff, p->statm_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
1052 if(unlikely(!ff)) goto cleanup;
1054 ff = procfile_readall(ff);
1055 if(unlikely(!ff)) goto cleanup;
1061 p->statm_size = proc_info->ki_size / sysconf(_SC_PAGESIZE);
1062 p->statm_resident = proc_info->ki_rssize;
1063 p->statm_share = 0; // do we have to use ru_ixrss here?
1065 p->statm_size = str2kernel_uint_t(procfile_lineword(ff, 0, 0));
1066 p->statm_resident = str2kernel_uint_t(procfile_lineword(ff, 0, 1));
1067 p->statm_share = str2kernel_uint_t(procfile_lineword(ff, 0, 2));
1068 // p->statm_text = str2kernel_uint_t(procfile_lineword(ff, 0, 3));
1069 // p->statm_lib = str2kernel_uint_t(procfile_lineword(ff, 0, 4));
1070 // p->statm_data = str2kernel_uint_t(procfile_lineword(ff, 0, 5));
1071 // p->statm_dirty = str2kernel_uint_t(procfile_lineword(ff, 0, 6));
1078 p->statm_resident = 0;
1080 // p->statm_text = 0;
1081 // p->statm_lib = 0;
1082 // p->statm_data = 0;
1083 // p->statm_dirty = 0;
1087 static inline int read_proc_pid_io(struct pid_stat *p, void *ptr) {
1090 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
1092 static procfile *ff = NULL;
1094 if(unlikely(!p->io_filename)) {
1095 char filename[FILENAME_MAX + 1];
1096 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/io", netdata_configured_host_prefix, p->pid);
1097 p->io_filename = strdupz(filename);
1101 ff = procfile_reopen(ff, p->io_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
1102 if(unlikely(!ff)) goto cleanup;
1104 ff = procfile_readall(ff);
1105 if(unlikely(!ff)) goto cleanup;
1110 p->last_io_collected_usec = p->io_collected_usec;
1111 p->io_collected_usec = now_monotonic_usec();
1114 pid_incremental_rate(io, p->io_storage_bytes_read, proc_info->ki_rusage.ru_inblock);
1115 pid_incremental_rate(io, p->io_storage_bytes_written, proc_info->ki_rusage.ru_oublock);
1117 pid_incremental_rate(io, p->io_logical_bytes_read, str2kernel_uint_t(procfile_lineword(ff, 0, 1)));
1118 pid_incremental_rate(io, p->io_logical_bytes_written, str2kernel_uint_t(procfile_lineword(ff, 1, 1)));
1119 // pid_incremental_rate(io, p->io_read_calls, str2kernel_uint_t(procfile_lineword(ff, 2, 1)));
1120 // pid_incremental_rate(io, p->io_write_calls, str2kernel_uint_t(procfile_lineword(ff, 3, 1)));
1121 pid_incremental_rate(io, p->io_storage_bytes_read, str2kernel_uint_t(procfile_lineword(ff, 4, 1)));
1122 pid_incremental_rate(io, p->io_storage_bytes_written, str2kernel_uint_t(procfile_lineword(ff, 5, 1)));
1123 // pid_incremental_rate(io, p->io_cancelled_write_bytes, str2kernel_uint_t(procfile_lineword(ff, 6, 1)));
1126 if(unlikely(global_iterations_counter == 1)) {
1127 p->io_logical_bytes_read = 0;
1128 p->io_logical_bytes_written = 0;
1129 // p->io_read_calls = 0;
1130 // p->io_write_calls = 0;
1131 p->io_storage_bytes_read = 0;
1132 p->io_storage_bytes_written = 0;
1133 // p->io_cancelled_write_bytes = 0;
1139 p->io_logical_bytes_read = 0;
1140 p->io_logical_bytes_written = 0;
1141 // p->io_read_calls = 0;
1142 // p->io_write_calls = 0;
1143 p->io_storage_bytes_read = 0;
1144 p->io_storage_bytes_written = 0;
1145 // p->io_cancelled_write_bytes = 0;
1149 static inline int read_proc_stat() {
1151 long cp_time[CPUSTATES];
1154 if (unlikely(CPUSTATES != 5)) {
1155 error("FREEBSD: There are %d CPU states (5 was expected)", CPUSTATES);
1158 if (unlikely(GETSYSCTL("kern.cp_time", cp_time))) goto cleanup;
1160 static char filename[FILENAME_MAX + 1] = "";
1161 static procfile *ff = NULL;
1163 static kernel_uint_t utime_raw = 0, stime_raw = 0, gtime_raw = 0, gntime_raw = 0, ntime_raw = 0;
1164 static usec_t collected_usec = 0, last_collected_usec = 0;
1168 snprintfz(filename, FILENAME_MAX, "%s/proc/stat", netdata_configured_host_prefix);
1169 ff = procfile_open(filename, " \t:", PROCFILE_FLAG_DEFAULT);
1170 if(unlikely(!ff)) goto cleanup;
1173 ff = procfile_readall(ff);
1174 if(unlikely(!ff)) goto cleanup;
1177 last_collected_usec = collected_usec;
1178 collected_usec = now_monotonic_usec();
1182 // temporary - it is added global_ntime;
1183 kernel_uint_t global_ntime = 0;
1186 incremental_rate(global_utime, utime_raw, cp_time[0], collected_usec, last_collected_usec);
1187 incremental_rate(global_ntime, ntime_raw, cp_time[1], collected_usec, last_collected_usec);
1188 incremental_rate(global_stime, stime_raw, cp_time[2], collected_usec, last_collected_usec);
1190 incremental_rate(global_utime, utime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 1)), collected_usec, last_collected_usec);
1191 incremental_rate(global_ntime, ntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 2)), collected_usec, last_collected_usec);
1192 incremental_rate(global_stime, stime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 3)), collected_usec, last_collected_usec);
1193 incremental_rate(global_gtime, gtime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 10)), collected_usec, last_collected_usec);
1196 global_utime += global_ntime;
1199 if(enable_guest_charts) {
1200 enable_guest_charts = 0;
1201 info("Guest charts aren't supported by FreeBSD");
1204 if(enable_guest_charts) {
1205 // temporary - it is added global_ntime;
1206 kernel_uint_t global_gntime = 0;
1208 // guest nice time, on guest time
1209 incremental_rate(global_gntime, gntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 11)), collected_usec, last_collected_usec);
1211 global_gtime += global_gntime;
1213 // remove guest time from user time
1214 global_utime -= (global_utime > global_gtime) ? global_gtime : global_utime;
1218 if(unlikely(global_iterations_counter == 1)) {
1234 // ----------------------------------------------------------------------------
1236 int file_descriptor_compare(void* a, void* b) {
1237 #ifdef NETDATA_INTERNAL_CHECKS
1238 if(((struct file_descriptor *)a)->magic != 0x0BADCAFE || ((struct file_descriptor *)b)->magic != 0x0BADCAFE)
1239 error("Corrupted index data detected. Please report this.");
1240 #endif /* NETDATA_INTERNAL_CHECKS */
1242 if(((struct file_descriptor *)a)->hash < ((struct file_descriptor *)b)->hash)
1245 else if(((struct file_descriptor *)a)->hash > ((struct file_descriptor *)b)->hash)
1249 return strcmp(((struct file_descriptor *)a)->name, ((struct file_descriptor *)b)->name);
1252 int file_descriptor_iterator(avl *a) { if(a) {}; return 0; }
1254 avl_tree all_files_index = {
1256 file_descriptor_compare
1259 static struct file_descriptor *file_descriptor_find(const char *name, uint32_t hash) {
1260 struct file_descriptor tmp;
1261 tmp.hash = (hash)?hash:simple_hash(name);
1265 #ifdef NETDATA_INTERNAL_CHECKS
1266 tmp.magic = 0x0BADCAFE;
1267 #endif /* NETDATA_INTERNAL_CHECKS */
1269 return (struct file_descriptor *)avl_search(&all_files_index, (avl *) &tmp);
1272 #define file_descriptor_add(fd) avl_insert(&all_files_index, (avl *)(fd))
1273 #define file_descriptor_remove(fd) avl_remove(&all_files_index, (avl *)(fd))
1275 // ----------------------------------------------------------------------------
1277 static inline void file_descriptor_not_used(int id)
1279 if(id > 0 && id < all_files_size) {
1281 #ifdef NETDATA_INTERNAL_CHECKS
1282 if(all_files[id].magic != 0x0BADCAFE) {
1283 error("Ignoring request to remove empty file id %d.", id);
1286 #endif /* NETDATA_INTERNAL_CHECKS */
1289 fprintf(stderr, "apps.plugin: decreasing slot %d (count = %d).\n", id, all_files[id].count);
1291 if(all_files[id].count > 0) {
1292 all_files[id].count--;
1294 if(!all_files[id].count) {
1296 fprintf(stderr, "apps.plugin: >> slot %d is empty.\n", id);
1298 if(unlikely(file_descriptor_remove(&all_files[id]) != (void *)&all_files[id]))
1299 error("INTERNAL ERROR: removal of unused fd from index, removed a different fd");
1301 #ifdef NETDATA_INTERNAL_CHECKS
1302 all_files[id].magic = 0x00000000;
1303 #endif /* NETDATA_INTERNAL_CHECKS */
1308 error("Request to decrease counter of fd %d (%s), while the use counter is 0", id, all_files[id].name);
1310 else error("Request to decrease counter of fd %d, which is outside the array size (1 to %d)", id, all_files_size);
1313 static inline void all_files_grow() {
1314 void *old = all_files;
1317 // there is no empty slot
1319 fprintf(stderr, "apps.plugin: extending fd array to %d entries\n", all_files_size + FILE_DESCRIPTORS_INCREASE_STEP);
1321 all_files = reallocz(all_files, (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP) * sizeof(struct file_descriptor));
1323 // if the address changed, we have to rebuild the index
1324 // since all pointers are now invalid
1326 if(unlikely(old && old != (void *)all_files)) {
1328 fprintf(stderr, "apps.plugin: >> re-indexing.\n");
1330 all_files_index.root = NULL;
1331 for(i = 0; i < all_files_size; i++) {
1332 if(!all_files[i].count) continue;
1333 if(unlikely(file_descriptor_add(&all_files[i]) != (void *)&all_files[i]))
1334 error("INTERNAL ERROR: duplicate indexing of fd during realloc.");
1338 fprintf(stderr, "apps.plugin: >> re-indexing done.\n");
1341 // initialize the newly added entries
1343 for(i = all_files_size; i < (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP); i++) {
1344 all_files[i].count = 0;
1345 all_files[i].name = NULL;
1346 #ifdef NETDATA_INTERNAL_CHECKS
1347 all_files[i].magic = 0x00000000;
1348 #endif /* NETDATA_INTERNAL_CHECKS */
1349 all_files[i].pos = i;
1352 if(unlikely(!all_files_size)) all_files_len = 1;
1353 all_files_size += FILE_DESCRIPTORS_INCREASE_STEP;
1356 static inline int file_descriptor_set_on_empty_slot(const char *name, uint32_t hash, FD_FILETYPE type) {
1357 // check we have enough memory to add it
1358 if(!all_files || all_files_len == all_files_size)
1362 fprintf(stderr, "apps.plugin: >> searching for empty slot.\n");
1364 // search for an empty slot
1366 static int last_pos = 0;
1368 for(i = 0, c = last_pos ; i < all_files_size ; i++, c++) {
1369 if(c >= all_files_size) c = 0;
1370 if(c == 0) continue;
1372 if(!all_files[c].count) {
1374 fprintf(stderr, "apps.plugin: >> Examining slot %d.\n", c);
1376 #ifdef NETDATA_INTERNAL_CHECKS
1377 if(all_files[c].magic == 0x0BADCAFE && all_files[c].name && file_descriptor_find(all_files[c].name, all_files[c].hash))
1378 error("fd on position %d is not cleared properly. It still has %s in it.\n", c, all_files[c].name);
1379 #endif /* NETDATA_INTERNAL_CHECKS */
1382 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);
1384 freez((void *)all_files[c].name);
1385 all_files[c].name = NULL;
1393 if(i == all_files_size) {
1394 fatal("We should find an empty slot, but there isn't any");
1397 // else we have an empty slot in 'c'
1400 fprintf(stderr, "apps.plugin: >> updating slot %d.\n", c);
1402 all_files[c].name = strdupz(name);
1403 all_files[c].hash = hash;
1404 all_files[c].type = type;
1405 all_files[c].pos = c;
1406 all_files[c].count = 1;
1407 #ifdef NETDATA_INTERNAL_CHECKS
1408 all_files[c].magic = 0x0BADCAFE;
1409 #endif /* NETDATA_INTERNAL_CHECKS */
1410 if(unlikely(file_descriptor_add(&all_files[c]) != (void *)&all_files[c]))
1411 error("INTERNAL ERROR: duplicate indexing of fd.");
1414 fprintf(stderr, "apps.plugin: using fd position %d (name: %s)\n", c, all_files[c].name);
1419 static inline int file_descriptor_find_or_add(const char *name)
1421 uint32_t hash = simple_hash(name);
1424 fprintf(stderr, "apps.plugin: adding or finding name '%s' with hash %u\n", name, hash);
1426 struct file_descriptor *fd = file_descriptor_find(name, hash);
1430 fprintf(stderr, "apps.plugin: >> found on slot %d\n", fd->pos);
1438 if(likely(name[0] == '/')) type = FILETYPE_FILE;
1439 else if(likely(strncmp(name, "pipe:", 5) == 0)) type = FILETYPE_PIPE;
1440 else if(likely(strncmp(name, "socket:", 7) == 0)) type = FILETYPE_SOCKET;
1441 else if(likely(strncmp(name, "anon_inode:", 11) == 0)) {
1442 const char *t = &name[11];
1444 if(strcmp(t, "inotify") == 0) type = FILETYPE_INOTIFY;
1445 else if(strcmp(t, "[eventfd]") == 0) type = FILETYPE_EVENTFD;
1446 else if(strcmp(t, "[eventpoll]") == 0) type = FILETYPE_EVENTPOLL;
1447 else if(strcmp(t, "[timerfd]") == 0) type = FILETYPE_TIMERFD;
1448 else if(strcmp(t, "[signalfd]") == 0) type = FILETYPE_SIGNALFD;
1451 fprintf(stderr, "apps.plugin: FIXME: unknown anonymous inode: %s\n", name);
1453 type = FILETYPE_OTHER;
1456 else if(likely(strcmp(name, "inotify") == 0)) type = FILETYPE_INOTIFY;
1459 fprintf(stderr, "apps.plugin: FIXME: cannot understand linkname: %s\n", name);
1461 type = FILETYPE_OTHER;
1464 return file_descriptor_set_on_empty_slot(name, hash, type);
1467 static inline void make_all_pid_fds_negative(struct pid_stat *p) {
1468 int *fd = p->fds, *end = &p->fds[p->fds_size];
1475 static inline void cleanup_negative_pid_fds(struct pid_stat *p) {
1476 int *fd = p->fds, *fdend = &p->fds[p->fds_size];
1479 if(unlikely(*fd < 0)) {
1480 file_descriptor_not_used(-(*fd));
1488 static inline void zero_pid_fds(struct pid_stat *p, int first, int size) {
1489 int *fd = &p->fds[first], *end = &p->fds[first + size];
1490 while(fd < end) *fd++ = 0;
1493 static inline int read_pid_file_descriptors(struct pid_stat *p, void *ptr) {
1498 struct kinfo_file *fds;
1499 static char *fdsbuf;
1500 char *bfdsbuf, *efdsbuf;
1501 char fdsname[FILENAME_MAX + 1];
1503 // we make all pid fds negative, so that
1504 // we can detect unused file descriptors
1505 // at the end, to free them
1506 make_all_pid_fds_negative(p);
1510 mib[2] = KERN_PROC_FILEDESC;
1513 if (unlikely(sysctl(mib, 4, NULL, &size, NULL, 0))) {
1514 error("sysctl error: Can't get file descriptors data size for pid %d", p->pid);
1517 if (likely(size > 0))
1518 fdsbuf = reallocz(fdsbuf, size);
1519 if (unlikely(sysctl(mib, 4, fdsbuf, &size, NULL, 0))) {
1520 error("sysctl error: Can't get file descriptors data for pid %d", p->pid);
1525 efdsbuf = fdsbuf + size;
1526 while (bfdsbuf < efdsbuf) {
1527 fds = (struct kinfo_file *)(uintptr_t)bfdsbuf;
1528 if (unlikely(fds->kf_structsize == 0))
1531 // do not process file descriptors for current working directory, root directory,
1532 // jail directory, ktrace vnode, text vnode and controlling terminal
1533 if (unlikely(fds->kf_fd < 0)) {
1534 bfdsbuf += fds->kf_structsize;
1538 // get file descriptors array index
1539 int fdid = fds->kf_fd;
1541 // check if the fds array is small
1542 if (unlikely(fdid >= p->fds_size)) {
1543 // it is small, extend it
1545 if (unlikely(debug))
1546 fprintf(stderr, "apps.plugin: extending fd memory slots for %s from %d to %d\n", p->comm, p->fds_size, fdid + MAX_SPARE_FDS);
1548 p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(int));
1550 // and initialize it
1551 zero_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
1552 p->fds_size = fdid + MAX_SPARE_FDS;
1555 if (unlikely(p->fds[fdid] == 0)) {
1556 // we don't know this fd, get it
1558 switch (fds->kf_type) {
1561 if (unlikely(!fds->kf_path[0])) {
1562 sprintf(fdsname, "other: inode: %lu", fds->kf_un.kf_file.kf_file_fileid);
1565 sprintf(fdsname, "%s", fds->kf_path);
1567 case KF_TYPE_SOCKET:
1568 switch (fds->kf_sock_domain) {
1571 if (fds->kf_sock_protocol == IPPROTO_TCP)
1572 sprintf(fdsname, "socket: %d %lx", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sock_inpcb);
1574 sprintf(fdsname, "socket: %d %lx", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sock_pcb);
1577 /* print address of pcb and connected pcb */
1578 sprintf(fdsname, "socket: %lx %lx", fds->kf_un.kf_sock.kf_sock_pcb, fds->kf_un.kf_sock.kf_sock_unpconn);
1581 /* print protocol number and socket address */
1582 sprintf(fdsname, "socket: other: %d %s %s", fds->kf_sock_protocol, fds->kf_sa_local.__ss_pad1, fds->kf_sa_local.__ss_pad2);
1586 sprintf(fdsname, "pipe: %lu %lu", fds->kf_un.kf_pipe.kf_pipe_addr, fds->kf_un.kf_pipe.kf_pipe_peer);
1589 sprintf(fdsname, "other: pts: %u", fds->kf_un.kf_pts.kf_pts_dev);
1592 sprintf(fdsname, "other: shm: %s size: %lu", fds->kf_path, fds->kf_un.kf_file.kf_file_size);
1595 sprintf(fdsname, "other: sem: %u", fds->kf_un.kf_sem.kf_sem_value);
1598 sprintf(fdsname, "other: pid: %d fd: %d", fds->kf_un.kf_proc.kf_pid, fds->kf_fd);
1601 // if another process already has this, we will get
1603 p->fds[fdid] = file_descriptor_find_or_add(fdsname);
1606 // else make it positive again, we need it
1607 // of course, the actual file may have changed, but we don't care so much
1608 // FIXME: we could compare the inode as returned by readdir dirent structure
1611 p->fds[fdid] = -p->fds[fdid];
1613 bfdsbuf += fds->kf_structsize;
1616 if(unlikely(!p->fds_dirname)) {
1617 char dirname[FILENAME_MAX+1];
1618 snprintfz(dirname, FILENAME_MAX, "%s/proc/%d/fd", netdata_configured_host_prefix, p->pid);
1619 p->fds_dirname = strdupz(dirname);
1622 DIR *fds = opendir(p->fds_dirname);
1623 if(unlikely(!fds)) return 0;
1626 char fdname[FILENAME_MAX + 1];
1627 char linkname[FILENAME_MAX + 1];
1629 // we make all pid fds negative, so that
1630 // we can detect unused file descriptors
1631 // at the end, to free them
1632 make_all_pid_fds_negative(p);
1634 while((de = readdir(fds))) {
1635 // we need only files with numeric names
1637 if(unlikely(de->d_name[0] < '0' || de->d_name[0] > '9'))
1641 int fdid = (int) str2l(de->d_name);
1642 if(unlikely(fdid < 0)) continue;
1644 // check if the fds array is small
1645 if(unlikely(fdid >= p->fds_size)) {
1646 // it is small, extend it
1650 , "apps.plugin: extending fd memory slots for %s from %d to %d\n"
1653 , fdid + MAX_SPARE_FDS
1656 p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(int));
1658 // and initialize it
1659 zero_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
1660 p->fds_size = fdid + MAX_SPARE_FDS;
1663 if(unlikely(p->fds[fdid] == 0)) {
1664 // we don't know this fd, get it
1666 sprintf(fdname, "%s/proc/%d/fd/%s", netdata_configured_host_prefix, p->pid, de->d_name);
1667 ssize_t l = readlink(fdname, linkname, FILENAME_MAX);
1668 if(unlikely(l == -1)) {
1669 if(debug || (p->target && p->target->debug)) {
1670 if(debug || (p->target && p->target->debug))
1671 error("Cannot read link %s", fdname);
1680 // if another process already has this, we will get
1682 p->fds[fdid] = file_descriptor_find_or_add(linkname);
1685 // else make it positive again, we need it
1686 // of course, the actual file may have changed, but we don't care so much
1687 // FIXME: we could compare the inode as returned by readdir dirent structure
1688 // UPDATE: no we cannot use inodes - under /proc inodes don't change when the link is changed
1691 p->fds[fdid] = -p->fds[fdid];
1696 cleanup_negative_pid_fds(p);
1701 // ----------------------------------------------------------------------------
1703 static inline int print_process_and_parents(struct pid_stat *p, usec_t time) {
1704 char *prefix = "\\_ ";
1708 indent = print_process_and_parents(p->parent, p->stat_collected_usec);
1712 char buffer[indent + 1];
1715 for(i = 0; i < indent ;i++) buffer[i] = ' ';
1718 fprintf(stderr, " %s %s%s (%d %s %llu"
1723 , p->updated?"running":"exited"
1724 , p->stat_collected_usec - time
1727 if(p->utime) fprintf(stderr, " utime=" KERNEL_UINT_FORMAT, p->utime);
1728 if(p->stime) fprintf(stderr, " stime=" KERNEL_UINT_FORMAT, p->stime);
1729 if(p->gtime) fprintf(stderr, " gtime=" KERNEL_UINT_FORMAT, p->gtime);
1730 if(p->cutime) fprintf(stderr, " cutime=" KERNEL_UINT_FORMAT, p->cutime);
1731 if(p->cstime) fprintf(stderr, " cstime=" KERNEL_UINT_FORMAT, p->cstime);
1732 if(p->cgtime) fprintf(stderr, " cgtime=" KERNEL_UINT_FORMAT, p->cgtime);
1733 if(p->minflt) fprintf(stderr, " minflt=" KERNEL_UINT_FORMAT, p->minflt);
1734 if(p->cminflt) fprintf(stderr, " cminflt=" KERNEL_UINT_FORMAT, p->cminflt);
1735 if(p->majflt) fprintf(stderr, " majflt=" KERNEL_UINT_FORMAT, p->majflt);
1736 if(p->cmajflt) fprintf(stderr, " cmajflt=" KERNEL_UINT_FORMAT, p->cmajflt);
1737 fprintf(stderr, ")\n");
1742 static inline void print_process_tree(struct pid_stat *p, char *msg) {
1744 fprintf(stderr, "%s: process %s (%d, %s) with parents:\n", msg, p->comm, p->pid, p->updated?"running":"exited");
1745 print_process_and_parents(p, p->stat_collected_usec);
1748 static inline void find_lost_child_debug(struct pid_stat *pe, kernel_uint_t lost, int type) {
1750 struct pid_stat *p = NULL;
1752 for(p = root_of_pids; p ; p = p->next) {
1753 if(p == pe) continue;
1757 if(p->cminflt > lost) {
1758 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);
1764 if(p->cmajflt > lost) {
1765 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);
1771 if(p->cutime > lost) {
1772 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);
1778 if(p->cstime > lost) {
1779 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);
1785 if(p->cgtime > lost) {
1786 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);
1796 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);
1800 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);
1804 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);
1808 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);
1812 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);
1818 static inline kernel_uint_t remove_exited_child_from_parent(kernel_uint_t *field, kernel_uint_t *pfield) {
1819 kernel_uint_t absorbed = 0;
1821 if(*field > *pfield) {
1822 absorbed += *pfield;
1835 static inline void process_exited_processes() {
1838 for(p = root_of_pids; p ; p = p->next) {
1839 if(p->updated || !p->stat_collected_usec)
1842 kernel_uint_t utime = (p->utime_raw + p->cutime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1843 kernel_uint_t stime = (p->stime_raw + p->cstime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1844 kernel_uint_t gtime = (p->gtime_raw + p->cgtime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1845 kernel_uint_t minflt = (p->minflt_raw + p->cminflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1846 kernel_uint_t majflt = (p->majflt_raw + p->cmajflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1848 if(utime + stime + gtime + minflt + majflt == 0)
1851 if(unlikely(debug)) {
1853 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"
1856 , p->updated?"running":"exited"
1863 print_process_tree(p, "Searching parents");
1866 struct pid_stat *pp;
1867 for(pp = p->parent; pp ; pp = pp->parent) {
1868 if(!pp->updated) continue;
1870 kernel_uint_t absorbed;
1871 absorbed = remove_exited_child_from_parent(&utime, &pp->cutime);
1872 if(unlikely(debug && absorbed))
1873 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);
1875 absorbed = remove_exited_child_from_parent(&stime, &pp->cstime);
1876 if(unlikely(debug && absorbed))
1877 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);
1879 absorbed = remove_exited_child_from_parent(>ime, &pp->cgtime);
1880 if(unlikely(debug && absorbed))
1881 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);
1883 absorbed = remove_exited_child_from_parent(&minflt, &pp->cminflt);
1884 if(unlikely(debug && absorbed))
1885 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);
1887 absorbed = remove_exited_child_from_parent(&majflt, &pp->cmajflt);
1888 if(unlikely(debug && absorbed))
1889 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);
1892 if(unlikely(utime + stime + gtime + minflt + majflt > 0)) {
1893 if(unlikely(debug)) {
1894 if(utime) find_lost_child_debug(p, utime, 3);
1895 if(stime) find_lost_child_debug(p, stime, 4);
1896 if(gtime) find_lost_child_debug(p, gtime, 5);
1897 if(minflt) find_lost_child_debug(p, minflt, 1);
1898 if(majflt) find_lost_child_debug(p, majflt, 2);
1904 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"
1907 , p->updated?"running":"exited"
1915 for(pp = p->parent; pp ; pp = pp->parent) {
1916 if(pp->updated) break;
1920 fprintf(stderr, " > - KEEP - parent for another loop: %s (%d %s)\n"
1923 , pp->updated?"running":"exited"
1927 p->utime_raw = utime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1928 p->stime_raw = stime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1929 p->gtime_raw = gtime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1930 p->minflt_raw = minflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1931 p->majflt_raw = majflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1932 p->cutime_raw = p->cstime_raw = p->cgtime_raw = p->cminflt_raw = p->cmajflt_raw = 0;
1935 fprintf(stderr, "\n");
1937 else if(unlikely(debug)) {
1938 fprintf(stderr, " > totally absorbed - DONE - %s (%d %s)\n"
1941 , p->updated?"running":"exited"
1947 static inline void link_all_processes_to_their_parents(void) {
1948 struct pid_stat *p, *pp;
1950 // link all children to their parents
1951 // and update children count on parents
1952 for(p = root_of_pids; p ; p = p->next) {
1953 // for each process found
1958 if(unlikely(!p->ppid)) {
1963 pp = all_pids[p->ppid];
1966 pp->children_count++;
1968 if(unlikely(debug || (p->target && p->target->debug)))
1969 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);
1973 error("pid %d %s states parent %d, but the later does not exist.", p->pid, p->comm, p->ppid);
1978 // ----------------------------------------------------------------------------
1980 // 1. read all files in /proc
1981 // 2. for each numeric directory:
1982 // i. read /proc/pid/stat
1983 // ii. read /proc/pid/statm
1984 // iii. read /proc/pid/io (requires root access)
1985 // iii. read the entries in directory /proc/pid/fd (requires root access)
1987 // a. find or create a struct file_descriptor
1988 // b. cleanup any old/unused file_descriptors
1990 // after all these, some pids may be linked to targets, while others may not
1992 // in case of errors, only 1 every 1000 errors is printed
1993 // to avoid filling up all disk space
1994 // if debug is enabled, all errors are printed
1996 static int compar_pid(const void *pid1, const void *pid2) {
1998 struct pid_stat *p1 = all_pids[*((pid_t *)pid1)];
1999 struct pid_stat *p2 = all_pids[*((pid_t *)pid2)];
2001 if(p1->sortlist > p2->sortlist)
2007 static inline int collect_data_for_pid(pid_t pid, void *ptr) {
2008 if(unlikely(pid < INIT_PID || pid > pid_max)) {
2009 error("Invalid pid %d read (expected %d to %d). Ignoring process.", pid, INIT_PID, pid_max);
2013 struct pid_stat *p = get_pid_entry(pid);
2014 if(unlikely(!p || p->read)) return 0;
2017 // fprintf(stderr, "Reading process %d (%s), sortlist %d\n", p->pid, p->comm, p->sortlist);
2019 // --------------------------------------------------------------------
2022 if(unlikely(!managed_log(p, PID_LOG_STAT, read_proc_pid_stat(p, ptr))))
2023 // there is no reason to proceed if we cannot get its status
2026 read_proc_pid_ownership(p, ptr);
2028 // check its parent pid
2029 if(unlikely(p->ppid < 0 || p->ppid > pid_max)) {
2030 error("Pid %d (command '%s') states invalid parent pid %d. Using 0.", pid, p->comm, p->ppid);
2034 // --------------------------------------------------------------------
2037 managed_log(p, PID_LOG_IO, read_proc_pid_io(p, ptr));
2039 // --------------------------------------------------------------------
2040 // /proc/<pid>/statm
2042 if(unlikely(!managed_log(p, PID_LOG_STATM, read_proc_pid_statm(p, ptr))))
2043 // there is no reason to proceed if we cannot get its memory status
2046 // --------------------------------------------------------------------
2049 if(enable_file_charts)
2050 managed_log(p, PID_LOG_FDS, read_pid_file_descriptors(p, ptr));
2052 // --------------------------------------------------------------------
2055 if(unlikely(debug && include_exited_childs && all_pids_count && p->ppid && all_pids[p->ppid] && !all_pids[p->ppid]->read))
2056 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);
2058 // mark it as updated
2066 static int collect_data_for_all_processes(void) {
2067 struct pid_stat *p = NULL;
2071 size_t procbase_size;
2072 static struct kinfo_proc *procbase;
2078 mib[2] = KERN_PROC_PROC;
2079 if (unlikely(sysctl(mib, 3, NULL, &procbase_size, NULL, 0))) {
2080 error("sysctl error: Can't get processes data size");
2083 procbase = reallocz(procbase, procbase_size);
2084 if (unlikely(sysctl(mib, 3, procbase, &procbase_size, NULL, 0))) {
2085 error("sysctl error: Can't get processes data");
2088 procnum = procbase_size / sizeof(struct kinfo_proc);
2091 if(all_pids_count) {
2093 for(p = root_of_pids; p ; p = p->next) {
2094 p->read = 0; // mark it as not read, so that collect_data_for_pid() will read it
2097 p->children_count = 0;
2100 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
2101 all_pids_sortlist[slc++] = p->pid;
2105 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
2106 if(unlikely(slc != all_pids_count)) {
2107 error("Internal error: I was thinking I had %zu processes in my arrays, but it seems there are more.", all_pids_count);
2108 all_pids_count = slc;
2111 if(include_exited_childs) {
2112 // Read parents before childs
2113 // This is needed to prevent a situation where
2114 // a child is found running, but until we read
2115 // its parent, it has exited and its parent
2116 // has accumulated its resources.
2118 qsort((void *)all_pids_sortlist, (size_t)all_pids_count, sizeof(pid_t), compar_pid);
2120 // we forward read all running processes
2121 // collect_data_for_pid() is smart enough,
2122 // not to read the same pid twice per iteration
2123 for(slc = 0; slc < all_pids_count; slc++)
2124 collect_data_for_pid(all_pids_sortlist[slc], NULL);
2130 for (i = INIT_PID; i < procnum - INIT_PID; ++i) {
2131 pid_t pid = procbase[i].ki_pid;
2132 collect_data_for_pid(pid, &procbase[i]);
2135 char dirname[FILENAME_MAX + 1];
2137 snprintfz(dirname, FILENAME_MAX, "%s/proc", netdata_configured_host_prefix);
2138 DIR *dir = opendir(dirname);
2141 struct dirent *de = NULL;
2143 while((de = readdir(dir))) {
2144 char *endptr = de->d_name;
2146 if(unlikely(de->d_type != DT_DIR || de->d_name[0] < '0' || de->d_name[0] > '9'))
2149 pid_t pid = (pid_t) strtoul(de->d_name, &endptr, 10);
2151 // make sure we read a valid number
2152 if(unlikely(endptr == de->d_name || *endptr != '\0'))
2155 collect_data_for_pid(pid, NULL);
2163 // we need /proc/stat to normalize the cpu consumption of the exited childs
2166 // build the process tree
2167 link_all_processes_to_their_parents();
2169 // normally this is done
2170 // however we may have processes exited while we collected values
2171 // so let's find the exited ones
2172 // we do this by collecting the ownership of process
2173 // if we manage to get the ownership, the process still runs
2174 process_exited_processes();
2179 // ----------------------------------------------------------------------------
2180 // update statistics on the targets
2182 // 1. link all childs to their parents
2183 // 2. go from bottom to top, marking as merged all childs to their parents
2184 // this step links all parents without a target to the child target, if any
2185 // 3. link all top level processes (the ones not merged) to the default target
2186 // 4. go from top to bottom, linking all childs without a target, to their parent target
2187 // after this step, all processes have a target
2188 // [5. for each killed pid (updated = 0), remove its usage from its target]
2189 // 6. zero all apps_groups_targets
2190 // 7. concentrate all values on the apps_groups_targets
2191 // 8. remove all killed processes
2192 // 9. find the unique file count for each target
2193 // check: update_apps_groups_statistics()
2195 static void cleanup_exited_pids(void) {
2197 struct pid_stat *p = NULL;
2199 for(p = root_of_pids; p ;) {
2200 if(!p->updated && (!p->keep || p->keeploops > 0)) {
2201 if(unlikely(debug && (p->keep || p->keeploops)))
2202 fprintf(stderr, " > CLEANUP cannot keep exited process %d (%s) anymore - removing it.\n", p->pid, p->comm);
2204 for(c = 0; c < p->fds_size; c++)
2206 file_descriptor_not_used(p->fds[c]);
2215 if(unlikely(p->keep)) p->keeploops++;
2222 static void apply_apps_groups_targets_inheritance(void) {
2223 struct pid_stat *p = NULL;
2225 // children that do not have a target
2226 // inherit their target from their parent
2227 int found = 1, loops = 0;
2229 if(unlikely(debug)) loops++;
2231 for(p = root_of_pids; p ; p = p->next) {
2232 // if this process does not have a target
2233 // and it has a parent
2234 // and its parent has a target
2235 // then, set the parent's target to this process
2236 if(unlikely(!p->target && p->parent && p->parent->target)) {
2237 p->target = p->parent->target;
2240 if(debug || (p->target && p->target->debug))
2241 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);
2246 // find all the procs with 0 childs and merge them to their parents
2247 // repeat, until nothing more can be done.
2251 if(unlikely(debug)) loops++;
2254 for(p = root_of_pids; p ; p = p->next) {
2255 if(unlikely(!p->sortlist && !p->children_count))
2256 p->sortlist = sortlist++;
2258 // if this process does not have any children
2259 // and is not already merged
2261 // and its parent has children
2262 // and the target of this process and its parent is the same, or the parent does not have a target
2263 // and its parent is not init
2264 // then, mark them as merged.
2269 && p->parent->children_count
2270 && (p->target == p->parent->target || !p->parent->target)
2271 && p->ppid != INIT_PID
2273 p->parent->children_count--;
2276 // the parent inherits the child's target, if it does not have a target itself
2277 if(unlikely(p->target && !p->parent->target)) {
2278 p->parent->target = p->target;
2280 if(debug || (p->target && p->target->debug))
2281 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);
2289 fprintf(stderr, "apps.plugin: TARGET INHERITANCE: merged %d processes\n", found);
2292 // init goes always to default target
2293 if(all_pids[INIT_PID])
2294 all_pids[INIT_PID]->target = apps_groups_default_target;
2296 // give a default target on all top level processes
2297 if(unlikely(debug)) loops++;
2298 for(p = root_of_pids; p ; p = p->next) {
2299 // if the process is not merged itself
2300 // then is is a top level process
2301 if(unlikely(!p->merged && !p->target))
2302 p->target = apps_groups_default_target;
2304 // make sure all processes have a sortlist
2305 if(unlikely(!p->sortlist))
2306 p->sortlist = sortlist++;
2310 all_pids[1]->sortlist = sortlist++;
2312 // give a target to all merged child processes
2315 if(unlikely(debug)) loops++;
2317 for(p = root_of_pids; p ; p = p->next) {
2318 if(unlikely(!p->target && p->merged && p->parent && p->parent->target)) {
2319 p->target = p->parent->target;
2322 if(debug || (p->target && p->target->debug))
2323 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);
2329 fprintf(stderr, "apps.plugin: apply_apps_groups_targets_inheritance() made %d loops on the process tree\n", loops);
2332 static size_t zero_all_targets(struct target *root) {
2336 for (w = root; w ; w = w->next) {
2354 w->statm_resident = 0;
2356 // w->statm_text = 0;
2357 // w->statm_lib = 0;
2358 // w->statm_data = 0;
2359 // w->statm_dirty = 0;
2361 w->io_logical_bytes_read = 0;
2362 w->io_logical_bytes_written = 0;
2363 // w->io_read_calls = 0;
2364 // w->io_write_calls = 0;
2365 w->io_storage_bytes_read = 0;
2366 w->io_storage_bytes_written = 0;
2367 // w->io_cancelled_write_bytes = 0;
2369 // zero file counters
2371 memset(w->target_fds, 0, sizeof(int) * w->target_fds_size);
2375 w->openinotifies = 0;
2376 w->openeventfds = 0;
2377 w->opentimerfds = 0;
2378 w->opensignalfds = 0;
2379 w->openeventpolls = 0;
2387 static inline void reallocate_target_fds(struct target *w) {
2391 if(unlikely(!w->target_fds || w->target_fds_size < all_files_size)) {
2392 w->target_fds = reallocz(w->target_fds, sizeof(int) * all_files_size);
2393 memset(&w->target_fds[w->target_fds_size], 0, sizeof(int) * (all_files_size - w->target_fds_size));
2394 w->target_fds_size = all_files_size;
2398 static inline void aggregate_fd_on_target(int fd, struct target *w) {
2402 if(unlikely(w->target_fds[fd])) {
2403 // it is already aggregated
2404 // just increase its usage counter
2405 w->target_fds[fd]++;
2409 // increase its usage counter
2410 // so that we will not add it again
2411 w->target_fds[fd]++;
2413 switch(all_files[fd].type) {
2422 case FILETYPE_SOCKET:
2426 case FILETYPE_INOTIFY:
2430 case FILETYPE_EVENTFD:
2434 case FILETYPE_TIMERFD:
2438 case FILETYPE_SIGNALFD:
2442 case FILETYPE_EVENTPOLL:
2443 w->openeventpolls++;
2446 case FILETYPE_OTHER:
2452 static inline void aggregate_pid_fds_on_targets(struct pid_stat *p) {
2454 if(unlikely(!p->updated)) {
2455 // the process is not running
2459 struct target *w = p->target, *u = p->user_target, *g = p->group_target;
2461 reallocate_target_fds(w);
2462 reallocate_target_fds(u);
2463 reallocate_target_fds(g);
2465 int c, size = p->fds_size, *fds = p->fds;
2466 for(c = 0; c < size ;c++) {
2469 if(likely(fd <= 0 || fd >= all_files_size))
2472 aggregate_fd_on_target(fd, w);
2473 aggregate_fd_on_target(fd, u);
2474 aggregate_fd_on_target(fd, g);
2478 static inline void aggregate_pid_on_target(struct target *w, struct pid_stat *p, struct target *o) {
2481 if(unlikely(!p->updated)) {
2482 // the process is not running
2487 error("pid %d %s was left without a target!", p->pid, p->comm);
2491 w->cutime += p->cutime;
2492 w->cstime += p->cstime;
2493 w->cgtime += p->cgtime;
2494 w->cminflt += p->cminflt;
2495 w->cmajflt += p->cmajflt;
2497 w->utime += p->utime;
2498 w->stime += p->stime;
2499 w->gtime += p->gtime;
2500 w->minflt += p->minflt;
2501 w->majflt += p->majflt;
2503 // w->rss += p->rss;
2505 w->statm_size += p->statm_size;
2506 w->statm_resident += p->statm_resident;
2507 w->statm_share += p->statm_share;
2508 // w->statm_text += p->statm_text;
2509 // w->statm_lib += p->statm_lib;
2510 // w->statm_data += p->statm_data;
2511 // w->statm_dirty += p->statm_dirty;
2513 w->io_logical_bytes_read += p->io_logical_bytes_read;
2514 w->io_logical_bytes_written += p->io_logical_bytes_written;
2515 // w->io_read_calls += p->io_read_calls;
2516 // w->io_write_calls += p->io_write_calls;
2517 w->io_storage_bytes_read += p->io_storage_bytes_read;
2518 w->io_storage_bytes_written += p->io_storage_bytes_written;
2519 // w->io_cancelled_write_bytes += p->io_cancelled_write_bytes;
2522 w->num_threads += p->num_threads;
2524 if(unlikely(debug || w->debug))
2525 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);
2528 static void calculate_netdata_statistics(void) {
2530 apply_apps_groups_targets_inheritance();
2532 zero_all_targets(users_root_target);
2533 zero_all_targets(groups_root_target);
2534 apps_groups_targets_count = zero_all_targets(apps_groups_root_target);
2536 // this has to be done, before the cleanup
2537 struct pid_stat *p = NULL;
2538 struct target *w = NULL, *o = NULL;
2540 // concentrate everything on the targets
2541 for(p = root_of_pids; p ; p = p->next) {
2543 // --------------------------------------------------------------------
2544 // apps_groups target
2546 aggregate_pid_on_target(p->target, p, NULL);
2549 // --------------------------------------------------------------------
2553 if(likely(p->user_target && p->user_target->uid == p->uid))
2556 if(unlikely(debug && p->user_target))
2557 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);
2559 w = p->user_target = get_users_target(p->uid);
2562 aggregate_pid_on_target(w, p, o);
2565 // --------------------------------------------------------------------
2566 // user group target
2568 o = p->group_target;
2569 if(likely(p->group_target && p->group_target->gid == p->gid))
2570 w = p->group_target;
2572 if(unlikely(debug && p->group_target))
2573 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);
2575 w = p->group_target = get_groups_target(p->gid);
2578 aggregate_pid_on_target(w, p, o);
2581 // --------------------------------------------------------------------
2582 // aggregate all file descriptors
2584 if(enable_file_charts)
2585 aggregate_pid_fds_on_targets(p);
2588 cleanup_exited_pids();
2591 // ----------------------------------------------------------------------------
2592 // update chart dimensions
2594 int print_calculated_number(char *str, calculated_number value) { (void)str; (void)value; return 0; }
2596 static inline void send_BEGIN(const char *type, const char *id, usec_t usec) {
2597 fprintf(stdout, "BEGIN %s.%s %llu\n", type, id, usec);
2600 static inline void send_SET(const char *name, kernel_uint_t value) {
2601 fprintf(stdout, "SET %s = " KERNEL_UINT_FORMAT "\n", name, value);
2604 static inline void send_END(void) {
2605 fprintf(stdout, "END\n");
2608 static usec_t send_resource_usage_to_netdata() {
2609 static struct timeval last = { 0, 0 };
2610 static struct rusage me_last;
2620 now_monotonic_timeval(&last);
2621 getrusage(RUSAGE_SELF, &me_last);
2623 // the first time, give a zero to allow
2624 // netdata calibrate to the current time
2625 // usec = update_every * USEC_PER_SEC;
2631 now_monotonic_timeval(&now);
2632 getrusage(RUSAGE_SELF, &me);
2634 usec = dt_usec(&now, &last);
2635 cpuuser = me.ru_utime.tv_sec * USEC_PER_SEC + me.ru_utime.tv_usec;
2636 cpusyst = me.ru_stime.tv_sec * USEC_PER_SEC + me.ru_stime.tv_usec;
2638 memmove(&last, &now, sizeof(struct timeval));
2639 memmove(&me_last, &me, sizeof(struct rusage));
2642 static char created_charts = 0;
2643 if(unlikely(!created_charts)) {
2647 , "CHART netdata.apps_cpu '' 'Apps Plugin CPU' 'milliseconds/s' apps.plugin netdata.apps_cpu stacked 140000 %1$d\n"
2648 "DIMENSION user '' incremental 1 1000\n"
2649 "DIMENSION system '' incremental 1 1000\n"
2650 "CHART netdata.apps_files '' 'Apps Plugin Files' 'files/s' apps.plugin netdata.apps_files line 140001 %1$d\n"
2651 "DIMENSION calls '' incremental 1 1\n"
2652 "DIMENSION files '' incremental 1 1\n"
2653 "DIMENSION pids '' absolute 1 1\n"
2654 "DIMENSION fds '' absolute 1 1\n"
2655 "DIMENSION targets '' absolute 1 1\n"
2656 "CHART netdata.apps_fix '' 'Apps Plugin Normalization Ratios' 'percentage' apps.plugin netdata.apps_fix line 140002 %1$d\n"
2657 "DIMENSION utime '' absolute 1 %2$llu\n"
2658 "DIMENSION stime '' absolute 1 %2$llu\n"
2659 "DIMENSION gtime '' absolute 1 %2$llu\n"
2660 "DIMENSION minflt '' absolute 1 %2$llu\n"
2661 "DIMENSION majflt '' absolute 1 %2$llu\n"
2666 if(include_exited_childs)
2668 , "CHART netdata.apps_children_fix '' 'Apps Plugin Exited Children Normalization Ratios' 'percentage' apps.plugin netdata.apps_children_fix line 140003 %1$d\n"
2669 "DIMENSION cutime '' absolute 1 %2$llu\n"
2670 "DIMENSION cstime '' absolute 1 %2$llu\n"
2671 "DIMENSION cgtime '' absolute 1 %2$llu\n"
2672 "DIMENSION cminflt '' absolute 1 %2$llu\n"
2673 "DIMENSION cmajflt '' absolute 1 %2$llu\n"
2680 "BEGIN netdata.apps_cpu %llu\n"
2682 "SET system = %llu\n"
2684 "BEGIN netdata.apps_files %llu\n"
2689 "SET targets = %zu\n"
2691 "BEGIN netdata.apps_fix %llu\n"
2706 , apps_groups_targets_count
2708 , (unsigned int)(utime_fix_ratio * 100 * RATES_DETAIL)
2709 , (unsigned int)(stime_fix_ratio * 100 * RATES_DETAIL)
2710 , (unsigned int)(gtime_fix_ratio * 100 * RATES_DETAIL)
2711 , (unsigned int)(minflt_fix_ratio * 100 * RATES_DETAIL)
2712 , (unsigned int)(majflt_fix_ratio * 100 * RATES_DETAIL)
2715 if(include_exited_childs)
2717 "BEGIN netdata.apps_children_fix %llu\n"
2721 "SET cminflt = %u\n"
2722 "SET cmajflt = %u\n"
2725 , (unsigned int)(cutime_fix_ratio * 100 * RATES_DETAIL)
2726 , (unsigned int)(cstime_fix_ratio * 100 * RATES_DETAIL)
2727 , (unsigned int)(cgtime_fix_ratio * 100 * RATES_DETAIL)
2728 , (unsigned int)(cminflt_fix_ratio * 100 * RATES_DETAIL)
2729 , (unsigned int)(cmajflt_fix_ratio * 100 * RATES_DETAIL)
2735 static void normalize_utilization(struct target *root) {
2738 // childs processing introduces spikes
2739 // here we try to eliminate them by disabling childs processing either for specific dimensions
2740 // or entirely. Of course, either way, we disable it just a single iteration.
2742 kernel_uint_t max_time = processors * hz * RATES_DETAIL;
2743 kernel_uint_t utime = 0, cutime = 0, stime = 0, cstime = 0, gtime = 0, cgtime = 0, minflt = 0, cminflt = 0, majflt = 0, cmajflt = 0;
2745 if(global_utime > max_time) global_utime = max_time;
2746 if(global_stime > max_time) global_stime = max_time;
2747 if(global_gtime > max_time) global_gtime = max_time;
2749 for(w = root; w ; w = w->next) {
2750 if(w->target || (!w->processes && !w->exposed)) continue;
2755 cutime += w->cutime;
2756 cstime += w->cstime;
2757 cgtime += w->cgtime;
2759 minflt += w->minflt;
2760 majflt += w->majflt;
2761 cminflt += w->cminflt;
2762 cmajflt += w->cmajflt;
2765 if((global_utime || global_stime || global_gtime) && (utime || stime || gtime)) {
2766 if(global_utime + global_stime + global_gtime > utime + cutime + stime + cstime + gtime + cgtime) {
2767 // everything we collected fits
2773 cgtime_fix_ratio = 1.0; //(double)(global_utime + global_stime) / (double)(utime + cutime + stime + cstime);
2775 else if(global_utime + global_stime > utime + stime) {
2776 // childrens resources are too high
2777 // lower only the children resources
2780 gtime_fix_ratio = 1.0;
2783 cgtime_fix_ratio = (double)((global_utime + global_stime) - (utime + stime)) / (double)(cutime + cstime);
2786 // even running processes are unrealistic
2787 // zero the children resources
2788 // lower the running processes resources
2791 gtime_fix_ratio = (double)(global_utime + global_stime) / (double)(utime + stime);
2794 cgtime_fix_ratio = 0.0;
2803 cgtime_fix_ratio = 0.0;
2806 if(utime_fix_ratio > 1.0) utime_fix_ratio = 1.0;
2807 if(cutime_fix_ratio > 1.0) cutime_fix_ratio = 1.0;
2808 if(stime_fix_ratio > 1.0) stime_fix_ratio = 1.0;
2809 if(cstime_fix_ratio > 1.0) cstime_fix_ratio = 1.0;
2810 if(gtime_fix_ratio > 1.0) gtime_fix_ratio = 1.0;
2811 if(cgtime_fix_ratio > 1.0) cgtime_fix_ratio = 1.0;
2813 // if(utime_fix_ratio < 0.0) utime_fix_ratio = 0.0;
2814 // if(cutime_fix_ratio < 0.0) cutime_fix_ratio = 0.0;
2815 // if(stime_fix_ratio < 0.0) stime_fix_ratio = 0.0;
2816 // if(cstime_fix_ratio < 0.0) cstime_fix_ratio = 0.0;
2817 // if(gtime_fix_ratio < 0.0) gtime_fix_ratio = 0.0;
2818 // if(cgtime_fix_ratio < 0.0) cgtime_fix_ratio = 0.0;
2821 // we use cpu time to normalize page faults
2822 // the problem is that to find the proper max values
2823 // for page faults we have to parse /proc/vmstat
2824 // which is quite big to do it again (netdata does it already)
2826 // a better solution could be to somehow have netdata
2827 // do this normalization for us
2829 if(utime || stime || gtime)
2831 minflt_fix_ratio = (double)(utime * utime_fix_ratio + stime * stime_fix_ratio + gtime * gtime_fix_ratio) / (double)(utime + stime + gtime);
2834 majflt_fix_ratio = 1.0;
2836 if(cutime || cstime || cgtime)
2838 cminflt_fix_ratio = (double)(cutime * cutime_fix_ratio + cstime * cstime_fix_ratio + cgtime * cgtime_fix_ratio) / (double)(cutime + cstime + cgtime);
2841 cmajflt_fix_ratio = 1.0;
2845 if(unlikely(debug)) {
2847 "SYSTEM: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
2848 "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 " "
2849 "DELTA: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
2850 "FIX: u=%0.2f s=%0.2f g=%0.2f cu=%0.2f cs=%0.2f cg=%0.2f "
2851 "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 " "
2862 , utime + cutime - global_utime
2863 , stime + cstime - global_stime
2864 , gtime + cgtime - global_gtime
2871 , (kernel_uint_t)(utime * utime_fix_ratio)
2872 , (kernel_uint_t)(stime * stime_fix_ratio)
2873 , (kernel_uint_t)(gtime * gtime_fix_ratio)
2874 , (kernel_uint_t)(cutime * cutime_fix_ratio)
2875 , (kernel_uint_t)(cstime * cstime_fix_ratio)
2876 , (kernel_uint_t)(cgtime * cgtime_fix_ratio)
2881 static void send_collected_data_to_netdata(struct target *root, const char *type, usec_t usec) {
2884 send_BEGIN(type, "cpu", usec);
2885 for (w = root; w ; w = w->next) {
2886 if(unlikely(w->exposed))
2887 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));
2891 send_BEGIN(type, "cpu_user", usec);
2892 for (w = root; w ; w = w->next) {
2893 if(unlikely(w->exposed))
2894 send_SET(w->name, (kernel_uint_t)(w->utime * utime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cutime * cutime_fix_ratio)):0ULL));
2898 send_BEGIN(type, "cpu_system", usec);
2899 for (w = root; w ; w = w->next) {
2900 if(unlikely(w->exposed))
2901 send_SET(w->name, (kernel_uint_t)(w->stime * stime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cstime * cstime_fix_ratio)):0ULL));
2905 if(show_guest_time) {
2906 send_BEGIN(type, "cpu_guest", usec);
2907 for (w = root; w ; w = w->next) {
2908 if(unlikely(w->exposed))
2909 send_SET(w->name, (kernel_uint_t)(w->gtime * gtime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cgtime * cgtime_fix_ratio)):0ULL));
2914 send_BEGIN(type, "threads", usec);
2915 for (w = root; w ; w = w->next) {
2916 if(unlikely(w->exposed))
2917 send_SET(w->name, w->num_threads);
2921 send_BEGIN(type, "processes", usec);
2922 for (w = root; w ; w = w->next) {
2923 if(unlikely(w->exposed))
2924 send_SET(w->name, w->processes);
2928 send_BEGIN(type, "mem", usec);
2929 for (w = root; w ; w = w->next) {
2930 if(unlikely(w->exposed))
2931 send_SET(w->name, (w->statm_resident > w->statm_share)?(w->statm_resident - w->statm_share):0ULL);
2935 send_BEGIN(type, "vmem", usec);
2936 for (w = root; w ; w = w->next) {
2937 if(unlikely(w->exposed))
2938 send_SET(w->name, w->statm_size);
2942 send_BEGIN(type, "minor_faults", usec);
2943 for (w = root; w ; w = w->next) {
2944 if(unlikely(w->exposed))
2945 send_SET(w->name, (kernel_uint_t)(w->minflt * minflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cminflt * cminflt_fix_ratio)):0ULL));
2949 send_BEGIN(type, "major_faults", usec);
2950 for (w = root; w ; w = w->next) {
2951 if(unlikely(w->exposed))
2952 send_SET(w->name, (kernel_uint_t)(w->majflt * majflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cmajflt * cmajflt_fix_ratio)):0ULL));
2957 send_BEGIN(type, "lreads", usec);
2958 for (w = root; w ; w = w->next) {
2959 if(unlikely(w->exposed))
2960 send_SET(w->name, w->io_logical_bytes_read);
2964 send_BEGIN(type, "lwrites", usec);
2965 for (w = root; w ; w = w->next) {
2966 if(unlikely(w->exposed))
2967 send_SET(w->name, w->io_logical_bytes_written);
2972 send_BEGIN(type, "preads", usec);
2973 for (w = root; w ; w = w->next) {
2974 if(unlikely(w->exposed))
2975 send_SET(w->name, w->io_storage_bytes_read);
2979 send_BEGIN(type, "pwrites", usec);
2980 for (w = root; w ; w = w->next) {
2981 if(unlikely(w->exposed))
2982 send_SET(w->name, w->io_storage_bytes_written);
2986 if(enable_file_charts) {
2987 send_BEGIN(type, "files", usec);
2988 for (w = root; w; w = w->next) {
2989 if (unlikely(w->exposed))
2990 send_SET(w->name, w->openfiles);
2994 send_BEGIN(type, "sockets", usec);
2995 for (w = root; w; w = w->next) {
2996 if (unlikely(w->exposed))
2997 send_SET(w->name, w->opensockets);
3001 send_BEGIN(type, "pipes", usec);
3002 for (w = root; w; w = w->next) {
3003 if (unlikely(w->exposed))
3004 send_SET(w->name, w->openpipes);
3011 // ----------------------------------------------------------------------------
3012 // generate the charts
3014 static void send_charts_updates_to_netdata(struct target *root, const char *type, const char *title)
3017 int newly_added = 0;
3019 for(w = root ; w ; w = w->next) {
3020 if (w->target) continue;
3022 if (!w->exposed && w->processes) {
3025 if (debug || w->debug) fprintf(stderr, "apps.plugin: %s just added - regenerating charts.\n", w->name);
3029 // nothing more to show
3030 if(!newly_added && show_guest_time == show_guest_time_old) return;
3032 // we have something new to show
3033 // update the charts
3034 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);
3035 for (w = root; w ; w = w->next) {
3036 if(unlikely(w->exposed))
3037 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu %s\n", w->name, hz * RATES_DETAIL / 100, w->hidden ? "hidden" : "");
3040 fprintf(stdout, "CHART %s.mem '' '%s Real Memory (w/o shared)' 'MB' mem %s.mem stacked 20003 %d\n", type, title, type, update_every);
3041 for (w = root; w ; w = w->next) {
3042 if(unlikely(w->exposed))
3043 fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
3046 fprintf(stdout, "CHART %s.vmem '' '%s Virtual Memory Size' 'MB' mem %s.vmem stacked 20004 %d\n", type, title, type, update_every);
3047 for (w = root; w ; w = w->next) {
3048 if(unlikely(w->exposed))
3049 fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
3052 fprintf(stdout, "CHART %s.threads '' '%s Threads' 'threads' processes %s.threads stacked 20005 %d\n", type, title, type, update_every);
3053 for (w = root; w ; w = w->next) {
3054 if(unlikely(w->exposed))
3055 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3058 fprintf(stdout, "CHART %s.processes '' '%s Processes' 'processes' processes %s.processes stacked 20004 %d\n", type, title, type, update_every);
3059 for (w = root; w ; w = w->next) {
3060 if(unlikely(w->exposed))
3061 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3064 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);
3065 for (w = root; w ; w = w->next) {
3066 if(unlikely(w->exposed))
3067 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3070 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);
3071 for (w = root; w ; w = w->next) {
3072 if(unlikely(w->exposed))
3073 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3076 if(show_guest_time) {
3077 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);
3078 for (w = root; w; w = w->next) {
3079 if(unlikely(w->exposed))
3080 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3084 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);
3085 for (w = root; w ; w = w->next) {
3086 if(unlikely(w->exposed))
3087 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3090 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);
3091 for (w = root; w ; w = w->next) {
3092 if(unlikely(w->exposed))
3093 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3097 fprintf(stdout, "CHART %s.lreads '' '%s Disk Logical Reads' 'kilobytes/s' disk %s.lreads stacked 20042 %d\n", type, title, type, update_every);
3098 for (w = root; w ; w = w->next) {
3099 if(unlikely(w->exposed))
3100 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3103 fprintf(stdout, "CHART %s.lwrites '' '%s I/O Logical Writes' 'kilobytes/s' disk %s.lwrites stacked 20042 %d\n", type, title, type, update_every);
3104 for (w = root; w ; w = w->next) {
3105 if(unlikely(w->exposed))
3106 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3111 fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'blocks/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
3112 for (w = root; w ; w = w->next) {
3113 if(unlikely(w->exposed))
3114 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3117 fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'blocks/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
3118 for (w = root; w ; w = w->next) {
3119 if(unlikely(w->exposed))
3120 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3123 fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'kilobytes/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
3124 for (w = root; w ; w = w->next) {
3125 if(unlikely(w->exposed))
3126 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3129 fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'kilobytes/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
3130 for (w = root; w ; w = w->next) {
3131 if(unlikely(w->exposed))
3132 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3136 if(enable_file_charts) {
3137 fprintf(stdout, "CHART %s.files '' '%s Open Files' 'open files' disk %s.files stacked 20050 %d\n", type,
3138 title, type, update_every);
3139 for (w = root; w; w = w->next) {
3140 if (unlikely(w->exposed))
3141 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3144 fprintf(stdout, "CHART %s.sockets '' '%s Open Sockets' 'open sockets' net %s.sockets stacked 20051 %d\n",
3145 type, title, type, update_every);
3146 for (w = root; w; w = w->next) {
3147 if (unlikely(w->exposed))
3148 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3151 fprintf(stdout, "CHART %s.pipes '' '%s Pipes' 'open pipes' processes %s.pipes stacked 20053 %d\n", type,
3152 title, type, update_every);
3153 for (w = root; w; w = w->next) {
3154 if (unlikely(w->exposed))
3155 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3161 // ----------------------------------------------------------------------------
3162 // parse command line arguments
3164 int check_proc_1_io() {
3167 procfile *ff = procfile_open("/proc/1/io", NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
3168 if(!ff) goto cleanup;
3170 ff = procfile_readall(ff);
3171 if(!ff) goto cleanup;
3180 static void parse_args(int argc, char **argv)
3185 for(i = 1; i < argc; i++) {
3187 int n = (int)str2l(argv[i]);
3194 if(strcmp("version", argv[i]) == 0 || strcmp("-v", argv[i]) == 0) {
3195 printf("apps.plugin %s\n", VERSION);
3199 if(strcmp("test-permissions", argv[i]) == 0 || strcmp("-t", argv[i]) == 0) {
3200 if(!check_proc_1_io()) {
3201 perror("Tried to read /proc/1/io and it failed");
3208 if(strcmp("debug", argv[i]) == 0) {
3210 // debug_flags = 0xffffffff;
3214 if(strcmp("no-childs", argv[i]) == 0 || strcmp("without-childs", argv[i]) == 0) {
3215 include_exited_childs = 0;
3219 if(strcmp("with-childs", argv[i]) == 0) {
3220 include_exited_childs = 1;
3224 if(strcmp("with-guest", argv[i]) == 0) {
3225 enable_guest_charts = 1;
3229 if(strcmp("no-guest", argv[i]) == 0 || strcmp("without-guest", argv[i]) == 0) {
3230 enable_guest_charts = 0;
3234 if(strcmp("with-files", argv[i]) == 0) {
3235 enable_file_charts = 1;
3239 if(strcmp("no-files", argv[i]) == 0 || strcmp("without-files", argv[i]) == 0) {
3240 enable_file_charts = 0;
3244 if(strcmp("no-users", argv[i]) == 0 || strcmp("without-users", argv[i]) == 0) {
3245 enable_users_charts = 0;
3249 if(strcmp("no-groups", argv[i]) == 0 || strcmp("without-groups", argv[i]) == 0) {
3250 enable_groups_charts = 0;
3254 if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0) {
3257 " netdata apps.plugin %s\n"
3258 " Copyright (C) 2016-2017 Costa Tsaousis <costa@tsaousis.gr>\n"
3259 " Released under GNU General Public License v3 or later.\n"
3260 " All rights reserved.\n"
3262 " This program is a data collector plugin for netdata.\n"
3264 " Valid command line options:\n"
3266 " SECONDS set the data collection frequency\n"
3268 " debug enable debugging (lot of output)\n"
3271 " without-childs enable / disable aggregating exited\n"
3272 " children resources into parents\n"
3273 " (default is enabled)\n"
3276 " without-guest enable / disable reporting guest charts\n"
3277 " (default is disabled)\n"
3280 " without-files enable / disable reporting files, sockets, pipes\n"
3281 " (default is enabled)\n"
3283 " NAME read apps_NAME.conf instead of\n"
3284 " apps_groups.conf\n"
3285 " (default NAME=groups)\n"
3287 " version print program version and exit\n"
3299 error("Cannot understand option %s", argv[i]);
3303 if(freq > 0) update_every = freq;
3304 if(!name) name = "groups";
3306 if(read_apps_groups_conf(name)) {
3307 error("Cannot read process groups '%s/apps_%s.conf'. There are no internal defaults. Failing.", config_dir, name);
3312 static int am_i_running_as_root() {
3313 uid_t uid = getuid(), euid = geteuid();
3315 if(uid == 0 || euid == 0) {
3316 if(debug) info("I am running with escalated privileges, uid = %u, euid = %u.", uid, euid);
3320 if(debug) info("I am not running with escalated privileges, uid = %u, euid = %u.", uid, euid);
3324 #ifdef HAVE_CAPABILITY
3325 static int check_capabilities() {
3326 cap_t caps = cap_get_proc();
3328 error("Cannot get current capabilities.");
3332 info("Received my capabilities from the system.");
3336 cap_flag_value_t cfv = CAP_CLEAR;
3337 if(cap_get_flag(caps, CAP_DAC_READ_SEARCH, CAP_EFFECTIVE, &cfv) == -1) {
3338 error("Cannot find if CAP_DAC_READ_SEARCH is effective.");
3342 if(cfv != CAP_SET) {
3343 error("apps.plugin should run with CAP_DAC_READ_SEARCH.");
3347 info("apps.plugin runs with CAP_DAC_READ_SEARCH.");
3351 if(cap_get_flag(caps, CAP_SYS_PTRACE, CAP_EFFECTIVE, &cfv) == -1) {
3352 error("Cannot find if CAP_SYS_PTRACE is effective.");
3356 if(cfv != CAP_SET) {
3357 error("apps.plugin should run with CAP_SYS_PTRACE.");
3361 info("apps.plugin runs with CAP_SYS_PTRACE.");
3369 static int check_capabilities() {
3374 int main(int argc, char **argv) {
3375 // debug_flags = D_PROCFILE;
3377 // set the name for logging
3378 program_name = "apps.plugin";
3380 // disable syslog for apps.plugin
3381 error_log_syslog = 0;
3383 // set errors flood protection to 100 logs per hour
3384 error_log_errors_per_period = 100;
3385 error_log_throttle_period = 3600;
3387 netdata_configured_host_prefix = getenv("NETDATA_HOST_PREFIX");
3388 if(netdata_configured_host_prefix == NULL) {
3389 // info("NETDATA_HOST_PREFIX is not passed from netdata");
3390 netdata_configured_host_prefix = "";
3392 // else info("Found NETDATA_HOST_PREFIX='%s'", netdata_configured_host_prefix);
3394 config_dir = getenv("NETDATA_CONFIG_DIR");
3395 if(config_dir == NULL) {
3396 // info("NETDATA_CONFIG_DIR is not passed from netdata");
3397 config_dir = CONFIG_DIR;
3399 // else info("Found NETDATA_CONFIG_DIR='%s'", config_dir);
3401 #ifdef NETDATA_INTERNAL_CHECKS
3402 if(debug_flags != 0) {
3403 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
3404 if(setrlimit(RLIMIT_CORE, &rl) != 0)
3405 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
3406 #ifdef HAVE_SYS_PRCTL_H
3407 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
3410 #endif /* NETDATA_INTERNAL_CHECKS */
3412 procfile_adaptive_initial_allocation = 1;
3414 time_t started_t = now_monotonic_sec();
3416 get_system_pid_max();
3419 parse_args(argc, argv);
3421 if(!check_capabilities() && !am_i_running_as_root() && !check_proc_1_io()) {
3422 uid_t uid = getuid(), euid = geteuid();
3423 #ifdef HAVE_CAPABILITY
3424 error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
3425 "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
3426 "To enable capabilities run: sudo setcap cap_dac_read_search,cap_sys_ptrace+ep %s; "
3427 "To enable setuid to root run: sudo chown root %s; sudo chmod 4755 %s; "
3428 , uid, euid, argv[0], argv[0], argv[0]
3431 error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
3432 "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
3433 "Your system does not support capabilities. "
3434 "To enable setuid to root run: sudo chown root %s; sudo chmod 4755 %s; "
3435 , uid, euid, argv[0], argv[0]
3440 info("started on pid %d", getpid());
3442 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
3443 all_pids_sortlist = callocz(sizeof(pid_t), (size_t)pid_max);
3446 all_pids = callocz(sizeof(struct pid_stat *), (size_t) pid_max);
3448 usec_t step = update_every * USEC_PER_SEC;
3449 global_iterations_counter = 1;
3451 heartbeat_init(&hb);
3452 for(;1; global_iterations_counter++) {
3454 #ifdef NETDATA_PROFILING
3455 #warning "compiling for profiling"
3456 static int profiling_count=0;
3458 if(unlikely(profiling_count > 1000)) exit(0);
3460 heartbeat_next(&hb, step);
3463 if(!collect_data_for_all_processes()) {
3464 error("Cannot collect /proc data for running processes. Disabling apps.plugin...");
3465 printf("DISABLE\n");
3469 calculate_netdata_statistics();
3470 normalize_utilization(apps_groups_root_target);
3472 usec_t dt = send_resource_usage_to_netdata();
3474 // this is smart enough to show only newly added apps, when needed
3475 send_charts_updates_to_netdata(apps_groups_root_target, "apps", "Apps");
3477 if(likely(enable_users_charts))
3478 send_charts_updates_to_netdata(users_root_target, "users", "Users");
3480 if(likely(enable_groups_charts))
3481 send_charts_updates_to_netdata(groups_root_target, "groups", "User Groups");
3483 send_collected_data_to_netdata(apps_groups_root_target, "apps", dt);
3485 if(likely(enable_users_charts))
3486 send_collected_data_to_netdata(users_root_target, "users", dt);
3488 if(likely(enable_groups_charts))
3489 send_collected_data_to_netdata(groups_root_target, "groups", dt);
3493 show_guest_time_old = show_guest_time;
3496 fprintf(stderr, "apps.plugin: done Loop No %zu\n", global_iterations_counter);
3498 // restart check (14400 seconds)
3499 if(now_monotonic_sec() - started_t > 14400) exit(0);