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,
65 enable_file_charts = 0,
67 enable_file_charts = 1,
69 enable_users_charts = 1,
70 enable_groups_charts = 1,
71 include_exited_childs = 1;
74 // will be changed to getenv(NETDATA_CONFIG_DIR) if it exists
75 static char *config_dir = CONFIG_DIR;
77 // ----------------------------------------------------------------------------
79 // handled in code (automatically set)
82 show_guest_time = 0, // 1 when guest values are collected
83 show_guest_time_old = 0,
84 proc_pid_cmdline_is_needed = 0; // 1 when we need to read /proc/cmdline
87 // ----------------------------------------------------------------------------
91 global_iterations_counter = 1,
96 // ----------------------------------------------------------------------------
99 // With normalization we lower the collected metrics by a factor to make them
100 // match the total utilization of the system.
101 // The discrepancy exists because apps.plugin needs some time to collect all
102 // the metrics. This results in utilization that exceeds the total utilization
105 // With normalization we align the per-process utilization, to the total of
106 // the system. We first consume the exited children utilization and it the
107 // collected values is above the total, we proportionally scale each reported
110 // the total system time, as reported by /proc/stat
117 // the normalization ratios, as calculated by normalize_utilization()
118 double utime_fix_ratio = 1.0,
119 stime_fix_ratio = 1.0,
120 gtime_fix_ratio = 1.0,
121 minflt_fix_ratio = 1.0,
122 majflt_fix_ratio = 1.0,
123 cutime_fix_ratio = 1.0,
124 cstime_fix_ratio = 1.0,
125 cgtime_fix_ratio = 1.0,
126 cminflt_fix_ratio = 1.0,
127 cmajflt_fix_ratio = 1.0;
130 // ----------------------------------------------------------------------------
133 // target is the structure that processes are aggregated to be reported
136 // - Each entry in /etc/apps_groups.conf creates a target.
137 // - Each user and group used by a process in the system, creates a target.
140 char compare[MAX_COMPARE_NAME + 1];
141 uint32_t comparehash;
144 char id[MAX_NAME + 1];
147 char name[MAX_NAME + 1];
152 kernel_uint_t minflt;
153 kernel_uint_t cminflt;
154 kernel_uint_t majflt;
155 kernel_uint_t cmajflt;
159 kernel_uint_t cutime;
160 kernel_uint_t cstime;
161 kernel_uint_t cgtime;
162 kernel_uint_t num_threads;
163 // kernel_uint_t rss;
165 kernel_uint_t statm_size;
166 kernel_uint_t statm_resident;
167 kernel_uint_t statm_share;
168 // kernel_uint_t statm_text;
169 // kernel_uint_t statm_lib;
170 // kernel_uint_t statm_data;
171 // kernel_uint_t statm_dirty;
173 kernel_uint_t io_logical_bytes_read;
174 kernel_uint_t io_logical_bytes_written;
175 // kernel_uint_t io_read_calls;
176 // kernel_uint_t io_write_calls;
177 kernel_uint_t io_storage_bytes_read;
178 kernel_uint_t io_storage_bytes_written;
179 // kernel_uint_t io_cancelled_write_bytes;
184 kernel_uint_t openfiles;
185 kernel_uint_t openpipes;
186 kernel_uint_t opensockets;
187 kernel_uint_t openinotifies;
188 kernel_uint_t openeventfds;
189 kernel_uint_t opentimerfds;
190 kernel_uint_t opensignalfds;
191 kernel_uint_t openeventpolls;
192 kernel_uint_t openother;
194 unsigned int processes; // how many processes have been merged to this
195 int exposed; // if set, we have sent this to netdata
196 int hidden; // if set, we set the hidden flag on the dimension
199 int starts_with; // if set, the compare string matches only the
200 // beginning of the command
202 struct target *target; // the one that will be reported to netdata
207 *apps_groups_default_target = NULL, // the default target
208 *apps_groups_root_target = NULL, // apps_groups.conf defined
209 *users_root_target = NULL, // users
210 *groups_root_target = NULL; // user groups
213 apps_groups_targets_count = 0; // # of apps_groups.conf targets
216 // ----------------------------------------------------------------------------
219 // structure to store data for each process running
220 // see: man proc for the description of the fields
224 char comm[MAX_COMPARE_NAME + 1];
225 char cmdline[MAX_CMDLINE + 1];
237 // these are raw values collected
238 kernel_uint_t minflt_raw;
239 kernel_uint_t cminflt_raw;
240 kernel_uint_t majflt_raw;
241 kernel_uint_t cmajflt_raw;
242 kernel_uint_t utime_raw;
243 kernel_uint_t stime_raw;
244 kernel_uint_t gtime_raw; // guest_time
245 kernel_uint_t cutime_raw;
246 kernel_uint_t cstime_raw;
247 kernel_uint_t cgtime_raw; // cguest_time
250 kernel_uint_t minflt;
251 kernel_uint_t cminflt;
252 kernel_uint_t majflt;
253 kernel_uint_t cmajflt;
257 kernel_uint_t cutime;
258 kernel_uint_t cstime;
259 kernel_uint_t cgtime;
264 // int64_t itrealvalue;
265 // kernel_uint_t starttime;
266 // kernel_uint_t vsize;
267 // kernel_uint_t rss;
268 // kernel_uint_t rsslim;
269 // kernel_uint_t starcode;
270 // kernel_uint_t endcode;
271 // kernel_uint_t startstack;
272 // kernel_uint_t kstkesp;
273 // kernel_uint_t kstkeip;
276 // uint64_t sigignore;
277 // uint64_t sigcatch;
281 // int32_t exit_signal;
282 // int32_t processor;
283 // uint32_t rt_priority;
285 // kernel_uint_t delayacct_blkio_ticks;
290 kernel_uint_t statm_size;
291 kernel_uint_t statm_resident;
292 kernel_uint_t statm_share;
293 // kernel_uint_t statm_text;
294 // kernel_uint_t statm_lib;
295 // kernel_uint_t statm_data;
296 // kernel_uint_t statm_dirty;
298 kernel_uint_t io_logical_bytes_read_raw;
299 kernel_uint_t io_logical_bytes_written_raw;
300 // kernel_uint_t io_read_calls_raw;
301 // kernel_uint_t io_write_calls_raw;
302 kernel_uint_t io_storage_bytes_read_raw;
303 kernel_uint_t io_storage_bytes_written_raw;
304 // kernel_uint_t io_cancelled_write_bytes_raw;
306 kernel_uint_t io_logical_bytes_read;
307 kernel_uint_t io_logical_bytes_written;
308 // kernel_uint_t io_read_calls;
309 // kernel_uint_t io_write_calls;
310 kernel_uint_t io_storage_bytes_read;
311 kernel_uint_t io_storage_bytes_written;
312 // kernel_uint_t io_cancelled_write_bytes;
314 int *fds; // array of fds it uses
315 int fds_size; // the size of the fds array
317 int children_count; // number of processes directly referencing this
318 char keep:1; // 1 when we need to keep this process in memory even after it exited
319 int keeploops; // increases by 1 every time keep is 1 and updated 0
320 char updated:1; // 1 when the process is currently running
321 char merged:1; // 1 when it has been merged to its parent
322 char read:1; // 1 when we have already read this process for this iteration
324 int sortlist; // higher numbers = top on the process tree
325 // each process gets a unique number
327 struct target *target; // app_groups.conf targets
328 struct target *user_target; // uid based targets
329 struct target *group_target; // gid based targets
331 usec_t stat_collected_usec;
332 usec_t last_stat_collected_usec;
334 usec_t io_collected_usec;
335 usec_t last_io_collected_usec;
337 char *fds_dirname; // the full directory name in /proc/PID/fd
340 char *statm_filename;
342 char *cmdline_filename;
344 struct pid_stat *parent;
345 struct pid_stat *prev;
346 struct pid_stat *next;
349 // log each problem once per process
350 // log flood protection flags (log_thrown)
351 #define PID_LOG_IO 0x00000001
352 #define PID_LOG_STATM 0x00000002
353 #define PID_LOG_CMDLINE 0x00000004
354 #define PID_LOG_FDS 0x00000008
355 #define PID_LOG_STAT 0x00000010
357 static struct pid_stat
358 *root_of_pids = NULL, // global list of all processes running
359 **all_pids = NULL; // to avoid allocations, we pre-allocate the
360 // the entire pid space.
363 all_pids_count = 0; // the number of processes running
365 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
366 // Another pre-allocated list of all possible pids.
367 // We need it to pids and assign them a unique sortlist id, so that we
368 // read parents before children. This is needed to prevent a situation where
369 // a child is found running, but until we read its parent, it has exited and
370 // its parent has accumulated its resources.
372 *all_pids_sortlist = NULL;
375 // ----------------------------------------------------------------------------
378 // this is used to keep a global list of all open files of the system.
379 // it is needed in order to calculate the unique files processes have open.
381 #define FILE_DESCRIPTORS_INCREASE_STEP 100
383 // types for struct file_descriptor->type
384 typedef enum fd_filetype {
396 struct file_descriptor {
399 #ifdef NETDATA_INTERNAL_CHECKS
401 #endif /* NETDATA_INTERNAL_CHECKS */
415 // ----------------------------------------------------------------------------
416 // callback required by fatal()
418 void netdata_cleanup_and_exit(int ret) {
422 // ----------------------------------------------------------------------------
424 // aggregate all processes in groups, to have a limited number of dimensions
426 static struct target *get_users_target(uid_t uid) {
428 for(w = users_root_target ; w ; w = w->next)
429 if(w->uid == uid) return w;
431 w = callocz(sizeof(struct target), 1);
432 snprintfz(w->compare, MAX_COMPARE_NAME, "%u", uid);
433 w->comparehash = simple_hash(w->compare);
434 w->comparelen = strlen(w->compare);
436 snprintfz(w->id, MAX_NAME, "%u", uid);
437 w->idhash = simple_hash(w->id);
439 struct passwd *pw = getpwuid(uid);
441 snprintfz(w->name, MAX_NAME, "%u", uid);
443 snprintfz(w->name, MAX_NAME, "%s", pw->pw_name);
445 netdata_fix_chart_name(w->name);
449 w->next = users_root_target;
450 users_root_target = w;
453 fprintf(stderr, "apps.plugin: added uid %u ('%s') target\n", w->uid, w->name);
458 struct target *get_groups_target(gid_t gid)
461 for(w = groups_root_target ; w ; w = w->next)
462 if(w->gid == gid) return w;
464 w = callocz(sizeof(struct target), 1);
465 snprintfz(w->compare, MAX_COMPARE_NAME, "%u", gid);
466 w->comparehash = simple_hash(w->compare);
467 w->comparelen = strlen(w->compare);
469 snprintfz(w->id, MAX_NAME, "%u", gid);
470 w->idhash = simple_hash(w->id);
472 struct group *gr = getgrgid(gid);
474 snprintfz(w->name, MAX_NAME, "%u", gid);
476 snprintfz(w->name, MAX_NAME, "%s", gr->gr_name);
478 netdata_fix_chart_name(w->name);
482 w->next = groups_root_target;
483 groups_root_target = w;
486 fprintf(stderr, "apps.plugin: added gid %u ('%s') target\n", w->gid, w->name);
491 // find or create a new target
492 // there are targets that are just aggregated to other target (the second argument)
493 static struct target *get_apps_groups_target(const char *id, struct target *target, const char *name) {
494 int tdebug = 0, thidden = target?target->hidden:0, ends_with = 0;
495 const char *nid = id;
497 // extract the options
498 while(nid[0] == '-' || nid[0] == '+' || nid[0] == '*') {
499 if(nid[0] == '-') thidden = 1;
500 if(nid[0] == '+') tdebug = 1;
501 if(nid[0] == '*') ends_with = 1;
504 uint32_t hash = simple_hash(id);
506 // find if it already exists
507 struct target *w, *last = apps_groups_root_target;
508 for(w = apps_groups_root_target ; w ; w = w->next) {
509 if(w->idhash == hash && strncmp(nid, w->id, MAX_NAME) == 0)
515 // find an existing target
516 if(unlikely(!target)) {
517 while(*name == '-') {
518 if(*name == '-') thidden = 1;
522 for(target = apps_groups_root_target ; target != NULL ; target = target->next) {
523 if(!target->target && strcmp(name, target->name) == 0)
527 if(unlikely(debug)) {
529 fprintf(stderr, "apps.plugin: REUSING TARGET NAME '%s' on ID '%s'\n", target->name, target->id);
531 fprintf(stderr, "apps.plugin: NEW TARGET NAME '%s' on ID '%s'\n", name, id);
535 if(target && target->target)
536 fatal("Internal Error: request to link process '%s' to target '%s' which is linked to target '%s'", id, target->id, target->target->id);
538 w = callocz(sizeof(struct target), 1);
539 strncpyz(w->id, nid, MAX_NAME);
540 w->idhash = simple_hash(w->id);
542 if(unlikely(!target))
544 strncpyz(w->name, name, MAX_NAME);
547 strncpyz(w->name, nid, MAX_NAME);
549 strncpyz(w->compare, nid, MAX_COMPARE_NAME);
550 size_t len = strlen(w->compare);
551 if(w->compare[len - 1] == '*') {
552 w->compare[len - 1] = '\0';
555 w->ends_with = ends_with;
557 if(w->starts_with && w->ends_with)
558 proc_pid_cmdline_is_needed = 1;
560 w->comparehash = simple_hash(w->compare);
561 w->comparelen = strlen(w->compare);
567 // append it, to maintain the order in apps_groups.conf
568 if(last) last->next = w;
569 else apps_groups_root_target = w;
572 fprintf(stderr, "apps.plugin: ADDING TARGET ID '%s', process name '%s' (%s), aggregated on target '%s', options: %s %s\n"
574 , w->compare, (w->starts_with && w->ends_with)?"substring":((w->starts_with)?"prefix":((w->ends_with)?"suffix":"exact"))
575 , w->target?w->target->name:w->name
576 , (w->hidden)?"hidden":"-"
577 , (w->debug)?"debug":"-"
583 // read the apps_groups.conf file
584 static int read_apps_groups_conf(const char *file)
586 char filename[FILENAME_MAX + 1];
588 snprintfz(filename, FILENAME_MAX, "%s/apps_%s.conf", config_dir, file);
591 fprintf(stderr, "apps.plugin: process groups file: '%s'\n", filename);
593 // ----------------------------------------
595 procfile *ff = procfile_open(filename, " :\t", PROCFILE_FLAG_DEFAULT);
598 procfile_set_quotes(ff, "'\"");
600 ff = procfile_readall(ff);
604 size_t line, lines = procfile_lines(ff);
606 for(line = 0; line < lines ;line++) {
607 size_t word, words = procfile_linewords(ff, line);
610 char *name = procfile_lineword(ff, line, 0);
611 if(!name || !*name) continue;
613 // find a possibly existing target
614 struct target *w = NULL;
616 // loop through all words, skipping the first one (the name)
617 for(word = 0; word < words ;word++) {
618 char *s = procfile_lineword(ff, line, word);
619 if(!s || !*s) continue;
622 // is this the first word? skip it
623 if(s == name) continue;
626 struct target *n = get_apps_groups_target(s, w, name);
628 error("Cannot create target '%s' (line %zu, word %zu)", s, line, word);
632 // just some optimization
633 // to avoid searching for a target for each process
634 if(!w) w = n->target?n->target:n;
640 apps_groups_default_target = get_apps_groups_target("p+!o@w#e$i^r&7*5(-i)l-o_", NULL, "other"); // match nothing
641 if(!apps_groups_default_target)
642 fatal("Cannot create default target");
644 // allow the user to override group 'other'
645 if(apps_groups_default_target->target)
646 apps_groups_default_target = apps_groups_default_target->target;
652 // ----------------------------------------------------------------------------
653 // struct pid_stat management
655 static inline struct pid_stat *get_pid_entry(pid_t pid) {
656 if(unlikely(all_pids[pid]))
657 return all_pids[pid];
659 struct pid_stat *p = callocz(sizeof(struct pid_stat), 1);
660 p->fds = callocz(sizeof(int), MAX_SPARE_FDS);
661 p->fds_size = MAX_SPARE_FDS;
663 if(likely(root_of_pids))
664 root_of_pids->prev = p;
666 p->next = root_of_pids;
677 static inline void del_pid_entry(pid_t pid) {
678 struct pid_stat *p = all_pids[pid];
681 error("attempted to free pid %d that is not allocated.", pid);
686 fprintf(stderr, "apps.plugin: process %d %s exited, deleting it.\n", pid, p->comm);
688 if(root_of_pids == p)
689 root_of_pids = p->next;
691 if(p->next) p->next->prev = p->prev;
692 if(p->prev) p->prev->next = p->next;
695 freez(p->fds_dirname);
696 freez(p->stat_filename);
697 freez(p->statm_filename);
698 freez(p->io_filename);
699 freez(p->cmdline_filename);
702 all_pids[pid] = NULL;
706 // ----------------------------------------------------------------------------
708 static inline int managed_log(struct pid_stat *p, uint32_t log, int status) {
709 if(unlikely(!status)) {
710 // error("command failed log %u, errno %d", log, errno);
712 if(unlikely(debug || errno != ENOENT)) {
713 if(unlikely(debug || !(p->log_thrown & log))) {
714 p->log_thrown |= log;
717 error("Cannot process %s/proc/%d/io (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
721 error("Cannot process %s/proc/%d/statm (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
724 case PID_LOG_CMDLINE:
725 error("Cannot process %s/proc/%d/cmdline (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
729 error("Cannot process entries in %s/proc/%d/fd (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
736 error("unhandled error for pid %d, command '%s'", p->pid, p->comm);
743 else if(unlikely(p->log_thrown & log)) {
744 // error("unsetting log %u on pid %d", log, p->pid);
745 p->log_thrown &= ~log;
751 static inline void assign_target_to_pid(struct pid_stat *p) {
752 uint32_t hash = simple_hash(p->comm);
753 size_t pclen = strlen(p->comm);
756 for(w = apps_groups_root_target; w ; w = w->next) {
757 // if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \t\tcomparing '%s' with '%s'\n", w->compare, p->comm);
759 // find it - 4 cases:
760 // 1. the target is not a pattern
761 // 2. the target has the prefix
762 // 3. the target has the suffix
763 // 4. the target is something inside cmdline
765 if(unlikely(( (!w->starts_with && !w->ends_with && w->comparehash == hash && !strcmp(w->compare, p->comm))
766 || (w->starts_with && !w->ends_with && !strncmp(w->compare, p->comm, w->comparelen))
767 || (!w->starts_with && w->ends_with && pclen >= w->comparelen && !strcmp(w->compare, &p->comm[pclen - w->comparelen]))
768 || (proc_pid_cmdline_is_needed && w->starts_with && w->ends_with && strstr(p->cmdline, w->compare))
771 if(w->target) p->target = w->target;
774 if(debug || (p->target && p->target->debug))
775 fprintf(stderr, "apps.plugin: \t\t%s linked to target %s\n", p->comm, p->target->name);
783 // ----------------------------------------------------------------------------
784 // update pids from proc
786 static inline int read_proc_pid_cmdline(struct pid_stat *p) {
789 size_t i, bytes = MAX_CMDLINE;
794 mib[2] = KERN_PROC_ARGS;
796 if (unlikely(sysctl(mib, 4, p->cmdline, &bytes, NULL, 0)))
799 if(unlikely(!p->cmdline_filename)) {
800 char filename[FILENAME_MAX + 1];
801 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/cmdline", netdata_configured_host_prefix, p->pid);
802 p->cmdline_filename = strdupz(filename);
805 int fd = open(p->cmdline_filename, O_RDONLY, 0666);
806 if(unlikely(fd == -1)) goto cleanup;
808 ssize_t i, bytes = read(fd, p->cmdline, MAX_CMDLINE);
811 if(unlikely(bytes < 0)) goto cleanup;
814 p->cmdline[bytes] = '\0';
815 for(i = 0; i < bytes ; i++)
816 if(unlikely(!p->cmdline[i])) p->cmdline[i] = ' ';
819 fprintf(stderr, "Read file '%s' contents: %s\n", p->cmdline_filename, p->cmdline);
824 // copy the command to the command line
825 strncpyz(p->cmdline, p->comm, MAX_CMDLINE);
829 static inline int read_proc_pid_ownership(struct pid_stat *p, void *ptr) {
832 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
834 p->uid = proc_info->ki_uid;
835 p->gid = proc_info->ki_groups[0];
839 if(unlikely(!p->stat_filename)) {
840 error("pid %d does not have a stat_filename", p->pid);
844 // ----------------------------------------
848 if(stat(p->stat_filename, &st) != 0) {
849 error("Cannot stat file '%s'", p->stat_filename);
860 // ----------------------------------------------------------------------------
861 // macro to calculate the incremental rate of a value
862 // each parameter is accessed only ONCE - so it is safe to pass function calls
863 // or other macros as parameters
865 #define incremental_rate(rate_variable, last_kernel_variable, new_kernel_value, collected_usec, last_collected_usec) { \
866 kernel_uint_t _new_tmp = new_kernel_value; \
867 rate_variable = (_new_tmp - last_kernel_variable) * (USEC_PER_SEC * RATES_DETAIL) / (collected_usec - last_collected_usec); \
868 last_kernel_variable = _new_tmp; \
871 // the same macro for struct pid members
872 #define pid_incremental_rate(type, var, value) \
873 incremental_rate(var, var##_raw, value, p->type##_collected_usec, p->last_##type##_collected_usec)
876 // ----------------------------------------------------------------------------
878 static inline int read_proc_pid_stat(struct pid_stat *p, void *ptr) {
882 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
884 if (unlikely(proc_info->ki_tdflags & TDF_IDLETD))
887 static procfile *ff = NULL;
889 if(unlikely(!p->stat_filename)) {
890 char filename[FILENAME_MAX + 1];
891 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/stat", netdata_configured_host_prefix, p->pid);
892 p->stat_filename = strdupz(filename);
895 int set_quotes = (!ff)?1:0;
897 ff = procfile_reopen(ff, p->stat_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
898 if(unlikely(!ff)) goto cleanup;
900 // if(set_quotes) procfile_set_quotes(ff, "()");
901 if(unlikely(set_quotes))
902 procfile_set_open_close(ff, "(", ")");
904 ff = procfile_readall(ff);
905 if(unlikely(!ff)) goto cleanup;
908 p->last_stat_collected_usec = p->stat_collected_usec;
909 p->stat_collected_usec = now_monotonic_usec();
913 char *comm = proc_info->ki_comm;
914 p->ppid = proc_info->ki_ppid;
916 // p->pid = str2pid_t(procfile_lineword(ff, 0, 0));
917 char *comm = procfile_lineword(ff, 0, 1);
918 // p->state = *(procfile_lineword(ff, 0, 2));
919 p->ppid = (int32_t)str2pid_t(procfile_lineword(ff, 0, 3));
920 // p->pgrp = (int32_t)str2pid_t(procfile_lineword(ff, 0, 4));
921 // p->session = (int32_t)str2pid_t(procfile_lineword(ff, 0, 5));
922 // p->tty_nr = (int32_t)str2pid_t(procfile_lineword(ff, 0, 6));
923 // p->tpgid = (int32_t)str2pid_t(procfile_lineword(ff, 0, 7));
924 // p->flags = str2uint64_t(procfile_lineword(ff, 0, 8));
927 if(strcmp(p->comm, comm)) {
928 if(unlikely(debug)) {
930 fprintf(stderr, "apps.plugin: \tpid %d (%s) changed name to '%s'\n", p->pid, p->comm, comm);
932 fprintf(stderr, "apps.plugin: \tJust added %d (%s)\n", p->pid, comm);
935 strncpyz(p->comm, comm, MAX_COMPARE_NAME);
937 // /proc/<pid>/cmdline
938 if(likely(proc_pid_cmdline_is_needed))
939 managed_log(p, PID_LOG_CMDLINE, read_proc_pid_cmdline(p));
941 assign_target_to_pid(p);
945 pid_incremental_rate(stat, p->minflt, (kernel_uint_t)proc_info->ki_rusage.ru_minflt);
946 pid_incremental_rate(stat, p->cminflt, (kernel_uint_t)proc_info->ki_rusage_ch.ru_minflt);
947 pid_incremental_rate(stat, p->majflt, (kernel_uint_t)proc_info->ki_rusage.ru_majflt);
948 pid_incremental_rate(stat, p->cmajflt, (kernel_uint_t)proc_info->ki_rusage_ch.ru_majflt);
949 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);
950 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);
951 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);
952 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);
954 p->num_threads = proc_info->ki_numthreads;
956 if(enable_guest_charts) {
957 enable_guest_charts = 0;
958 info("Guest charts aren't supported by FreeBSD");
961 pid_incremental_rate(stat, p->minflt, str2kernel_uint_t(procfile_lineword(ff, 0, 9)));
962 pid_incremental_rate(stat, p->cminflt, str2kernel_uint_t(procfile_lineword(ff, 0, 10)));
963 pid_incremental_rate(stat, p->majflt, str2kernel_uint_t(procfile_lineword(ff, 0, 11)));
964 pid_incremental_rate(stat, p->cmajflt, str2kernel_uint_t(procfile_lineword(ff, 0, 12)));
965 pid_incremental_rate(stat, p->utime, str2kernel_uint_t(procfile_lineword(ff, 0, 13)));
966 pid_incremental_rate(stat, p->stime, str2kernel_uint_t(procfile_lineword(ff, 0, 14)));
967 pid_incremental_rate(stat, p->cutime, str2kernel_uint_t(procfile_lineword(ff, 0, 15)));
968 pid_incremental_rate(stat, p->cstime, str2kernel_uint_t(procfile_lineword(ff, 0, 16)));
969 // p->priority = str2kernel_uint_t(procfile_lineword(ff, 0, 17));
970 // p->nice = str2kernel_uint_t(procfile_lineword(ff, 0, 18));
971 p->num_threads = (int32_t)str2uint32_t(procfile_lineword(ff, 0, 19));
972 // p->itrealvalue = str2kernel_uint_t(procfile_lineword(ff, 0, 20));
973 // p->starttime = str2kernel_uint_t(procfile_lineword(ff, 0, 21));
974 // p->vsize = str2kernel_uint_t(procfile_lineword(ff, 0, 22));
975 // p->rss = str2kernel_uint_t(procfile_lineword(ff, 0, 23));
976 // p->rsslim = str2kernel_uint_t(procfile_lineword(ff, 0, 24));
977 // p->starcode = str2kernel_uint_t(procfile_lineword(ff, 0, 25));
978 // p->endcode = str2kernel_uint_t(procfile_lineword(ff, 0, 26));
979 // p->startstack = str2kernel_uint_t(procfile_lineword(ff, 0, 27));
980 // p->kstkesp = str2kernel_uint_t(procfile_lineword(ff, 0, 28));
981 // p->kstkeip = str2kernel_uint_t(procfile_lineword(ff, 0, 29));
982 // p->signal = str2kernel_uint_t(procfile_lineword(ff, 0, 30));
983 // p->blocked = str2kernel_uint_t(procfile_lineword(ff, 0, 31));
984 // p->sigignore = str2kernel_uint_t(procfile_lineword(ff, 0, 32));
985 // p->sigcatch = str2kernel_uint_t(procfile_lineword(ff, 0, 33));
986 // p->wchan = str2kernel_uint_t(procfile_lineword(ff, 0, 34));
987 // p->nswap = str2kernel_uint_t(procfile_lineword(ff, 0, 35));
988 // p->cnswap = str2kernel_uint_t(procfile_lineword(ff, 0, 36));
989 // p->exit_signal = str2kernel_uint_t(procfile_lineword(ff, 0, 37));
990 // p->processor = str2kernel_uint_t(procfile_lineword(ff, 0, 38));
991 // p->rt_priority = str2kernel_uint_t(procfile_lineword(ff, 0, 39));
992 // p->policy = str2kernel_uint_t(procfile_lineword(ff, 0, 40));
993 // p->delayacct_blkio_ticks = str2kernel_uint_t(procfile_lineword(ff, 0, 41));
995 if(enable_guest_charts) {
997 pid_incremental_rate(stat, p->gtime, str2kernel_uint_t(procfile_lineword(ff, 0, 42)));
998 pid_incremental_rate(stat, p->cgtime, str2kernel_uint_t(procfile_lineword(ff, 0, 43)));
1000 if (show_guest_time || p->gtime || p->cgtime) {
1001 p->utime -= (p->utime >= p->gtime) ? p->gtime : p->utime;
1002 p->cutime -= (p->cutime >= p->cgtime) ? p->cgtime : p->cutime;
1003 show_guest_time = 1;
1008 if(unlikely(debug || (p->target && p->target->debug)))
1009 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);
1011 if(unlikely(global_iterations_counter == 1)) {
1042 static inline int read_proc_pid_statm(struct pid_stat *p, void *ptr) {
1045 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
1047 static procfile *ff = NULL;
1049 if(unlikely(!p->statm_filename)) {
1050 char filename[FILENAME_MAX + 1];
1051 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/statm", netdata_configured_host_prefix, p->pid);
1052 p->statm_filename = strdupz(filename);
1055 ff = procfile_reopen(ff, p->statm_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
1056 if(unlikely(!ff)) goto cleanup;
1058 ff = procfile_readall(ff);
1059 if(unlikely(!ff)) goto cleanup;
1065 p->statm_size = proc_info->ki_size / sysconf(_SC_PAGESIZE);
1066 p->statm_resident = proc_info->ki_rssize;
1067 p->statm_share = 0; // do we have to use ru_ixrss here?
1069 p->statm_size = str2kernel_uint_t(procfile_lineword(ff, 0, 0));
1070 p->statm_resident = str2kernel_uint_t(procfile_lineword(ff, 0, 1));
1071 p->statm_share = str2kernel_uint_t(procfile_lineword(ff, 0, 2));
1072 // p->statm_text = str2kernel_uint_t(procfile_lineword(ff, 0, 3));
1073 // p->statm_lib = str2kernel_uint_t(procfile_lineword(ff, 0, 4));
1074 // p->statm_data = str2kernel_uint_t(procfile_lineword(ff, 0, 5));
1075 // p->statm_dirty = str2kernel_uint_t(procfile_lineword(ff, 0, 6));
1082 p->statm_resident = 0;
1084 // p->statm_text = 0;
1085 // p->statm_lib = 0;
1086 // p->statm_data = 0;
1087 // p->statm_dirty = 0;
1091 static inline int read_proc_pid_io(struct pid_stat *p, void *ptr) {
1094 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
1096 static procfile *ff = NULL;
1098 if(unlikely(!p->io_filename)) {
1099 char filename[FILENAME_MAX + 1];
1100 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/io", netdata_configured_host_prefix, p->pid);
1101 p->io_filename = strdupz(filename);
1105 ff = procfile_reopen(ff, p->io_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
1106 if(unlikely(!ff)) goto cleanup;
1108 ff = procfile_readall(ff);
1109 if(unlikely(!ff)) goto cleanup;
1114 p->last_io_collected_usec = p->io_collected_usec;
1115 p->io_collected_usec = now_monotonic_usec();
1118 pid_incremental_rate(io, p->io_storage_bytes_read, proc_info->ki_rusage.ru_inblock);
1119 pid_incremental_rate(io, p->io_storage_bytes_written, proc_info->ki_rusage.ru_oublock);
1121 pid_incremental_rate(io, p->io_logical_bytes_read, str2kernel_uint_t(procfile_lineword(ff, 0, 1)));
1122 pid_incremental_rate(io, p->io_logical_bytes_written, str2kernel_uint_t(procfile_lineword(ff, 1, 1)));
1123 // pid_incremental_rate(io, p->io_read_calls, str2kernel_uint_t(procfile_lineword(ff, 2, 1)));
1124 // pid_incremental_rate(io, p->io_write_calls, str2kernel_uint_t(procfile_lineword(ff, 3, 1)));
1125 pid_incremental_rate(io, p->io_storage_bytes_read, str2kernel_uint_t(procfile_lineword(ff, 4, 1)));
1126 pid_incremental_rate(io, p->io_storage_bytes_written, str2kernel_uint_t(procfile_lineword(ff, 5, 1)));
1127 // pid_incremental_rate(io, p->io_cancelled_write_bytes, str2kernel_uint_t(procfile_lineword(ff, 6, 1)));
1130 if(unlikely(global_iterations_counter == 1)) {
1131 p->io_logical_bytes_read = 0;
1132 p->io_logical_bytes_written = 0;
1133 // p->io_read_calls = 0;
1134 // p->io_write_calls = 0;
1135 p->io_storage_bytes_read = 0;
1136 p->io_storage_bytes_written = 0;
1137 // p->io_cancelled_write_bytes = 0;
1143 p->io_logical_bytes_read = 0;
1144 p->io_logical_bytes_written = 0;
1145 // p->io_read_calls = 0;
1146 // p->io_write_calls = 0;
1147 p->io_storage_bytes_read = 0;
1148 p->io_storage_bytes_written = 0;
1149 // p->io_cancelled_write_bytes = 0;
1153 static inline int read_proc_stat() {
1155 long cp_time[CPUSTATES];
1158 if (unlikely(CPUSTATES != 5)) {
1159 error("FREEBSD: There are %d CPU states (5 was expected)", CPUSTATES);
1162 if (unlikely(GETSYSCTL_BY_NAME("kern.cp_time", cp_time))) goto cleanup;
1164 static char filename[FILENAME_MAX + 1] = "";
1165 static procfile *ff = NULL;
1167 static kernel_uint_t utime_raw = 0, stime_raw = 0, gtime_raw = 0, gntime_raw = 0, ntime_raw = 0;
1168 static usec_t collected_usec = 0, last_collected_usec = 0;
1172 snprintfz(filename, FILENAME_MAX, "%s/proc/stat", netdata_configured_host_prefix);
1173 ff = procfile_open(filename, " \t:", PROCFILE_FLAG_DEFAULT);
1174 if(unlikely(!ff)) goto cleanup;
1177 ff = procfile_readall(ff);
1178 if(unlikely(!ff)) goto cleanup;
1181 last_collected_usec = collected_usec;
1182 collected_usec = now_monotonic_usec();
1186 // temporary - it is added global_ntime;
1187 kernel_uint_t global_ntime = 0;
1190 incremental_rate(global_utime, utime_raw, cp_time[0], collected_usec, last_collected_usec);
1191 incremental_rate(global_ntime, ntime_raw, cp_time[1], collected_usec, last_collected_usec);
1192 incremental_rate(global_stime, stime_raw, cp_time[2], collected_usec, last_collected_usec);
1194 incremental_rate(global_utime, utime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 1)), collected_usec, last_collected_usec);
1195 incremental_rate(global_ntime, ntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 2)), collected_usec, last_collected_usec);
1196 incremental_rate(global_stime, stime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 3)), collected_usec, last_collected_usec);
1197 incremental_rate(global_gtime, gtime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 10)), collected_usec, last_collected_usec);
1200 global_utime += global_ntime;
1203 if(enable_guest_charts) {
1204 enable_guest_charts = 0;
1205 info("Guest charts aren't supported by FreeBSD");
1208 if(enable_guest_charts) {
1209 // temporary - it is added global_ntime;
1210 kernel_uint_t global_gntime = 0;
1212 // guest nice time, on guest time
1213 incremental_rate(global_gntime, gntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 11)), collected_usec, last_collected_usec);
1215 global_gtime += global_gntime;
1217 // remove guest time from user time
1218 global_utime -= (global_utime > global_gtime) ? global_gtime : global_utime;
1222 if(unlikely(global_iterations_counter == 1)) {
1238 // ----------------------------------------------------------------------------
1240 int file_descriptor_compare(void* a, void* b) {
1241 #ifdef NETDATA_INTERNAL_CHECKS
1242 if(((struct file_descriptor *)a)->magic != 0x0BADCAFE || ((struct file_descriptor *)b)->magic != 0x0BADCAFE)
1243 error("Corrupted index data detected. Please report this.");
1244 #endif /* NETDATA_INTERNAL_CHECKS */
1246 if(((struct file_descriptor *)a)->hash < ((struct file_descriptor *)b)->hash)
1249 else if(((struct file_descriptor *)a)->hash > ((struct file_descriptor *)b)->hash)
1253 return strcmp(((struct file_descriptor *)a)->name, ((struct file_descriptor *)b)->name);
1256 int file_descriptor_iterator(avl *a) { if(a) {}; return 0; }
1258 avl_tree all_files_index = {
1260 file_descriptor_compare
1263 static struct file_descriptor *file_descriptor_find(const char *name, uint32_t hash) {
1264 struct file_descriptor tmp;
1265 tmp.hash = (hash)?hash:simple_hash(name);
1269 #ifdef NETDATA_INTERNAL_CHECKS
1270 tmp.magic = 0x0BADCAFE;
1271 #endif /* NETDATA_INTERNAL_CHECKS */
1273 return (struct file_descriptor *)avl_search(&all_files_index, (avl *) &tmp);
1276 #define file_descriptor_add(fd) avl_insert(&all_files_index, (avl *)(fd))
1277 #define file_descriptor_remove(fd) avl_remove(&all_files_index, (avl *)(fd))
1279 // ----------------------------------------------------------------------------
1281 static inline void file_descriptor_not_used(int id)
1283 if(id > 0 && id < all_files_size) {
1285 #ifdef NETDATA_INTERNAL_CHECKS
1286 if(all_files[id].magic != 0x0BADCAFE) {
1287 error("Ignoring request to remove empty file id %d.", id);
1290 #endif /* NETDATA_INTERNAL_CHECKS */
1293 fprintf(stderr, "apps.plugin: decreasing slot %d (count = %d).\n", id, all_files[id].count);
1295 if(all_files[id].count > 0) {
1296 all_files[id].count--;
1298 if(!all_files[id].count) {
1300 fprintf(stderr, "apps.plugin: >> slot %d is empty.\n", id);
1302 if(unlikely(file_descriptor_remove(&all_files[id]) != (void *)&all_files[id]))
1303 error("INTERNAL ERROR: removal of unused fd from index, removed a different fd");
1305 #ifdef NETDATA_INTERNAL_CHECKS
1306 all_files[id].magic = 0x00000000;
1307 #endif /* NETDATA_INTERNAL_CHECKS */
1312 error("Request to decrease counter of fd %d (%s), while the use counter is 0", id, all_files[id].name);
1314 else error("Request to decrease counter of fd %d, which is outside the array size (1 to %d)", id, all_files_size);
1317 static inline void all_files_grow() {
1318 void *old = all_files;
1321 // there is no empty slot
1323 fprintf(stderr, "apps.plugin: extending fd array to %d entries\n", all_files_size + FILE_DESCRIPTORS_INCREASE_STEP);
1325 all_files = reallocz(all_files, (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP) * sizeof(struct file_descriptor));
1327 // if the address changed, we have to rebuild the index
1328 // since all pointers are now invalid
1330 if(unlikely(old && old != (void *)all_files)) {
1332 fprintf(stderr, "apps.plugin: >> re-indexing.\n");
1334 all_files_index.root = NULL;
1335 for(i = 0; i < all_files_size; i++) {
1336 if(!all_files[i].count) continue;
1337 if(unlikely(file_descriptor_add(&all_files[i]) != (void *)&all_files[i]))
1338 error("INTERNAL ERROR: duplicate indexing of fd during realloc.");
1342 fprintf(stderr, "apps.plugin: >> re-indexing done.\n");
1345 // initialize the newly added entries
1347 for(i = all_files_size; i < (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP); i++) {
1348 all_files[i].count = 0;
1349 all_files[i].name = NULL;
1350 #ifdef NETDATA_INTERNAL_CHECKS
1351 all_files[i].magic = 0x00000000;
1352 #endif /* NETDATA_INTERNAL_CHECKS */
1353 all_files[i].pos = i;
1356 if(unlikely(!all_files_size)) all_files_len = 1;
1357 all_files_size += FILE_DESCRIPTORS_INCREASE_STEP;
1360 static inline int file_descriptor_set_on_empty_slot(const char *name, uint32_t hash, FD_FILETYPE type) {
1361 // check we have enough memory to add it
1362 if(!all_files || all_files_len == all_files_size)
1366 fprintf(stderr, "apps.plugin: >> searching for empty slot.\n");
1368 // search for an empty slot
1370 static int last_pos = 0;
1372 for(i = 0, c = last_pos ; i < all_files_size ; i++, c++) {
1373 if(c >= all_files_size) c = 0;
1374 if(c == 0) continue;
1376 if(!all_files[c].count) {
1378 fprintf(stderr, "apps.plugin: >> Examining slot %d.\n", c);
1380 #ifdef NETDATA_INTERNAL_CHECKS
1381 if(all_files[c].magic == 0x0BADCAFE && all_files[c].name && file_descriptor_find(all_files[c].name, all_files[c].hash))
1382 error("fd on position %d is not cleared properly. It still has %s in it.\n", c, all_files[c].name);
1383 #endif /* NETDATA_INTERNAL_CHECKS */
1386 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);
1388 freez((void *)all_files[c].name);
1389 all_files[c].name = NULL;
1397 if(i == all_files_size) {
1398 fatal("We should find an empty slot, but there isn't any");
1401 // else we have an empty slot in 'c'
1404 fprintf(stderr, "apps.plugin: >> updating slot %d.\n", c);
1406 all_files[c].name = strdupz(name);
1407 all_files[c].hash = hash;
1408 all_files[c].type = type;
1409 all_files[c].pos = c;
1410 all_files[c].count = 1;
1411 #ifdef NETDATA_INTERNAL_CHECKS
1412 all_files[c].magic = 0x0BADCAFE;
1413 #endif /* NETDATA_INTERNAL_CHECKS */
1414 if(unlikely(file_descriptor_add(&all_files[c]) != (void *)&all_files[c]))
1415 error("INTERNAL ERROR: duplicate indexing of fd.");
1418 fprintf(stderr, "apps.plugin: using fd position %d (name: %s)\n", c, all_files[c].name);
1423 static inline int file_descriptor_find_or_add(const char *name)
1425 uint32_t hash = simple_hash(name);
1428 fprintf(stderr, "apps.plugin: adding or finding name '%s' with hash %u\n", name, hash);
1430 struct file_descriptor *fd = file_descriptor_find(name, hash);
1434 fprintf(stderr, "apps.plugin: >> found on slot %d\n", fd->pos);
1442 if(likely(name[0] == '/')) type = FILETYPE_FILE;
1443 else if(likely(strncmp(name, "pipe:", 5) == 0)) type = FILETYPE_PIPE;
1444 else if(likely(strncmp(name, "socket:", 7) == 0)) type = FILETYPE_SOCKET;
1445 else if(likely(strncmp(name, "anon_inode:", 11) == 0)) {
1446 const char *t = &name[11];
1448 if(strcmp(t, "inotify") == 0) type = FILETYPE_INOTIFY;
1449 else if(strcmp(t, "[eventfd]") == 0) type = FILETYPE_EVENTFD;
1450 else if(strcmp(t, "[eventpoll]") == 0) type = FILETYPE_EVENTPOLL;
1451 else if(strcmp(t, "[timerfd]") == 0) type = FILETYPE_TIMERFD;
1452 else if(strcmp(t, "[signalfd]") == 0) type = FILETYPE_SIGNALFD;
1455 fprintf(stderr, "apps.plugin: FIXME: unknown anonymous inode: %s\n", name);
1457 type = FILETYPE_OTHER;
1460 else if(likely(strcmp(name, "inotify") == 0)) type = FILETYPE_INOTIFY;
1463 fprintf(stderr, "apps.plugin: FIXME: cannot understand linkname: %s\n", name);
1465 type = FILETYPE_OTHER;
1468 return file_descriptor_set_on_empty_slot(name, hash, type);
1471 static inline void make_all_pid_fds_negative(struct pid_stat *p) {
1472 int *fd = p->fds, *end = &p->fds[p->fds_size];
1479 static inline void cleanup_negative_pid_fds(struct pid_stat *p) {
1480 int *fd = p->fds, *fdend = &p->fds[p->fds_size];
1483 if(unlikely(*fd < 0)) {
1484 file_descriptor_not_used(-(*fd));
1492 static inline void zero_pid_fds(struct pid_stat *p, int first, int size) {
1493 int *fd = &p->fds[first], *end = &p->fds[first + size];
1494 while(fd < end) *fd++ = 0;
1497 static inline int read_pid_file_descriptors(struct pid_stat *p, void *ptr) {
1502 struct kinfo_file *fds;
1503 static char *fdsbuf;
1504 char *bfdsbuf, *efdsbuf;
1505 char fdsname[FILENAME_MAX + 1];
1507 // we make all pid fds negative, so that
1508 // we can detect unused file descriptors
1509 // at the end, to free them
1510 make_all_pid_fds_negative(p);
1514 mib[2] = KERN_PROC_FILEDESC;
1517 if (unlikely(sysctl(mib, 4, NULL, &size, NULL, 0))) {
1518 error("sysctl error: Can't get file descriptors data size for pid %d", p->pid);
1521 if (likely(size > 0))
1522 fdsbuf = reallocz(fdsbuf, size);
1523 if (unlikely(sysctl(mib, 4, fdsbuf, &size, NULL, 0))) {
1524 error("sysctl error: Can't get file descriptors data for pid %d", p->pid);
1529 efdsbuf = fdsbuf + size;
1530 while (bfdsbuf < efdsbuf) {
1531 fds = (struct kinfo_file *)(uintptr_t)bfdsbuf;
1532 if (unlikely(fds->kf_structsize == 0))
1535 // do not process file descriptors for current working directory, root directory,
1536 // jail directory, ktrace vnode, text vnode and controlling terminal
1537 if (unlikely(fds->kf_fd < 0)) {
1538 bfdsbuf += fds->kf_structsize;
1542 // get file descriptors array index
1543 int fdid = fds->kf_fd;
1545 // check if the fds array is small
1546 if (unlikely(fdid >= p->fds_size)) {
1547 // it is small, extend it
1549 if (unlikely(debug))
1550 fprintf(stderr, "apps.plugin: extending fd memory slots for %s from %d to %d\n", p->comm, p->fds_size, fdid + MAX_SPARE_FDS);
1552 p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(int));
1554 // and initialize it
1555 zero_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
1556 p->fds_size = fdid + MAX_SPARE_FDS;
1559 if (unlikely(p->fds[fdid] == 0)) {
1560 // we don't know this fd, get it
1562 switch (fds->kf_type) {
1565 if (unlikely(!fds->kf_path[0])) {
1566 sprintf(fdsname, "other: inode: %lu", fds->kf_un.kf_file.kf_file_fileid);
1569 sprintf(fdsname, "%s", fds->kf_path);
1571 case KF_TYPE_SOCKET:
1572 switch (fds->kf_sock_domain) {
1575 if (fds->kf_sock_protocol == IPPROTO_TCP)
1576 sprintf(fdsname, "socket: %d %lx", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sock_inpcb);
1578 sprintf(fdsname, "socket: %d %lx", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sock_pcb);
1581 /* print address of pcb and connected pcb */
1582 sprintf(fdsname, "socket: %lx %lx", fds->kf_un.kf_sock.kf_sock_pcb, fds->kf_un.kf_sock.kf_sock_unpconn);
1585 /* print protocol number and socket address */
1586 sprintf(fdsname, "socket: other: %d %s %s", fds->kf_sock_protocol, fds->kf_sa_local.__ss_pad1, fds->kf_sa_local.__ss_pad2);
1590 sprintf(fdsname, "pipe: %lu %lu", fds->kf_un.kf_pipe.kf_pipe_addr, fds->kf_un.kf_pipe.kf_pipe_peer);
1593 sprintf(fdsname, "other: pts: %u", fds->kf_un.kf_pts.kf_pts_dev);
1596 sprintf(fdsname, "other: shm: %s size: %lu", fds->kf_path, fds->kf_un.kf_file.kf_file_size);
1599 sprintf(fdsname, "other: sem: %u", fds->kf_un.kf_sem.kf_sem_value);
1602 sprintf(fdsname, "other: pid: %d fd: %d", fds->kf_un.kf_proc.kf_pid, fds->kf_fd);
1605 // if another process already has this, we will get
1607 p->fds[fdid] = file_descriptor_find_or_add(fdsname);
1610 // else make it positive again, we need it
1611 // of course, the actual file may have changed, but we don't care so much
1612 // FIXME: we could compare the inode as returned by readdir dirent structure
1615 p->fds[fdid] = -p->fds[fdid];
1617 bfdsbuf += fds->kf_structsize;
1620 if(unlikely(!p->fds_dirname)) {
1621 char dirname[FILENAME_MAX+1];
1622 snprintfz(dirname, FILENAME_MAX, "%s/proc/%d/fd", netdata_configured_host_prefix, p->pid);
1623 p->fds_dirname = strdupz(dirname);
1626 DIR *fds = opendir(p->fds_dirname);
1627 if(unlikely(!fds)) return 0;
1630 char fdname[FILENAME_MAX + 1];
1631 char linkname[FILENAME_MAX + 1];
1633 // we make all pid fds negative, so that
1634 // we can detect unused file descriptors
1635 // at the end, to free them
1636 make_all_pid_fds_negative(p);
1638 while((de = readdir(fds))) {
1639 // we need only files with numeric names
1641 if(unlikely(de->d_name[0] < '0' || de->d_name[0] > '9'))
1645 int fdid = (int) str2l(de->d_name);
1646 if(unlikely(fdid < 0)) continue;
1648 // check if the fds array is small
1649 if(unlikely(fdid >= p->fds_size)) {
1650 // it is small, extend it
1654 , "apps.plugin: extending fd memory slots for %s from %d to %d\n"
1657 , fdid + MAX_SPARE_FDS
1660 p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(int));
1662 // and initialize it
1663 zero_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
1664 p->fds_size = fdid + MAX_SPARE_FDS;
1667 if(unlikely(p->fds[fdid] == 0)) {
1668 // we don't know this fd, get it
1670 sprintf(fdname, "%s/proc/%d/fd/%s", netdata_configured_host_prefix, p->pid, de->d_name);
1671 ssize_t l = readlink(fdname, linkname, FILENAME_MAX);
1672 if(unlikely(l == -1)) {
1673 if(debug || (p->target && p->target->debug)) {
1674 if(debug || (p->target && p->target->debug))
1675 error("Cannot read link %s", fdname);
1684 // if another process already has this, we will get
1686 p->fds[fdid] = file_descriptor_find_or_add(linkname);
1689 // else make it positive again, we need it
1690 // of course, the actual file may have changed, but we don't care so much
1691 // FIXME: we could compare the inode as returned by readdir dirent structure
1692 // UPDATE: no we cannot use inodes - under /proc inodes don't change when the link is changed
1695 p->fds[fdid] = -p->fds[fdid];
1700 cleanup_negative_pid_fds(p);
1705 // ----------------------------------------------------------------------------
1707 static inline int print_process_and_parents(struct pid_stat *p, usec_t time) {
1708 char *prefix = "\\_ ";
1712 indent = print_process_and_parents(p->parent, p->stat_collected_usec);
1716 char buffer[indent + 1];
1719 for(i = 0; i < indent ;i++) buffer[i] = ' ';
1722 fprintf(stderr, " %s %s%s (%d %s %llu"
1727 , p->updated?"running":"exited"
1728 , p->stat_collected_usec - time
1731 if(p->utime) fprintf(stderr, " utime=" KERNEL_UINT_FORMAT, p->utime);
1732 if(p->stime) fprintf(stderr, " stime=" KERNEL_UINT_FORMAT, p->stime);
1733 if(p->gtime) fprintf(stderr, " gtime=" KERNEL_UINT_FORMAT, p->gtime);
1734 if(p->cutime) fprintf(stderr, " cutime=" KERNEL_UINT_FORMAT, p->cutime);
1735 if(p->cstime) fprintf(stderr, " cstime=" KERNEL_UINT_FORMAT, p->cstime);
1736 if(p->cgtime) fprintf(stderr, " cgtime=" KERNEL_UINT_FORMAT, p->cgtime);
1737 if(p->minflt) fprintf(stderr, " minflt=" KERNEL_UINT_FORMAT, p->minflt);
1738 if(p->cminflt) fprintf(stderr, " cminflt=" KERNEL_UINT_FORMAT, p->cminflt);
1739 if(p->majflt) fprintf(stderr, " majflt=" KERNEL_UINT_FORMAT, p->majflt);
1740 if(p->cmajflt) fprintf(stderr, " cmajflt=" KERNEL_UINT_FORMAT, p->cmajflt);
1741 fprintf(stderr, ")\n");
1746 static inline void print_process_tree(struct pid_stat *p, char *msg) {
1748 fprintf(stderr, "%s: process %s (%d, %s) with parents:\n", msg, p->comm, p->pid, p->updated?"running":"exited");
1749 print_process_and_parents(p, p->stat_collected_usec);
1752 static inline void find_lost_child_debug(struct pid_stat *pe, kernel_uint_t lost, int type) {
1754 struct pid_stat *p = NULL;
1756 for(p = root_of_pids; p ; p = p->next) {
1757 if(p == pe) continue;
1761 if(p->cminflt > lost) {
1762 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);
1768 if(p->cmajflt > lost) {
1769 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);
1775 if(p->cutime > lost) {
1776 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);
1782 if(p->cstime > lost) {
1783 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);
1789 if(p->cgtime > lost) {
1790 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);
1800 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);
1804 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);
1808 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);
1812 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);
1816 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);
1822 static inline kernel_uint_t remove_exited_child_from_parent(kernel_uint_t *field, kernel_uint_t *pfield) {
1823 kernel_uint_t absorbed = 0;
1825 if(*field > *pfield) {
1826 absorbed += *pfield;
1839 static inline void process_exited_processes() {
1842 for(p = root_of_pids; p ; p = p->next) {
1843 if(p->updated || !p->stat_collected_usec)
1846 kernel_uint_t utime = (p->utime_raw + p->cutime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1847 kernel_uint_t stime = (p->stime_raw + p->cstime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1848 kernel_uint_t gtime = (p->gtime_raw + p->cgtime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1849 kernel_uint_t minflt = (p->minflt_raw + p->cminflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1850 kernel_uint_t majflt = (p->majflt_raw + p->cmajflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1852 if(utime + stime + gtime + minflt + majflt == 0)
1855 if(unlikely(debug)) {
1857 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"
1860 , p->updated?"running":"exited"
1867 print_process_tree(p, "Searching parents");
1870 struct pid_stat *pp;
1871 for(pp = p->parent; pp ; pp = pp->parent) {
1872 if(!pp->updated) continue;
1874 kernel_uint_t absorbed;
1875 absorbed = remove_exited_child_from_parent(&utime, &pp->cutime);
1876 if(unlikely(debug && absorbed))
1877 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);
1879 absorbed = remove_exited_child_from_parent(&stime, &pp->cstime);
1880 if(unlikely(debug && absorbed))
1881 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);
1883 absorbed = remove_exited_child_from_parent(>ime, &pp->cgtime);
1884 if(unlikely(debug && absorbed))
1885 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);
1887 absorbed = remove_exited_child_from_parent(&minflt, &pp->cminflt);
1888 if(unlikely(debug && absorbed))
1889 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);
1891 absorbed = remove_exited_child_from_parent(&majflt, &pp->cmajflt);
1892 if(unlikely(debug && absorbed))
1893 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);
1896 if(unlikely(utime + stime + gtime + minflt + majflt > 0)) {
1897 if(unlikely(debug)) {
1898 if(utime) find_lost_child_debug(p, utime, 3);
1899 if(stime) find_lost_child_debug(p, stime, 4);
1900 if(gtime) find_lost_child_debug(p, gtime, 5);
1901 if(minflt) find_lost_child_debug(p, minflt, 1);
1902 if(majflt) find_lost_child_debug(p, majflt, 2);
1908 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"
1911 , p->updated?"running":"exited"
1919 for(pp = p->parent; pp ; pp = pp->parent) {
1920 if(pp->updated) break;
1924 fprintf(stderr, " > - KEEP - parent for another loop: %s (%d %s)\n"
1927 , pp->updated?"running":"exited"
1931 p->utime_raw = utime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1932 p->stime_raw = stime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1933 p->gtime_raw = gtime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1934 p->minflt_raw = minflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1935 p->majflt_raw = majflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1936 p->cutime_raw = p->cstime_raw = p->cgtime_raw = p->cminflt_raw = p->cmajflt_raw = 0;
1939 fprintf(stderr, "\n");
1941 else if(unlikely(debug)) {
1942 fprintf(stderr, " > totally absorbed - DONE - %s (%d %s)\n"
1945 , p->updated?"running":"exited"
1951 static inline void link_all_processes_to_their_parents(void) {
1952 struct pid_stat *p, *pp;
1954 // link all children to their parents
1955 // and update children count on parents
1956 for(p = root_of_pids; p ; p = p->next) {
1957 // for each process found
1962 if(unlikely(!p->ppid)) {
1967 pp = all_pids[p->ppid];
1970 pp->children_count++;
1972 if(unlikely(debug || (p->target && p->target->debug)))
1973 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);
1977 error("pid %d %s states parent %d, but the later does not exist.", p->pid, p->comm, p->ppid);
1982 // ----------------------------------------------------------------------------
1984 // 1. read all files in /proc
1985 // 2. for each numeric directory:
1986 // i. read /proc/pid/stat
1987 // ii. read /proc/pid/statm
1988 // iii. read /proc/pid/io (requires root access)
1989 // iii. read the entries in directory /proc/pid/fd (requires root access)
1991 // a. find or create a struct file_descriptor
1992 // b. cleanup any old/unused file_descriptors
1994 // after all these, some pids may be linked to targets, while others may not
1996 // in case of errors, only 1 every 1000 errors is printed
1997 // to avoid filling up all disk space
1998 // if debug is enabled, all errors are printed
2000 static int compar_pid(const void *pid1, const void *pid2) {
2002 struct pid_stat *p1 = all_pids[*((pid_t *)pid1)];
2003 struct pid_stat *p2 = all_pids[*((pid_t *)pid2)];
2005 if(p1->sortlist > p2->sortlist)
2011 static inline int collect_data_for_pid(pid_t pid, void *ptr) {
2012 if(unlikely(pid < INIT_PID || pid > pid_max)) {
2013 error("Invalid pid %d read (expected %d to %d). Ignoring process.", pid, INIT_PID, pid_max);
2017 struct pid_stat *p = get_pid_entry(pid);
2018 if(unlikely(!p || p->read)) return 0;
2021 // fprintf(stderr, "Reading process %d (%s), sortlist %d\n", p->pid, p->comm, p->sortlist);
2023 // --------------------------------------------------------------------
2026 if(unlikely(!managed_log(p, PID_LOG_STAT, read_proc_pid_stat(p, ptr))))
2027 // there is no reason to proceed if we cannot get its status
2030 read_proc_pid_ownership(p, ptr);
2032 // check its parent pid
2033 if(unlikely(p->ppid < 0 || p->ppid > pid_max)) {
2034 error("Pid %d (command '%s') states invalid parent pid %d. Using 0.", pid, p->comm, p->ppid);
2038 // --------------------------------------------------------------------
2041 managed_log(p, PID_LOG_IO, read_proc_pid_io(p, ptr));
2043 // --------------------------------------------------------------------
2044 // /proc/<pid>/statm
2046 if(unlikely(!managed_log(p, PID_LOG_STATM, read_proc_pid_statm(p, ptr))))
2047 // there is no reason to proceed if we cannot get its memory status
2050 // --------------------------------------------------------------------
2053 if(enable_file_charts)
2054 managed_log(p, PID_LOG_FDS, read_pid_file_descriptors(p, ptr));
2056 // --------------------------------------------------------------------
2059 if(unlikely(debug && include_exited_childs && all_pids_count && p->ppid && all_pids[p->ppid] && !all_pids[p->ppid]->read))
2060 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);
2062 // mark it as updated
2070 static int collect_data_for_all_processes(void) {
2071 struct pid_stat *p = NULL;
2075 size_t procbase_size;
2076 static struct kinfo_proc *procbase;
2082 mib[2] = KERN_PROC_PROC;
2083 if (unlikely(sysctl(mib, 3, NULL, &procbase_size, NULL, 0))) {
2084 error("sysctl error: Can't get processes data size");
2087 procbase = reallocz(procbase, procbase_size);
2088 if (unlikely(sysctl(mib, 3, procbase, &procbase_size, NULL, 0))) {
2089 error("sysctl error: Can't get processes data");
2092 procnum = procbase_size / sizeof(struct kinfo_proc);
2095 if(all_pids_count) {
2097 for(p = root_of_pids; p ; p = p->next) {
2098 p->read = 0; // mark it as not read, so that collect_data_for_pid() will read it
2101 p->children_count = 0;
2104 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
2105 all_pids_sortlist[slc++] = p->pid;
2109 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
2110 if(unlikely(slc != all_pids_count)) {
2111 error("Internal error: I was thinking I had %zu processes in my arrays, but it seems there are more.", all_pids_count);
2112 all_pids_count = slc;
2115 if(include_exited_childs) {
2116 // Read parents before childs
2117 // This is needed to prevent a situation where
2118 // a child is found running, but until we read
2119 // its parent, it has exited and its parent
2120 // has accumulated its resources.
2122 qsort((void *)all_pids_sortlist, (size_t)all_pids_count, sizeof(pid_t), compar_pid);
2124 // we forward read all running processes
2125 // collect_data_for_pid() is smart enough,
2126 // not to read the same pid twice per iteration
2127 for(slc = 0; slc < all_pids_count; slc++)
2128 collect_data_for_pid(all_pids_sortlist[slc], NULL);
2134 for (i = INIT_PID; i < procnum - INIT_PID; ++i) {
2135 pid_t pid = procbase[i].ki_pid;
2136 collect_data_for_pid(pid, &procbase[i]);
2139 char dirname[FILENAME_MAX + 1];
2141 snprintfz(dirname, FILENAME_MAX, "%s/proc", netdata_configured_host_prefix);
2142 DIR *dir = opendir(dirname);
2145 struct dirent *de = NULL;
2147 while((de = readdir(dir))) {
2148 char *endptr = de->d_name;
2150 if(unlikely(de->d_type != DT_DIR || de->d_name[0] < '0' || de->d_name[0] > '9'))
2153 pid_t pid = (pid_t) strtoul(de->d_name, &endptr, 10);
2155 // make sure we read a valid number
2156 if(unlikely(endptr == de->d_name || *endptr != '\0'))
2159 collect_data_for_pid(pid, NULL);
2167 // we need /proc/stat to normalize the cpu consumption of the exited childs
2170 // build the process tree
2171 link_all_processes_to_their_parents();
2173 // normally this is done
2174 // however we may have processes exited while we collected values
2175 // so let's find the exited ones
2176 // we do this by collecting the ownership of process
2177 // if we manage to get the ownership, the process still runs
2178 process_exited_processes();
2183 // ----------------------------------------------------------------------------
2184 // update statistics on the targets
2186 // 1. link all childs to their parents
2187 // 2. go from bottom to top, marking as merged all childs to their parents
2188 // this step links all parents without a target to the child target, if any
2189 // 3. link all top level processes (the ones not merged) to the default target
2190 // 4. go from top to bottom, linking all childs without a target, to their parent target
2191 // after this step, all processes have a target
2192 // [5. for each killed pid (updated = 0), remove its usage from its target]
2193 // 6. zero all apps_groups_targets
2194 // 7. concentrate all values on the apps_groups_targets
2195 // 8. remove all killed processes
2196 // 9. find the unique file count for each target
2197 // check: update_apps_groups_statistics()
2199 static void cleanup_exited_pids(void) {
2201 struct pid_stat *p = NULL;
2203 for(p = root_of_pids; p ;) {
2204 if(!p->updated && (!p->keep || p->keeploops > 0)) {
2205 if(unlikely(debug && (p->keep || p->keeploops)))
2206 fprintf(stderr, " > CLEANUP cannot keep exited process %d (%s) anymore - removing it.\n", p->pid, p->comm);
2208 for(c = 0; c < p->fds_size; c++)
2210 file_descriptor_not_used(p->fds[c]);
2219 if(unlikely(p->keep)) p->keeploops++;
2226 static void apply_apps_groups_targets_inheritance(void) {
2227 struct pid_stat *p = NULL;
2229 // children that do not have a target
2230 // inherit their target from their parent
2231 int found = 1, loops = 0;
2233 if(unlikely(debug)) loops++;
2235 for(p = root_of_pids; p ; p = p->next) {
2236 // if this process does not have a target
2237 // and it has a parent
2238 // and its parent has a target
2239 // then, set the parent's target to this process
2240 if(unlikely(!p->target && p->parent && p->parent->target)) {
2241 p->target = p->parent->target;
2244 if(debug || (p->target && p->target->debug))
2245 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);
2250 // find all the procs with 0 childs and merge them to their parents
2251 // repeat, until nothing more can be done.
2255 if(unlikely(debug)) loops++;
2258 for(p = root_of_pids; p ; p = p->next) {
2259 if(unlikely(!p->sortlist && !p->children_count))
2260 p->sortlist = sortlist++;
2262 // if this process does not have any children
2263 // and is not already merged
2265 // and its parent has children
2266 // and the target of this process and its parent is the same, or the parent does not have a target
2267 // and its parent is not init
2268 // then, mark them as merged.
2273 && p->parent->children_count
2274 && (p->target == p->parent->target || !p->parent->target)
2275 && p->ppid != INIT_PID
2277 p->parent->children_count--;
2280 // the parent inherits the child's target, if it does not have a target itself
2281 if(unlikely(p->target && !p->parent->target)) {
2282 p->parent->target = p->target;
2284 if(debug || (p->target && p->target->debug))
2285 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);
2293 fprintf(stderr, "apps.plugin: TARGET INHERITANCE: merged %d processes\n", found);
2296 // init goes always to default target
2297 if(all_pids[INIT_PID])
2298 all_pids[INIT_PID]->target = apps_groups_default_target;
2300 // give a default target on all top level processes
2301 if(unlikely(debug)) loops++;
2302 for(p = root_of_pids; p ; p = p->next) {
2303 // if the process is not merged itself
2304 // then is is a top level process
2305 if(unlikely(!p->merged && !p->target))
2306 p->target = apps_groups_default_target;
2308 // make sure all processes have a sortlist
2309 if(unlikely(!p->sortlist))
2310 p->sortlist = sortlist++;
2314 all_pids[1]->sortlist = sortlist++;
2316 // give a target to all merged child processes
2319 if(unlikely(debug)) loops++;
2321 for(p = root_of_pids; p ; p = p->next) {
2322 if(unlikely(!p->target && p->merged && p->parent && p->parent->target)) {
2323 p->target = p->parent->target;
2326 if(debug || (p->target && p->target->debug))
2327 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);
2333 fprintf(stderr, "apps.plugin: apply_apps_groups_targets_inheritance() made %d loops on the process tree\n", loops);
2336 static size_t zero_all_targets(struct target *root) {
2340 for (w = root; w ; w = w->next) {
2358 w->statm_resident = 0;
2360 // w->statm_text = 0;
2361 // w->statm_lib = 0;
2362 // w->statm_data = 0;
2363 // w->statm_dirty = 0;
2365 w->io_logical_bytes_read = 0;
2366 w->io_logical_bytes_written = 0;
2367 // w->io_read_calls = 0;
2368 // w->io_write_calls = 0;
2369 w->io_storage_bytes_read = 0;
2370 w->io_storage_bytes_written = 0;
2371 // w->io_cancelled_write_bytes = 0;
2373 // zero file counters
2375 memset(w->target_fds, 0, sizeof(int) * w->target_fds_size);
2379 w->openinotifies = 0;
2380 w->openeventfds = 0;
2381 w->opentimerfds = 0;
2382 w->opensignalfds = 0;
2383 w->openeventpolls = 0;
2391 static inline void reallocate_target_fds(struct target *w) {
2395 if(unlikely(!w->target_fds || w->target_fds_size < all_files_size)) {
2396 w->target_fds = reallocz(w->target_fds, sizeof(int) * all_files_size);
2397 memset(&w->target_fds[w->target_fds_size], 0, sizeof(int) * (all_files_size - w->target_fds_size));
2398 w->target_fds_size = all_files_size;
2402 static inline void aggregate_fd_on_target(int fd, struct target *w) {
2406 if(unlikely(w->target_fds[fd])) {
2407 // it is already aggregated
2408 // just increase its usage counter
2409 w->target_fds[fd]++;
2413 // increase its usage counter
2414 // so that we will not add it again
2415 w->target_fds[fd]++;
2417 switch(all_files[fd].type) {
2426 case FILETYPE_SOCKET:
2430 case FILETYPE_INOTIFY:
2434 case FILETYPE_EVENTFD:
2438 case FILETYPE_TIMERFD:
2442 case FILETYPE_SIGNALFD:
2446 case FILETYPE_EVENTPOLL:
2447 w->openeventpolls++;
2450 case FILETYPE_OTHER:
2456 static inline void aggregate_pid_fds_on_targets(struct pid_stat *p) {
2458 if(unlikely(!p->updated)) {
2459 // the process is not running
2463 struct target *w = p->target, *u = p->user_target, *g = p->group_target;
2465 reallocate_target_fds(w);
2466 reallocate_target_fds(u);
2467 reallocate_target_fds(g);
2469 int c, size = p->fds_size, *fds = p->fds;
2470 for(c = 0; c < size ;c++) {
2473 if(likely(fd <= 0 || fd >= all_files_size))
2476 aggregate_fd_on_target(fd, w);
2477 aggregate_fd_on_target(fd, u);
2478 aggregate_fd_on_target(fd, g);
2482 static inline void aggregate_pid_on_target(struct target *w, struct pid_stat *p, struct target *o) {
2485 if(unlikely(!p->updated)) {
2486 // the process is not running
2491 error("pid %d %s was left without a target!", p->pid, p->comm);
2495 w->cutime += p->cutime;
2496 w->cstime += p->cstime;
2497 w->cgtime += p->cgtime;
2498 w->cminflt += p->cminflt;
2499 w->cmajflt += p->cmajflt;
2501 w->utime += p->utime;
2502 w->stime += p->stime;
2503 w->gtime += p->gtime;
2504 w->minflt += p->minflt;
2505 w->majflt += p->majflt;
2507 // w->rss += p->rss;
2509 w->statm_size += p->statm_size;
2510 w->statm_resident += p->statm_resident;
2511 w->statm_share += p->statm_share;
2512 // w->statm_text += p->statm_text;
2513 // w->statm_lib += p->statm_lib;
2514 // w->statm_data += p->statm_data;
2515 // w->statm_dirty += p->statm_dirty;
2517 w->io_logical_bytes_read += p->io_logical_bytes_read;
2518 w->io_logical_bytes_written += p->io_logical_bytes_written;
2519 // w->io_read_calls += p->io_read_calls;
2520 // w->io_write_calls += p->io_write_calls;
2521 w->io_storage_bytes_read += p->io_storage_bytes_read;
2522 w->io_storage_bytes_written += p->io_storage_bytes_written;
2523 // w->io_cancelled_write_bytes += p->io_cancelled_write_bytes;
2526 w->num_threads += p->num_threads;
2528 if(unlikely(debug || w->debug))
2529 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);
2532 static void calculate_netdata_statistics(void) {
2534 apply_apps_groups_targets_inheritance();
2536 zero_all_targets(users_root_target);
2537 zero_all_targets(groups_root_target);
2538 apps_groups_targets_count = zero_all_targets(apps_groups_root_target);
2540 // this has to be done, before the cleanup
2541 struct pid_stat *p = NULL;
2542 struct target *w = NULL, *o = NULL;
2544 // concentrate everything on the targets
2545 for(p = root_of_pids; p ; p = p->next) {
2547 // --------------------------------------------------------------------
2548 // apps_groups target
2550 aggregate_pid_on_target(p->target, p, NULL);
2553 // --------------------------------------------------------------------
2557 if(likely(p->user_target && p->user_target->uid == p->uid))
2560 if(unlikely(debug && p->user_target))
2561 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);
2563 w = p->user_target = get_users_target(p->uid);
2566 aggregate_pid_on_target(w, p, o);
2569 // --------------------------------------------------------------------
2570 // user group target
2572 o = p->group_target;
2573 if(likely(p->group_target && p->group_target->gid == p->gid))
2574 w = p->group_target;
2576 if(unlikely(debug && p->group_target))
2577 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);
2579 w = p->group_target = get_groups_target(p->gid);
2582 aggregate_pid_on_target(w, p, o);
2585 // --------------------------------------------------------------------
2586 // aggregate all file descriptors
2588 if(enable_file_charts)
2589 aggregate_pid_fds_on_targets(p);
2592 cleanup_exited_pids();
2595 // ----------------------------------------------------------------------------
2596 // update chart dimensions
2598 int print_calculated_number(char *str, calculated_number value) { (void)str; (void)value; return 0; }
2600 static inline void send_BEGIN(const char *type, const char *id, usec_t usec) {
2601 fprintf(stdout, "BEGIN %s.%s %llu\n", type, id, usec);
2604 static inline void send_SET(const char *name, kernel_uint_t value) {
2605 fprintf(stdout, "SET %s = " KERNEL_UINT_FORMAT "\n", name, value);
2608 static inline void send_END(void) {
2609 fprintf(stdout, "END\n");
2612 static usec_t send_resource_usage_to_netdata() {
2613 static struct timeval last = { 0, 0 };
2614 static struct rusage me_last;
2624 now_monotonic_timeval(&last);
2625 getrusage(RUSAGE_SELF, &me_last);
2627 // the first time, give a zero to allow
2628 // netdata calibrate to the current time
2629 // usec = update_every * USEC_PER_SEC;
2635 now_monotonic_timeval(&now);
2636 getrusage(RUSAGE_SELF, &me);
2638 usec = dt_usec(&now, &last);
2639 cpuuser = me.ru_utime.tv_sec * USEC_PER_SEC + me.ru_utime.tv_usec;
2640 cpusyst = me.ru_stime.tv_sec * USEC_PER_SEC + me.ru_stime.tv_usec;
2642 memmove(&last, &now, sizeof(struct timeval));
2643 memmove(&me_last, &me, sizeof(struct rusage));
2646 static char created_charts = 0;
2647 if(unlikely(!created_charts)) {
2651 , "CHART netdata.apps_cpu '' 'Apps Plugin CPU' 'milliseconds/s' apps.plugin netdata.apps_cpu stacked 140000 %1$d\n"
2652 "DIMENSION user '' incremental 1 1000\n"
2653 "DIMENSION system '' incremental 1 1000\n"
2654 "CHART netdata.apps_files '' 'Apps Plugin Files' 'files/s' apps.plugin netdata.apps_files line 140001 %1$d\n"
2655 "DIMENSION calls '' incremental 1 1\n"
2656 "DIMENSION files '' incremental 1 1\n"
2657 "DIMENSION pids '' absolute 1 1\n"
2658 "DIMENSION fds '' absolute 1 1\n"
2659 "DIMENSION targets '' absolute 1 1\n"
2660 "CHART netdata.apps_fix '' 'Apps Plugin Normalization Ratios' 'percentage' apps.plugin netdata.apps_fix line 140002 %1$d\n"
2661 "DIMENSION utime '' absolute 1 %2$llu\n"
2662 "DIMENSION stime '' absolute 1 %2$llu\n"
2663 "DIMENSION gtime '' absolute 1 %2$llu\n"
2664 "DIMENSION minflt '' absolute 1 %2$llu\n"
2665 "DIMENSION majflt '' absolute 1 %2$llu\n"
2670 if(include_exited_childs)
2672 , "CHART netdata.apps_children_fix '' 'Apps Plugin Exited Children Normalization Ratios' 'percentage' apps.plugin netdata.apps_children_fix line 140003 %1$d\n"
2673 "DIMENSION cutime '' absolute 1 %2$llu\n"
2674 "DIMENSION cstime '' absolute 1 %2$llu\n"
2675 "DIMENSION cgtime '' absolute 1 %2$llu\n"
2676 "DIMENSION cminflt '' absolute 1 %2$llu\n"
2677 "DIMENSION cmajflt '' absolute 1 %2$llu\n"
2684 "BEGIN netdata.apps_cpu %llu\n"
2686 "SET system = %llu\n"
2688 "BEGIN netdata.apps_files %llu\n"
2693 "SET targets = %zu\n"
2695 "BEGIN netdata.apps_fix %llu\n"
2710 , apps_groups_targets_count
2712 , (unsigned int)(utime_fix_ratio * 100 * RATES_DETAIL)
2713 , (unsigned int)(stime_fix_ratio * 100 * RATES_DETAIL)
2714 , (unsigned int)(gtime_fix_ratio * 100 * RATES_DETAIL)
2715 , (unsigned int)(minflt_fix_ratio * 100 * RATES_DETAIL)
2716 , (unsigned int)(majflt_fix_ratio * 100 * RATES_DETAIL)
2719 if(include_exited_childs)
2721 "BEGIN netdata.apps_children_fix %llu\n"
2725 "SET cminflt = %u\n"
2726 "SET cmajflt = %u\n"
2729 , (unsigned int)(cutime_fix_ratio * 100 * RATES_DETAIL)
2730 , (unsigned int)(cstime_fix_ratio * 100 * RATES_DETAIL)
2731 , (unsigned int)(cgtime_fix_ratio * 100 * RATES_DETAIL)
2732 , (unsigned int)(cminflt_fix_ratio * 100 * RATES_DETAIL)
2733 , (unsigned int)(cmajflt_fix_ratio * 100 * RATES_DETAIL)
2739 static void normalize_utilization(struct target *root) {
2742 // childs processing introduces spikes
2743 // here we try to eliminate them by disabling childs processing either for specific dimensions
2744 // or entirely. Of course, either way, we disable it just a single iteration.
2746 kernel_uint_t max_time = processors * hz * RATES_DETAIL;
2747 kernel_uint_t utime = 0, cutime = 0, stime = 0, cstime = 0, gtime = 0, cgtime = 0, minflt = 0, cminflt = 0, majflt = 0, cmajflt = 0;
2749 if(global_utime > max_time) global_utime = max_time;
2750 if(global_stime > max_time) global_stime = max_time;
2751 if(global_gtime > max_time) global_gtime = max_time;
2753 for(w = root; w ; w = w->next) {
2754 if(w->target || (!w->processes && !w->exposed)) continue;
2759 cutime += w->cutime;
2760 cstime += w->cstime;
2761 cgtime += w->cgtime;
2763 minflt += w->minflt;
2764 majflt += w->majflt;
2765 cminflt += w->cminflt;
2766 cmajflt += w->cmajflt;
2769 if((global_utime || global_stime || global_gtime) && (utime || stime || gtime)) {
2770 if(global_utime + global_stime + global_gtime > utime + cutime + stime + cstime + gtime + cgtime) {
2771 // everything we collected fits
2777 cgtime_fix_ratio = 1.0; //(double)(global_utime + global_stime) / (double)(utime + cutime + stime + cstime);
2779 else if(global_utime + global_stime > utime + stime) {
2780 // childrens resources are too high
2781 // lower only the children resources
2784 gtime_fix_ratio = 1.0;
2787 cgtime_fix_ratio = (double)((global_utime + global_stime) - (utime + stime)) / (double)(cutime + cstime);
2790 // even running processes are unrealistic
2791 // zero the children resources
2792 // lower the running processes resources
2795 gtime_fix_ratio = (double)(global_utime + global_stime) / (double)(utime + stime);
2798 cgtime_fix_ratio = 0.0;
2807 cgtime_fix_ratio = 0.0;
2810 if(utime_fix_ratio > 1.0) utime_fix_ratio = 1.0;
2811 if(cutime_fix_ratio > 1.0) cutime_fix_ratio = 1.0;
2812 if(stime_fix_ratio > 1.0) stime_fix_ratio = 1.0;
2813 if(cstime_fix_ratio > 1.0) cstime_fix_ratio = 1.0;
2814 if(gtime_fix_ratio > 1.0) gtime_fix_ratio = 1.0;
2815 if(cgtime_fix_ratio > 1.0) cgtime_fix_ratio = 1.0;
2817 // if(utime_fix_ratio < 0.0) utime_fix_ratio = 0.0;
2818 // if(cutime_fix_ratio < 0.0) cutime_fix_ratio = 0.0;
2819 // if(stime_fix_ratio < 0.0) stime_fix_ratio = 0.0;
2820 // if(cstime_fix_ratio < 0.0) cstime_fix_ratio = 0.0;
2821 // if(gtime_fix_ratio < 0.0) gtime_fix_ratio = 0.0;
2822 // if(cgtime_fix_ratio < 0.0) cgtime_fix_ratio = 0.0;
2825 // we use cpu time to normalize page faults
2826 // the problem is that to find the proper max values
2827 // for page faults we have to parse /proc/vmstat
2828 // which is quite big to do it again (netdata does it already)
2830 // a better solution could be to somehow have netdata
2831 // do this normalization for us
2833 if(utime || stime || gtime)
2835 minflt_fix_ratio = (double)(utime * utime_fix_ratio + stime * stime_fix_ratio + gtime * gtime_fix_ratio) / (double)(utime + stime + gtime);
2838 majflt_fix_ratio = 1.0;
2840 if(cutime || cstime || cgtime)
2842 cminflt_fix_ratio = (double)(cutime * cutime_fix_ratio + cstime * cstime_fix_ratio + cgtime * cgtime_fix_ratio) / (double)(cutime + cstime + cgtime);
2845 cmajflt_fix_ratio = 1.0;
2849 if(unlikely(debug)) {
2851 "SYSTEM: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
2852 "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 " "
2853 "DELTA: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
2854 "FIX: u=%0.2f s=%0.2f g=%0.2f cu=%0.2f cs=%0.2f cg=%0.2f "
2855 "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 " "
2866 , utime + cutime - global_utime
2867 , stime + cstime - global_stime
2868 , gtime + cgtime - global_gtime
2875 , (kernel_uint_t)(utime * utime_fix_ratio)
2876 , (kernel_uint_t)(stime * stime_fix_ratio)
2877 , (kernel_uint_t)(gtime * gtime_fix_ratio)
2878 , (kernel_uint_t)(cutime * cutime_fix_ratio)
2879 , (kernel_uint_t)(cstime * cstime_fix_ratio)
2880 , (kernel_uint_t)(cgtime * cgtime_fix_ratio)
2885 static void send_collected_data_to_netdata(struct target *root, const char *type, usec_t usec) {
2888 send_BEGIN(type, "cpu", usec);
2889 for (w = root; w ; w = w->next) {
2890 if(unlikely(w->exposed))
2891 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));
2895 send_BEGIN(type, "cpu_user", usec);
2896 for (w = root; w ; w = w->next) {
2897 if(unlikely(w->exposed))
2898 send_SET(w->name, (kernel_uint_t)(w->utime * utime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cutime * cutime_fix_ratio)):0ULL));
2902 send_BEGIN(type, "cpu_system", usec);
2903 for (w = root; w ; w = w->next) {
2904 if(unlikely(w->exposed))
2905 send_SET(w->name, (kernel_uint_t)(w->stime * stime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cstime * cstime_fix_ratio)):0ULL));
2909 if(show_guest_time) {
2910 send_BEGIN(type, "cpu_guest", usec);
2911 for (w = root; w ; w = w->next) {
2912 if(unlikely(w->exposed))
2913 send_SET(w->name, (kernel_uint_t)(w->gtime * gtime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cgtime * cgtime_fix_ratio)):0ULL));
2918 send_BEGIN(type, "threads", usec);
2919 for (w = root; w ; w = w->next) {
2920 if(unlikely(w->exposed))
2921 send_SET(w->name, w->num_threads);
2925 send_BEGIN(type, "processes", usec);
2926 for (w = root; w ; w = w->next) {
2927 if(unlikely(w->exposed))
2928 send_SET(w->name, w->processes);
2932 send_BEGIN(type, "mem", usec);
2933 for (w = root; w ; w = w->next) {
2934 if(unlikely(w->exposed))
2935 send_SET(w->name, (w->statm_resident > w->statm_share)?(w->statm_resident - w->statm_share):0ULL);
2939 send_BEGIN(type, "vmem", usec);
2940 for (w = root; w ; w = w->next) {
2941 if(unlikely(w->exposed))
2942 send_SET(w->name, w->statm_size);
2946 send_BEGIN(type, "minor_faults", usec);
2947 for (w = root; w ; w = w->next) {
2948 if(unlikely(w->exposed))
2949 send_SET(w->name, (kernel_uint_t)(w->minflt * minflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cminflt * cminflt_fix_ratio)):0ULL));
2953 send_BEGIN(type, "major_faults", usec);
2954 for (w = root; w ; w = w->next) {
2955 if(unlikely(w->exposed))
2956 send_SET(w->name, (kernel_uint_t)(w->majflt * majflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cmajflt * cmajflt_fix_ratio)):0ULL));
2961 send_BEGIN(type, "lreads", usec);
2962 for (w = root; w ; w = w->next) {
2963 if(unlikely(w->exposed))
2964 send_SET(w->name, w->io_logical_bytes_read);
2968 send_BEGIN(type, "lwrites", usec);
2969 for (w = root; w ; w = w->next) {
2970 if(unlikely(w->exposed))
2971 send_SET(w->name, w->io_logical_bytes_written);
2976 send_BEGIN(type, "preads", usec);
2977 for (w = root; w ; w = w->next) {
2978 if(unlikely(w->exposed))
2979 send_SET(w->name, w->io_storage_bytes_read);
2983 send_BEGIN(type, "pwrites", usec);
2984 for (w = root; w ; w = w->next) {
2985 if(unlikely(w->exposed))
2986 send_SET(w->name, w->io_storage_bytes_written);
2990 if(enable_file_charts) {
2991 send_BEGIN(type, "files", usec);
2992 for (w = root; w; w = w->next) {
2993 if (unlikely(w->exposed))
2994 send_SET(w->name, w->openfiles);
2998 send_BEGIN(type, "sockets", usec);
2999 for (w = root; w; w = w->next) {
3000 if (unlikely(w->exposed))
3001 send_SET(w->name, w->opensockets);
3005 send_BEGIN(type, "pipes", usec);
3006 for (w = root; w; w = w->next) {
3007 if (unlikely(w->exposed))
3008 send_SET(w->name, w->openpipes);
3015 // ----------------------------------------------------------------------------
3016 // generate the charts
3018 static void send_charts_updates_to_netdata(struct target *root, const char *type, const char *title)
3021 int newly_added = 0;
3023 for(w = root ; w ; w = w->next) {
3024 if (w->target) continue;
3026 if (!w->exposed && w->processes) {
3029 if (debug || w->debug) fprintf(stderr, "apps.plugin: %s just added - regenerating charts.\n", w->name);
3033 // nothing more to show
3034 if(!newly_added && show_guest_time == show_guest_time_old) return;
3036 // we have something new to show
3037 // update the charts
3038 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);
3039 for (w = root; w ; w = w->next) {
3040 if(unlikely(w->exposed))
3041 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu %s\n", w->name, hz * RATES_DETAIL / 100, w->hidden ? "hidden" : "");
3044 fprintf(stdout, "CHART %s.mem '' '%s Real Memory (w/o shared)' 'MB' mem %s.mem stacked 20003 %d\n", type, title, type, update_every);
3045 for (w = root; w ; w = w->next) {
3046 if(unlikely(w->exposed))
3047 fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
3050 fprintf(stdout, "CHART %s.vmem '' '%s Virtual Memory Size' 'MB' mem %s.vmem stacked 20004 %d\n", type, title, type, update_every);
3051 for (w = root; w ; w = w->next) {
3052 if(unlikely(w->exposed))
3053 fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
3056 fprintf(stdout, "CHART %s.threads '' '%s Threads' 'threads' processes %s.threads stacked 20005 %d\n", type, title, type, update_every);
3057 for (w = root; w ; w = w->next) {
3058 if(unlikely(w->exposed))
3059 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3062 fprintf(stdout, "CHART %s.processes '' '%s Processes' 'processes' processes %s.processes stacked 20004 %d\n", type, title, type, update_every);
3063 for (w = root; w ; w = w->next) {
3064 if(unlikely(w->exposed))
3065 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3068 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);
3069 for (w = root; w ; w = w->next) {
3070 if(unlikely(w->exposed))
3071 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3074 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);
3075 for (w = root; w ; w = w->next) {
3076 if(unlikely(w->exposed))
3077 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3080 if(show_guest_time) {
3081 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);
3082 for (w = root; w; w = w->next) {
3083 if(unlikely(w->exposed))
3084 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3088 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);
3089 for (w = root; w ; w = w->next) {
3090 if(unlikely(w->exposed))
3091 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3094 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);
3095 for (w = root; w ; w = w->next) {
3096 if(unlikely(w->exposed))
3097 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3101 fprintf(stdout, "CHART %s.lreads '' '%s Disk Logical Reads' 'kilobytes/s' disk %s.lreads stacked 20042 %d\n", type, title, type, update_every);
3102 for (w = root; w ; w = w->next) {
3103 if(unlikely(w->exposed))
3104 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3107 fprintf(stdout, "CHART %s.lwrites '' '%s I/O Logical Writes' 'kilobytes/s' disk %s.lwrites stacked 20042 %d\n", type, title, type, update_every);
3108 for (w = root; w ; w = w->next) {
3109 if(unlikely(w->exposed))
3110 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3115 fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'blocks/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
3116 for (w = root; w ; w = w->next) {
3117 if(unlikely(w->exposed))
3118 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3121 fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'blocks/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
3122 for (w = root; w ; w = w->next) {
3123 if(unlikely(w->exposed))
3124 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3127 fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'kilobytes/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
3128 for (w = root; w ; w = w->next) {
3129 if(unlikely(w->exposed))
3130 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3133 fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'kilobytes/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
3134 for (w = root; w ; w = w->next) {
3135 if(unlikely(w->exposed))
3136 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3140 if(enable_file_charts) {
3141 fprintf(stdout, "CHART %s.files '' '%s Open Files' 'open files' disk %s.files stacked 20050 %d\n", type,
3142 title, type, update_every);
3143 for (w = root; w; w = w->next) {
3144 if (unlikely(w->exposed))
3145 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3148 fprintf(stdout, "CHART %s.sockets '' '%s Open Sockets' 'open sockets' net %s.sockets stacked 20051 %d\n",
3149 type, title, type, update_every);
3150 for (w = root; w; w = w->next) {
3151 if (unlikely(w->exposed))
3152 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3155 fprintf(stdout, "CHART %s.pipes '' '%s Pipes' 'open pipes' processes %s.pipes stacked 20053 %d\n", type,
3156 title, type, update_every);
3157 for (w = root; w; w = w->next) {
3158 if (unlikely(w->exposed))
3159 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3165 // ----------------------------------------------------------------------------
3166 // parse command line arguments
3168 int check_proc_1_io() {
3171 procfile *ff = procfile_open("/proc/1/io", NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
3172 if(!ff) goto cleanup;
3174 ff = procfile_readall(ff);
3175 if(!ff) goto cleanup;
3184 static void parse_args(int argc, char **argv)
3189 for(i = 1; i < argc; i++) {
3191 int n = (int)str2l(argv[i]);
3198 if(strcmp("version", argv[i]) == 0 || strcmp("-v", argv[i]) == 0) {
3199 printf("apps.plugin %s\n", VERSION);
3203 if(strcmp("test-permissions", argv[i]) == 0 || strcmp("-t", argv[i]) == 0) {
3204 if(!check_proc_1_io()) {
3205 perror("Tried to read /proc/1/io and it failed");
3212 if(strcmp("debug", argv[i]) == 0) {
3214 // debug_flags = 0xffffffff;
3218 if(strcmp("no-childs", argv[i]) == 0 || strcmp("without-childs", argv[i]) == 0) {
3219 include_exited_childs = 0;
3223 if(strcmp("with-childs", argv[i]) == 0) {
3224 include_exited_childs = 1;
3228 if(strcmp("with-guest", argv[i]) == 0) {
3229 enable_guest_charts = 1;
3233 if(strcmp("no-guest", argv[i]) == 0 || strcmp("without-guest", argv[i]) == 0) {
3234 enable_guest_charts = 0;
3238 if(strcmp("with-files", argv[i]) == 0) {
3239 enable_file_charts = 1;
3243 if(strcmp("no-files", argv[i]) == 0 || strcmp("without-files", argv[i]) == 0) {
3244 enable_file_charts = 0;
3248 if(strcmp("no-users", argv[i]) == 0 || strcmp("without-users", argv[i]) == 0) {
3249 enable_users_charts = 0;
3253 if(strcmp("no-groups", argv[i]) == 0 || strcmp("without-groups", argv[i]) == 0) {
3254 enable_groups_charts = 0;
3258 if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0) {
3261 " netdata apps.plugin %s\n"
3262 " Copyright (C) 2016-2017 Costa Tsaousis <costa@tsaousis.gr>\n"
3263 " Released under GNU General Public License v3 or later.\n"
3264 " All rights reserved.\n"
3266 " This program is a data collector plugin for netdata.\n"
3268 " Valid command line options:\n"
3270 " SECONDS set the data collection frequency\n"
3272 " debug enable debugging (lot of output)\n"
3275 " without-childs enable / disable aggregating exited\n"
3276 " children resources into parents\n"
3277 " (default is enabled)\n"
3280 " without-guest enable / disable reporting guest charts\n"
3281 " (default is disabled)\n"
3284 " without-files enable / disable reporting files, sockets, pipes\n"
3285 " (default is enabled)\n"
3287 " NAME read apps_NAME.conf instead of\n"
3288 " apps_groups.conf\n"
3289 " (default NAME=groups)\n"
3291 " version print program version and exit\n"
3303 error("Cannot understand option %s", argv[i]);
3307 if(freq > 0) update_every = freq;
3308 if(!name) name = "groups";
3310 if(read_apps_groups_conf(name)) {
3311 error("Cannot read process groups '%s/apps_%s.conf'. There are no internal defaults. Failing.", config_dir, name);
3316 static int am_i_running_as_root() {
3317 uid_t uid = getuid(), euid = geteuid();
3319 if(uid == 0 || euid == 0) {
3320 if(debug) info("I am running with escalated privileges, uid = %u, euid = %u.", uid, euid);
3324 if(debug) info("I am not running with escalated privileges, uid = %u, euid = %u.", uid, euid);
3328 #ifdef HAVE_CAPABILITY
3329 static int check_capabilities() {
3330 cap_t caps = cap_get_proc();
3332 error("Cannot get current capabilities.");
3336 info("Received my capabilities from the system.");
3340 cap_flag_value_t cfv = CAP_CLEAR;
3341 if(cap_get_flag(caps, CAP_DAC_READ_SEARCH, CAP_EFFECTIVE, &cfv) == -1) {
3342 error("Cannot find if CAP_DAC_READ_SEARCH is effective.");
3346 if(cfv != CAP_SET) {
3347 error("apps.plugin should run with CAP_DAC_READ_SEARCH.");
3351 info("apps.plugin runs with CAP_DAC_READ_SEARCH.");
3355 if(cap_get_flag(caps, CAP_SYS_PTRACE, CAP_EFFECTIVE, &cfv) == -1) {
3356 error("Cannot find if CAP_SYS_PTRACE is effective.");
3360 if(cfv != CAP_SET) {
3361 error("apps.plugin should run with CAP_SYS_PTRACE.");
3365 info("apps.plugin runs with CAP_SYS_PTRACE.");
3373 static int check_capabilities() {
3378 int main(int argc, char **argv) {
3379 // debug_flags = D_PROCFILE;
3381 // set the name for logging
3382 program_name = "apps.plugin";
3384 // disable syslog for apps.plugin
3385 error_log_syslog = 0;
3387 // set errors flood protection to 100 logs per hour
3388 error_log_errors_per_period = 100;
3389 error_log_throttle_period = 3600;
3391 netdata_configured_host_prefix = getenv("NETDATA_HOST_PREFIX");
3392 if(netdata_configured_host_prefix == NULL) {
3393 // info("NETDATA_HOST_PREFIX is not passed from netdata");
3394 netdata_configured_host_prefix = "";
3396 // else info("Found NETDATA_HOST_PREFIX='%s'", netdata_configured_host_prefix);
3398 config_dir = getenv("NETDATA_CONFIG_DIR");
3399 if(config_dir == NULL) {
3400 // info("NETDATA_CONFIG_DIR is not passed from netdata");
3401 config_dir = CONFIG_DIR;
3403 // else info("Found NETDATA_CONFIG_DIR='%s'", config_dir);
3405 #ifdef NETDATA_INTERNAL_CHECKS
3406 if(debug_flags != 0) {
3407 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
3408 if(setrlimit(RLIMIT_CORE, &rl) != 0)
3409 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
3410 #ifdef HAVE_SYS_PRCTL_H
3411 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
3414 #endif /* NETDATA_INTERNAL_CHECKS */
3416 procfile_adaptive_initial_allocation = 1;
3418 time_t started_t = now_monotonic_sec();
3420 get_system_pid_max();
3423 parse_args(argc, argv);
3425 if(!check_capabilities() && !am_i_running_as_root() && !check_proc_1_io()) {
3426 uid_t uid = getuid(), euid = geteuid();
3427 #ifdef HAVE_CAPABILITY
3428 error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
3429 "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
3430 "To enable capabilities run: sudo setcap cap_dac_read_search,cap_sys_ptrace+ep %s; "
3431 "To enable setuid to root run: sudo chown root %s; sudo chmod 4755 %s; "
3432 , uid, euid, argv[0], argv[0], argv[0]
3435 error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
3436 "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
3437 "Your system does not support capabilities. "
3438 "To enable setuid to root run: sudo chown root %s; sudo chmod 4755 %s; "
3439 , uid, euid, argv[0], argv[0]
3444 info("started on pid %d", getpid());
3446 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
3447 all_pids_sortlist = callocz(sizeof(pid_t), (size_t)pid_max);
3450 all_pids = callocz(sizeof(struct pid_stat *), (size_t) pid_max);
3452 usec_t step = update_every * USEC_PER_SEC;
3453 global_iterations_counter = 1;
3455 heartbeat_init(&hb);
3456 for(;1; global_iterations_counter++) {
3458 #ifdef NETDATA_PROFILING
3459 #warning "compiling for profiling"
3460 static int profiling_count=0;
3462 if(unlikely(profiling_count > 1000)) exit(0);
3464 heartbeat_next(&hb, step);
3467 if(!collect_data_for_all_processes()) {
3468 error("Cannot collect /proc data for running processes. Disabling apps.plugin...");
3469 printf("DISABLE\n");
3473 calculate_netdata_statistics();
3474 normalize_utilization(apps_groups_root_target);
3476 usec_t dt = send_resource_usage_to_netdata();
3478 // this is smart enough to show only newly added apps, when needed
3479 send_charts_updates_to_netdata(apps_groups_root_target, "apps", "Apps");
3481 if(likely(enable_users_charts))
3482 send_charts_updates_to_netdata(users_root_target, "users", "Users");
3484 if(likely(enable_groups_charts))
3485 send_charts_updates_to_netdata(groups_root_target, "groups", "User Groups");
3487 send_collected_data_to_netdata(apps_groups_root_target, "apps", dt);
3489 if(likely(enable_users_charts))
3490 send_collected_data_to_netdata(users_root_target, "users", dt);
3492 if(likely(enable_groups_charts))
3493 send_collected_data_to_netdata(groups_root_target, "groups", dt);
3497 show_guest_time_old = show_guest_time;
3500 fprintf(stderr, "apps.plugin: done Loop No %zu\n", global_iterations_counter);
3502 // restart check (14400 seconds)
3503 if(now_monotonic_sec() - started_t > 14400) exit(0);