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,
94 targets_assignment_counter = 0;
97 // ----------------------------------------------------------------------------
100 // With normalization we lower the collected metrics by a factor to make them
101 // match the total utilization of the system.
102 // The discrepancy exists because apps.plugin needs some time to collect all
103 // the metrics. This results in utilization that exceeds the total utilization
106 // With normalization we align the per-process utilization, to the total of
107 // the system. We first consume the exited children utilization and it the
108 // collected values is above the total, we proportionally scale each reported
111 // the total system time, as reported by /proc/stat
118 // the normalization ratios, as calculated by normalize_utilization()
119 double utime_fix_ratio = 1.0,
120 stime_fix_ratio = 1.0,
121 gtime_fix_ratio = 1.0,
122 minflt_fix_ratio = 1.0,
123 majflt_fix_ratio = 1.0,
124 cutime_fix_ratio = 1.0,
125 cstime_fix_ratio = 1.0,
126 cgtime_fix_ratio = 1.0,
127 cminflt_fix_ratio = 1.0,
128 cmajflt_fix_ratio = 1.0;
131 // ----------------------------------------------------------------------------
134 // target is the structure that processes are aggregated to be reported
137 // - Each entry in /etc/apps_groups.conf creates a target.
138 // - Each user and group used by a process in the system, creates a target.
141 char compare[MAX_COMPARE_NAME + 1];
142 uint32_t comparehash;
145 char id[MAX_NAME + 1];
148 char name[MAX_NAME + 1];
153 kernel_uint_t minflt;
154 kernel_uint_t cminflt;
155 kernel_uint_t majflt;
156 kernel_uint_t cmajflt;
160 kernel_uint_t cutime;
161 kernel_uint_t cstime;
162 kernel_uint_t cgtime;
163 kernel_uint_t num_threads;
164 // kernel_uint_t rss;
166 kernel_uint_t statm_size;
167 kernel_uint_t statm_resident;
168 kernel_uint_t statm_share;
169 // kernel_uint_t statm_text;
170 // kernel_uint_t statm_lib;
171 // kernel_uint_t statm_data;
172 // kernel_uint_t statm_dirty;
174 kernel_uint_t io_logical_bytes_read;
175 kernel_uint_t io_logical_bytes_written;
176 // kernel_uint_t io_read_calls;
177 // kernel_uint_t io_write_calls;
178 kernel_uint_t io_storage_bytes_read;
179 kernel_uint_t io_storage_bytes_written;
180 // kernel_uint_t io_cancelled_write_bytes;
185 kernel_uint_t openfiles;
186 kernel_uint_t openpipes;
187 kernel_uint_t opensockets;
188 kernel_uint_t openinotifies;
189 kernel_uint_t openeventfds;
190 kernel_uint_t opentimerfds;
191 kernel_uint_t opensignalfds;
192 kernel_uint_t openeventpolls;
193 kernel_uint_t openother;
195 unsigned int processes; // how many processes have been merged to this
196 int exposed; // if set, we have sent this to netdata
197 int hidden; // if set, we set the hidden flag on the dimension
200 int starts_with; // if set, the compare string matches only the
201 // beginning of the command
203 struct target *target; // the one that will be reported to netdata
208 *apps_groups_default_target = NULL, // the default target
209 *apps_groups_root_target = NULL, // apps_groups.conf defined
210 *users_root_target = NULL, // users
211 *groups_root_target = NULL; // user groups
214 apps_groups_targets_count = 0; // # of apps_groups.conf targets
217 // ----------------------------------------------------------------------------
220 // structure to store data for each process running
221 // see: man proc for the description of the fields
225 char comm[MAX_COMPARE_NAME + 1];
226 char cmdline[MAX_CMDLINE + 1];
238 // these are raw values collected
239 kernel_uint_t minflt_raw;
240 kernel_uint_t cminflt_raw;
241 kernel_uint_t majflt_raw;
242 kernel_uint_t cmajflt_raw;
243 kernel_uint_t utime_raw;
244 kernel_uint_t stime_raw;
245 kernel_uint_t gtime_raw; // guest_time
246 kernel_uint_t cutime_raw;
247 kernel_uint_t cstime_raw;
248 kernel_uint_t cgtime_raw; // cguest_time
251 kernel_uint_t minflt;
252 kernel_uint_t cminflt;
253 kernel_uint_t majflt;
254 kernel_uint_t cmajflt;
258 kernel_uint_t cutime;
259 kernel_uint_t cstime;
260 kernel_uint_t cgtime;
265 // int64_t itrealvalue;
266 // kernel_uint_t starttime;
267 // kernel_uint_t vsize;
268 // kernel_uint_t rss;
269 // kernel_uint_t rsslim;
270 // kernel_uint_t starcode;
271 // kernel_uint_t endcode;
272 // kernel_uint_t startstack;
273 // kernel_uint_t kstkesp;
274 // kernel_uint_t kstkeip;
277 // uint64_t sigignore;
278 // uint64_t sigcatch;
282 // int32_t exit_signal;
283 // int32_t processor;
284 // uint32_t rt_priority;
286 // kernel_uint_t delayacct_blkio_ticks;
291 kernel_uint_t statm_size;
292 kernel_uint_t statm_resident;
293 kernel_uint_t statm_share;
294 // kernel_uint_t statm_text;
295 // kernel_uint_t statm_lib;
296 // kernel_uint_t statm_data;
297 // kernel_uint_t statm_dirty;
299 kernel_uint_t io_logical_bytes_read_raw;
300 kernel_uint_t io_logical_bytes_written_raw;
301 // kernel_uint_t io_read_calls_raw;
302 // kernel_uint_t io_write_calls_raw;
303 kernel_uint_t io_storage_bytes_read_raw;
304 kernel_uint_t io_storage_bytes_written_raw;
305 // kernel_uint_t io_cancelled_write_bytes_raw;
307 kernel_uint_t io_logical_bytes_read;
308 kernel_uint_t io_logical_bytes_written;
309 // kernel_uint_t io_read_calls;
310 // kernel_uint_t io_write_calls;
311 kernel_uint_t io_storage_bytes_read;
312 kernel_uint_t io_storage_bytes_written;
313 // kernel_uint_t io_cancelled_write_bytes;
315 int *fds; // array of fds it uses
316 int fds_size; // the size of the fds array
318 int children_count; // number of processes directly referencing this
319 char keep:1; // 1 when we need to keep this process in memory even after it exited
320 int keeploops; // increases by 1 every time keep is 1 and updated 0
321 char updated:1; // 1 when the process is currently running
322 char merged:1; // 1 when it has been merged to its parent
323 char read:1; // 1 when we have already read this process for this iteration
325 int sortlist; // higher numbers = top on the process tree
326 // each process gets a unique number
328 struct target *target; // app_groups.conf targets
329 struct target *user_target; // uid based targets
330 struct target *group_target; // gid based targets
332 usec_t stat_collected_usec;
333 usec_t last_stat_collected_usec;
335 usec_t io_collected_usec;
336 usec_t last_io_collected_usec;
338 char *fds_dirname; // the full directory name in /proc/PID/fd
341 char *statm_filename;
343 char *cmdline_filename;
345 struct pid_stat *parent;
346 struct pid_stat *prev;
347 struct pid_stat *next;
350 // log each problem once per process
351 // log flood protection flags (log_thrown)
352 #define PID_LOG_IO 0x00000001
353 #define PID_LOG_STATM 0x00000002
354 #define PID_LOG_CMDLINE 0x00000004
355 #define PID_LOG_FDS 0x00000008
356 #define PID_LOG_STAT 0x00000010
358 static struct pid_stat
359 *root_of_pids = NULL, // global list of all processes running
360 **all_pids = NULL; // to avoid allocations, we pre-allocate the
361 // the entire pid space.
364 all_pids_count = 0; // the number of processes running
366 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
367 // Another pre-allocated list of all possible pids.
368 // We need it to pids and assign them a unique sortlist id, so that we
369 // read parents before children. This is needed to prevent a situation where
370 // a child is found running, but until we read its parent, it has exited and
371 // its parent has accumulated its resources.
373 *all_pids_sortlist = NULL;
376 // ----------------------------------------------------------------------------
379 // this is used to keep a global list of all open files of the system.
380 // it is needed in order to calculate the unique files processes have open.
382 #define FILE_DESCRIPTORS_INCREASE_STEP 100
384 // types for struct file_descriptor->type
385 typedef enum fd_filetype {
397 struct file_descriptor {
400 #ifdef NETDATA_INTERNAL_CHECKS
402 #endif /* NETDATA_INTERNAL_CHECKS */
416 // ----------------------------------------------------------------------------
417 // callback required by fatal()
419 void netdata_cleanup_and_exit(int ret) {
423 // ----------------------------------------------------------------------------
425 // aggregate all processes in groups, to have a limited number of dimensions
427 static struct target *get_users_target(uid_t uid) {
429 for(w = users_root_target ; w ; w = w->next)
430 if(w->uid == uid) return w;
432 w = callocz(sizeof(struct target), 1);
433 snprintfz(w->compare, MAX_COMPARE_NAME, "%u", uid);
434 w->comparehash = simple_hash(w->compare);
435 w->comparelen = strlen(w->compare);
437 snprintfz(w->id, MAX_NAME, "%u", uid);
438 w->idhash = simple_hash(w->id);
440 struct passwd *pw = getpwuid(uid);
442 snprintfz(w->name, MAX_NAME, "%u", uid);
444 snprintfz(w->name, MAX_NAME, "%s", pw->pw_name);
446 netdata_fix_chart_name(w->name);
450 w->next = users_root_target;
451 users_root_target = w;
454 fprintf(stderr, "apps.plugin: added uid %u ('%s') target\n", w->uid, w->name);
459 struct target *get_groups_target(gid_t gid)
462 for(w = groups_root_target ; w ; w = w->next)
463 if(w->gid == gid) return w;
465 w = callocz(sizeof(struct target), 1);
466 snprintfz(w->compare, MAX_COMPARE_NAME, "%u", gid);
467 w->comparehash = simple_hash(w->compare);
468 w->comparelen = strlen(w->compare);
470 snprintfz(w->id, MAX_NAME, "%u", gid);
471 w->idhash = simple_hash(w->id);
473 struct group *gr = getgrgid(gid);
475 snprintfz(w->name, MAX_NAME, "%u", gid);
477 snprintfz(w->name, MAX_NAME, "%s", gr->gr_name);
479 netdata_fix_chart_name(w->name);
483 w->next = groups_root_target;
484 groups_root_target = w;
487 fprintf(stderr, "apps.plugin: added gid %u ('%s') target\n", w->gid, w->name);
492 // find or create a new target
493 // there are targets that are just aggregated to other target (the second argument)
494 static struct target *get_apps_groups_target(const char *id, struct target *target, const char *name) {
495 int tdebug = 0, thidden = target?target->hidden:0, ends_with = 0;
496 const char *nid = id;
498 // extract the options
499 while(nid[0] == '-' || nid[0] == '+' || nid[0] == '*') {
500 if(nid[0] == '-') thidden = 1;
501 if(nid[0] == '+') tdebug = 1;
502 if(nid[0] == '*') ends_with = 1;
505 uint32_t hash = simple_hash(id);
507 // find if it already exists
508 struct target *w, *last = apps_groups_root_target;
509 for(w = apps_groups_root_target ; w ; w = w->next) {
510 if(w->idhash == hash && strncmp(nid, w->id, MAX_NAME) == 0)
516 // find an existing target
517 if(unlikely(!target)) {
518 while(*name == '-') {
519 if(*name == '-') thidden = 1;
523 for(target = apps_groups_root_target ; target != NULL ; target = target->next) {
524 if(!target->target && strcmp(name, target->name) == 0)
528 if(unlikely(debug)) {
530 fprintf(stderr, "apps.plugin: REUSING TARGET NAME '%s' on ID '%s'\n", target->name, target->id);
532 fprintf(stderr, "apps.plugin: NEW TARGET NAME '%s' on ID '%s'\n", name, id);
536 if(target && target->target)
537 fatal("Internal Error: request to link process '%s' to target '%s' which is linked to target '%s'", id, target->id, target->target->id);
539 w = callocz(sizeof(struct target), 1);
540 strncpyz(w->id, nid, MAX_NAME);
541 w->idhash = simple_hash(w->id);
543 if(unlikely(!target))
545 strncpyz(w->name, name, MAX_NAME);
548 strncpyz(w->name, nid, MAX_NAME);
550 strncpyz(w->compare, nid, MAX_COMPARE_NAME);
551 size_t len = strlen(w->compare);
552 if(w->compare[len - 1] == '*') {
553 w->compare[len - 1] = '\0';
556 w->ends_with = ends_with;
558 if(w->starts_with && w->ends_with)
559 proc_pid_cmdline_is_needed = 1;
561 w->comparehash = simple_hash(w->compare);
562 w->comparelen = strlen(w->compare);
568 // append it, to maintain the order in apps_groups.conf
569 if(last) last->next = w;
570 else apps_groups_root_target = w;
573 fprintf(stderr, "apps.plugin: ADDING TARGET ID '%s', process name '%s' (%s), aggregated on target '%s', options: %s %s\n"
575 , w->compare, (w->starts_with && w->ends_with)?"substring":((w->starts_with)?"prefix":((w->ends_with)?"suffix":"exact"))
576 , w->target?w->target->name:w->name
577 , (w->hidden)?"hidden":"-"
578 , (w->debug)?"debug":"-"
584 // read the apps_groups.conf file
585 static int read_apps_groups_conf(const char *file)
587 char filename[FILENAME_MAX + 1];
589 snprintfz(filename, FILENAME_MAX, "%s/apps_%s.conf", config_dir, file);
592 fprintf(stderr, "apps.plugin: process groups file: '%s'\n", filename);
594 // ----------------------------------------
596 procfile *ff = procfile_open(filename, " :\t", PROCFILE_FLAG_DEFAULT);
599 procfile_set_quotes(ff, "'\"");
601 ff = procfile_readall(ff);
605 size_t line, lines = procfile_lines(ff);
607 for(line = 0; line < lines ;line++) {
608 size_t word, words = procfile_linewords(ff, line);
611 char *name = procfile_lineword(ff, line, 0);
612 if(!name || !*name) continue;
614 // find a possibly existing target
615 struct target *w = NULL;
617 // loop through all words, skipping the first one (the name)
618 for(word = 0; word < words ;word++) {
619 char *s = procfile_lineword(ff, line, word);
620 if(!s || !*s) continue;
623 // is this the first word? skip it
624 if(s == name) continue;
627 struct target *n = get_apps_groups_target(s, w, name);
629 error("Cannot create target '%s' (line %zu, word %zu)", s, line, word);
633 // just some optimization
634 // to avoid searching for a target for each process
635 if(!w) w = n->target?n->target:n;
641 apps_groups_default_target = get_apps_groups_target("p+!o@w#e$i^r&7*5(-i)l-o_", NULL, "other"); // match nothing
642 if(!apps_groups_default_target)
643 fatal("Cannot create default target");
645 // allow the user to override group 'other'
646 if(apps_groups_default_target->target)
647 apps_groups_default_target = apps_groups_default_target->target;
653 // ----------------------------------------------------------------------------
654 // struct pid_stat management
656 static inline struct pid_stat *get_pid_entry(pid_t pid) {
657 if(unlikely(all_pids[pid]))
658 return all_pids[pid];
660 struct pid_stat *p = callocz(sizeof(struct pid_stat), 1);
661 p->fds = callocz(sizeof(int), MAX_SPARE_FDS);
662 p->fds_size = MAX_SPARE_FDS;
664 if(likely(root_of_pids))
665 root_of_pids->prev = p;
667 p->next = root_of_pids;
678 static inline void del_pid_entry(pid_t pid) {
679 struct pid_stat *p = all_pids[pid];
682 error("attempted to free pid %d that is not allocated.", pid);
687 fprintf(stderr, "apps.plugin: process %d %s exited, deleting it.\n", pid, p->comm);
689 if(root_of_pids == p)
690 root_of_pids = p->next;
692 if(p->next) p->next->prev = p->prev;
693 if(p->prev) p->prev->next = p->next;
696 freez(p->fds_dirname);
697 freez(p->stat_filename);
698 freez(p->statm_filename);
699 freez(p->io_filename);
700 freez(p->cmdline_filename);
703 all_pids[pid] = NULL;
707 // ----------------------------------------------------------------------------
709 static inline int managed_log(struct pid_stat *p, uint32_t log, int status) {
710 if(unlikely(!status)) {
711 // error("command failed log %u, errno %d", log, errno);
713 if(unlikely(debug || errno != ENOENT)) {
714 if(unlikely(debug || !(p->log_thrown & log))) {
715 p->log_thrown |= log;
718 error("Cannot process %s/proc/%d/io (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
722 error("Cannot process %s/proc/%d/statm (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
725 case PID_LOG_CMDLINE:
726 error("Cannot process %s/proc/%d/cmdline (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
730 error("Cannot process entries in %s/proc/%d/fd (command '%s')", netdata_configured_host_prefix, p->pid, p->comm);
737 error("unhandled error for pid %d, command '%s'", p->pid, p->comm);
744 else if(unlikely(p->log_thrown & log)) {
745 // error("unsetting log %u on pid %d", log, p->pid);
746 p->log_thrown &= ~log;
752 static inline void assign_target_to_pid(struct pid_stat *p) {
753 targets_assignment_counter++;
755 uint32_t hash = simple_hash(p->comm);
756 size_t pclen = strlen(p->comm);
759 for(w = apps_groups_root_target; w ; w = w->next) {
760 // if(debug || (p->target && p->target->debug)) fprintf(stderr, "apps.plugin: \t\tcomparing '%s' with '%s'\n", w->compare, p->comm);
762 // find it - 4 cases:
763 // 1. the target is not a pattern
764 // 2. the target has the prefix
765 // 3. the target has the suffix
766 // 4. the target is something inside cmdline
768 if(unlikely(( (!w->starts_with && !w->ends_with && w->comparehash == hash && !strcmp(w->compare, p->comm))
769 || (w->starts_with && !w->ends_with && !strncmp(w->compare, p->comm, w->comparelen))
770 || (!w->starts_with && w->ends_with && pclen >= w->comparelen && !strcmp(w->compare, &p->comm[pclen - w->comparelen]))
771 || (proc_pid_cmdline_is_needed && w->starts_with && w->ends_with && strstr(p->cmdline, w->compare))
774 if(w->target) p->target = w->target;
777 if(debug || (p->target && p->target->debug))
778 fprintf(stderr, "apps.plugin: \t\t%s linked to target %s\n", p->comm, p->target->name);
786 // ----------------------------------------------------------------------------
787 // update pids from proc
789 static inline int read_proc_pid_cmdline(struct pid_stat *p) {
792 size_t i, bytes = MAX_CMDLINE;
797 mib[2] = KERN_PROC_ARGS;
799 if (unlikely(sysctl(mib, 4, p->cmdline, &bytes, NULL, 0)))
802 if(unlikely(!p->cmdline_filename)) {
803 char filename[FILENAME_MAX + 1];
804 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/cmdline", netdata_configured_host_prefix, p->pid);
805 p->cmdline_filename = strdupz(filename);
808 int fd = open(p->cmdline_filename, O_RDONLY, 0666);
809 if(unlikely(fd == -1)) goto cleanup;
811 ssize_t i, bytes = read(fd, p->cmdline, MAX_CMDLINE);
814 if(unlikely(bytes < 0)) goto cleanup;
817 p->cmdline[bytes] = '\0';
818 for(i = 0; i < bytes ; i++)
819 if(unlikely(!p->cmdline[i])) p->cmdline[i] = ' ';
822 fprintf(stderr, "Read file '%s' contents: %s\n", p->cmdline_filename, p->cmdline);
827 // copy the command to the command line
828 strncpyz(p->cmdline, p->comm, MAX_CMDLINE);
832 static inline int read_proc_pid_ownership(struct pid_stat *p, void *ptr) {
835 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
837 p->uid = proc_info->ki_uid;
838 p->gid = proc_info->ki_groups[0];
842 if(unlikely(!p->stat_filename)) {
843 error("pid %d does not have a stat_filename", p->pid);
847 // ----------------------------------------
851 if(stat(p->stat_filename, &st) != 0) {
852 error("Cannot stat file '%s'", p->stat_filename);
863 // ----------------------------------------------------------------------------
864 // macro to calculate the incremental rate of a value
865 // each parameter is accessed only ONCE - so it is safe to pass function calls
866 // or other macros as parameters
868 #define incremental_rate(rate_variable, last_kernel_variable, new_kernel_value, collected_usec, last_collected_usec) { \
869 kernel_uint_t _new_tmp = new_kernel_value; \
870 rate_variable = (_new_tmp - last_kernel_variable) * (USEC_PER_SEC * RATES_DETAIL) / (collected_usec - last_collected_usec); \
871 last_kernel_variable = _new_tmp; \
874 // the same macro for struct pid members
875 #define pid_incremental_rate(type, var, value) \
876 incremental_rate(var, var##_raw, value, p->type##_collected_usec, p->last_##type##_collected_usec)
879 // ----------------------------------------------------------------------------
881 static inline int read_proc_pid_stat(struct pid_stat *p, void *ptr) {
885 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
887 if (unlikely(proc_info->ki_tdflags & TDF_IDLETD))
890 static procfile *ff = NULL;
892 if(unlikely(!p->stat_filename)) {
893 char filename[FILENAME_MAX + 1];
894 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/stat", netdata_configured_host_prefix, p->pid);
895 p->stat_filename = strdupz(filename);
898 int set_quotes = (!ff)?1:0;
900 ff = procfile_reopen(ff, p->stat_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
901 if(unlikely(!ff)) goto cleanup;
903 // if(set_quotes) procfile_set_quotes(ff, "()");
904 if(unlikely(set_quotes))
905 procfile_set_open_close(ff, "(", ")");
907 ff = procfile_readall(ff);
908 if(unlikely(!ff)) goto cleanup;
911 p->last_stat_collected_usec = p->stat_collected_usec;
912 p->stat_collected_usec = now_monotonic_usec();
916 char *comm = proc_info->ki_comm;
917 p->ppid = proc_info->ki_ppid;
919 // p->pid = str2pid_t(procfile_lineword(ff, 0, 0));
920 char *comm = procfile_lineword(ff, 0, 1);
921 // p->state = *(procfile_lineword(ff, 0, 2));
922 p->ppid = (int32_t)str2pid_t(procfile_lineword(ff, 0, 3));
923 // p->pgrp = (int32_t)str2pid_t(procfile_lineword(ff, 0, 4));
924 // p->session = (int32_t)str2pid_t(procfile_lineword(ff, 0, 5));
925 // p->tty_nr = (int32_t)str2pid_t(procfile_lineword(ff, 0, 6));
926 // p->tpgid = (int32_t)str2pid_t(procfile_lineword(ff, 0, 7));
927 // p->flags = str2uint64_t(procfile_lineword(ff, 0, 8));
930 if(strcmp(p->comm, comm)) {
931 if(unlikely(debug)) {
933 fprintf(stderr, "apps.plugin: \tpid %d (%s) changed name to '%s'\n", p->pid, p->comm, comm);
935 fprintf(stderr, "apps.plugin: \tJust added %d (%s)\n", p->pid, comm);
938 strncpyz(p->comm, comm, MAX_COMPARE_NAME);
940 // /proc/<pid>/cmdline
941 if(likely(proc_pid_cmdline_is_needed))
942 managed_log(p, PID_LOG_CMDLINE, read_proc_pid_cmdline(p));
944 assign_target_to_pid(p);
948 pid_incremental_rate(stat, p->minflt, (kernel_uint_t)proc_info->ki_rusage.ru_minflt);
949 pid_incremental_rate(stat, p->cminflt, (kernel_uint_t)proc_info->ki_rusage_ch.ru_minflt);
950 pid_incremental_rate(stat, p->majflt, (kernel_uint_t)proc_info->ki_rusage.ru_majflt);
951 pid_incremental_rate(stat, p->cmajflt, (kernel_uint_t)proc_info->ki_rusage_ch.ru_majflt);
952 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);
953 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);
954 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);
955 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);
957 p->num_threads = proc_info->ki_numthreads;
959 if(enable_guest_charts) {
960 enable_guest_charts = 0;
961 info("Guest charts aren't supported by FreeBSD");
964 pid_incremental_rate(stat, p->minflt, str2kernel_uint_t(procfile_lineword(ff, 0, 9)));
965 pid_incremental_rate(stat, p->cminflt, str2kernel_uint_t(procfile_lineword(ff, 0, 10)));
966 pid_incremental_rate(stat, p->majflt, str2kernel_uint_t(procfile_lineword(ff, 0, 11)));
967 pid_incremental_rate(stat, p->cmajflt, str2kernel_uint_t(procfile_lineword(ff, 0, 12)));
968 pid_incremental_rate(stat, p->utime, str2kernel_uint_t(procfile_lineword(ff, 0, 13)));
969 pid_incremental_rate(stat, p->stime, str2kernel_uint_t(procfile_lineword(ff, 0, 14)));
970 pid_incremental_rate(stat, p->cutime, str2kernel_uint_t(procfile_lineword(ff, 0, 15)));
971 pid_incremental_rate(stat, p->cstime, str2kernel_uint_t(procfile_lineword(ff, 0, 16)));
972 // p->priority = str2kernel_uint_t(procfile_lineword(ff, 0, 17));
973 // p->nice = str2kernel_uint_t(procfile_lineword(ff, 0, 18));
974 p->num_threads = (int32_t)str2uint32_t(procfile_lineword(ff, 0, 19));
975 // p->itrealvalue = str2kernel_uint_t(procfile_lineword(ff, 0, 20));
976 // p->starttime = str2kernel_uint_t(procfile_lineword(ff, 0, 21));
977 // p->vsize = str2kernel_uint_t(procfile_lineword(ff, 0, 22));
978 // p->rss = str2kernel_uint_t(procfile_lineword(ff, 0, 23));
979 // p->rsslim = str2kernel_uint_t(procfile_lineword(ff, 0, 24));
980 // p->starcode = str2kernel_uint_t(procfile_lineword(ff, 0, 25));
981 // p->endcode = str2kernel_uint_t(procfile_lineword(ff, 0, 26));
982 // p->startstack = str2kernel_uint_t(procfile_lineword(ff, 0, 27));
983 // p->kstkesp = str2kernel_uint_t(procfile_lineword(ff, 0, 28));
984 // p->kstkeip = str2kernel_uint_t(procfile_lineword(ff, 0, 29));
985 // p->signal = str2kernel_uint_t(procfile_lineword(ff, 0, 30));
986 // p->blocked = str2kernel_uint_t(procfile_lineword(ff, 0, 31));
987 // p->sigignore = str2kernel_uint_t(procfile_lineword(ff, 0, 32));
988 // p->sigcatch = str2kernel_uint_t(procfile_lineword(ff, 0, 33));
989 // p->wchan = str2kernel_uint_t(procfile_lineword(ff, 0, 34));
990 // p->nswap = str2kernel_uint_t(procfile_lineword(ff, 0, 35));
991 // p->cnswap = str2kernel_uint_t(procfile_lineword(ff, 0, 36));
992 // p->exit_signal = str2kernel_uint_t(procfile_lineword(ff, 0, 37));
993 // p->processor = str2kernel_uint_t(procfile_lineword(ff, 0, 38));
994 // p->rt_priority = str2kernel_uint_t(procfile_lineword(ff, 0, 39));
995 // p->policy = str2kernel_uint_t(procfile_lineword(ff, 0, 40));
996 // p->delayacct_blkio_ticks = str2kernel_uint_t(procfile_lineword(ff, 0, 41));
998 if(enable_guest_charts) {
1000 pid_incremental_rate(stat, p->gtime, str2kernel_uint_t(procfile_lineword(ff, 0, 42)));
1001 pid_incremental_rate(stat, p->cgtime, str2kernel_uint_t(procfile_lineword(ff, 0, 43)));
1003 if (show_guest_time || p->gtime || p->cgtime) {
1004 p->utime -= (p->utime >= p->gtime) ? p->gtime : p->utime;
1005 p->cutime -= (p->cutime >= p->cgtime) ? p->cgtime : p->cutime;
1006 show_guest_time = 1;
1011 if(unlikely(debug || (p->target && p->target->debug)))
1012 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);
1014 if(unlikely(global_iterations_counter == 1)) {
1045 static inline int read_proc_pid_statm(struct pid_stat *p, void *ptr) {
1048 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
1050 static procfile *ff = NULL;
1052 if(unlikely(!p->statm_filename)) {
1053 char filename[FILENAME_MAX + 1];
1054 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/statm", netdata_configured_host_prefix, p->pid);
1055 p->statm_filename = strdupz(filename);
1058 ff = procfile_reopen(ff, p->statm_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
1059 if(unlikely(!ff)) goto cleanup;
1061 ff = procfile_readall(ff);
1062 if(unlikely(!ff)) goto cleanup;
1068 p->statm_size = proc_info->ki_size / sysconf(_SC_PAGESIZE);
1069 p->statm_resident = proc_info->ki_rssize;
1070 p->statm_share = 0; // do we have to use ru_ixrss here?
1072 p->statm_size = str2kernel_uint_t(procfile_lineword(ff, 0, 0));
1073 p->statm_resident = str2kernel_uint_t(procfile_lineword(ff, 0, 1));
1074 p->statm_share = str2kernel_uint_t(procfile_lineword(ff, 0, 2));
1075 // p->statm_text = str2kernel_uint_t(procfile_lineword(ff, 0, 3));
1076 // p->statm_lib = str2kernel_uint_t(procfile_lineword(ff, 0, 4));
1077 // p->statm_data = str2kernel_uint_t(procfile_lineword(ff, 0, 5));
1078 // p->statm_dirty = str2kernel_uint_t(procfile_lineword(ff, 0, 6));
1085 p->statm_resident = 0;
1087 // p->statm_text = 0;
1088 // p->statm_lib = 0;
1089 // p->statm_data = 0;
1090 // p->statm_dirty = 0;
1094 static inline int read_proc_pid_io(struct pid_stat *p, void *ptr) {
1097 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
1099 static procfile *ff = NULL;
1101 if(unlikely(!p->io_filename)) {
1102 char filename[FILENAME_MAX + 1];
1103 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/io", netdata_configured_host_prefix, p->pid);
1104 p->io_filename = strdupz(filename);
1108 ff = procfile_reopen(ff, p->io_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
1109 if(unlikely(!ff)) goto cleanup;
1111 ff = procfile_readall(ff);
1112 if(unlikely(!ff)) goto cleanup;
1117 p->last_io_collected_usec = p->io_collected_usec;
1118 p->io_collected_usec = now_monotonic_usec();
1121 pid_incremental_rate(io, p->io_storage_bytes_read, proc_info->ki_rusage.ru_inblock);
1122 pid_incremental_rate(io, p->io_storage_bytes_written, proc_info->ki_rusage.ru_oublock);
1124 pid_incremental_rate(io, p->io_logical_bytes_read, str2kernel_uint_t(procfile_lineword(ff, 0, 1)));
1125 pid_incremental_rate(io, p->io_logical_bytes_written, str2kernel_uint_t(procfile_lineword(ff, 1, 1)));
1126 // pid_incremental_rate(io, p->io_read_calls, str2kernel_uint_t(procfile_lineword(ff, 2, 1)));
1127 // pid_incremental_rate(io, p->io_write_calls, str2kernel_uint_t(procfile_lineword(ff, 3, 1)));
1128 pid_incremental_rate(io, p->io_storage_bytes_read, str2kernel_uint_t(procfile_lineword(ff, 4, 1)));
1129 pid_incremental_rate(io, p->io_storage_bytes_written, str2kernel_uint_t(procfile_lineword(ff, 5, 1)));
1130 // pid_incremental_rate(io, p->io_cancelled_write_bytes, str2kernel_uint_t(procfile_lineword(ff, 6, 1)));
1133 if(unlikely(global_iterations_counter == 1)) {
1134 p->io_logical_bytes_read = 0;
1135 p->io_logical_bytes_written = 0;
1136 // p->io_read_calls = 0;
1137 // p->io_write_calls = 0;
1138 p->io_storage_bytes_read = 0;
1139 p->io_storage_bytes_written = 0;
1140 // p->io_cancelled_write_bytes = 0;
1146 p->io_logical_bytes_read = 0;
1147 p->io_logical_bytes_written = 0;
1148 // p->io_read_calls = 0;
1149 // p->io_write_calls = 0;
1150 p->io_storage_bytes_read = 0;
1151 p->io_storage_bytes_written = 0;
1152 // p->io_cancelled_write_bytes = 0;
1156 static inline int read_proc_stat() {
1158 long cp_time[CPUSTATES];
1161 if (unlikely(CPUSTATES != 5)) {
1162 error("FREEBSD: There are %d CPU states (5 was expected)", CPUSTATES);
1165 if (unlikely(GETSYSCTL("kern.cp_time", cp_time))) goto cleanup;
1167 static char filename[FILENAME_MAX + 1] = "";
1168 static procfile *ff = NULL;
1170 static kernel_uint_t utime_raw = 0, stime_raw = 0, gtime_raw = 0, gntime_raw = 0, ntime_raw = 0;
1171 static usec_t collected_usec = 0, last_collected_usec = 0;
1175 snprintfz(filename, FILENAME_MAX, "%s/proc/stat", netdata_configured_host_prefix);
1176 ff = procfile_open(filename, " \t:", PROCFILE_FLAG_DEFAULT);
1177 if(unlikely(!ff)) goto cleanup;
1180 ff = procfile_readall(ff);
1181 if(unlikely(!ff)) goto cleanup;
1184 last_collected_usec = collected_usec;
1185 collected_usec = now_monotonic_usec();
1189 // temporary - it is added global_ntime;
1190 kernel_uint_t global_ntime = 0;
1193 incremental_rate(global_utime, utime_raw, cp_time[0], collected_usec, last_collected_usec);
1194 incremental_rate(global_ntime, ntime_raw, cp_time[1], collected_usec, last_collected_usec);
1195 incremental_rate(global_stime, stime_raw, cp_time[2], collected_usec, last_collected_usec);
1197 incremental_rate(global_utime, utime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 1)), collected_usec, last_collected_usec);
1198 incremental_rate(global_ntime, ntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 2)), collected_usec, last_collected_usec);
1199 incremental_rate(global_stime, stime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 3)), collected_usec, last_collected_usec);
1200 incremental_rate(global_gtime, gtime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 10)), collected_usec, last_collected_usec);
1203 global_utime += global_ntime;
1206 if(enable_guest_charts) {
1207 enable_guest_charts = 0;
1208 info("Guest charts aren't supported by FreeBSD");
1211 if(enable_guest_charts) {
1212 // temporary - it is added global_ntime;
1213 kernel_uint_t global_gntime = 0;
1215 // guest nice time, on guest time
1216 incremental_rate(global_gntime, gntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 11)), collected_usec, last_collected_usec);
1218 global_gtime += global_gntime;
1220 // remove guest time from user time
1221 global_utime -= (global_utime > global_gtime) ? global_gtime : global_utime;
1225 if(unlikely(global_iterations_counter == 1)) {
1241 // ----------------------------------------------------------------------------
1243 int file_descriptor_compare(void* a, void* b) {
1244 #ifdef NETDATA_INTERNAL_CHECKS
1245 if(((struct file_descriptor *)a)->magic != 0x0BADCAFE || ((struct file_descriptor *)b)->magic != 0x0BADCAFE)
1246 error("Corrupted index data detected. Please report this.");
1247 #endif /* NETDATA_INTERNAL_CHECKS */
1249 if(((struct file_descriptor *)a)->hash < ((struct file_descriptor *)b)->hash)
1252 else if(((struct file_descriptor *)a)->hash > ((struct file_descriptor *)b)->hash)
1256 return strcmp(((struct file_descriptor *)a)->name, ((struct file_descriptor *)b)->name);
1259 int file_descriptor_iterator(avl *a) { if(a) {}; return 0; }
1261 avl_tree all_files_index = {
1263 file_descriptor_compare
1266 static struct file_descriptor *file_descriptor_find(const char *name, uint32_t hash) {
1267 struct file_descriptor tmp;
1268 tmp.hash = (hash)?hash:simple_hash(name);
1272 #ifdef NETDATA_INTERNAL_CHECKS
1273 tmp.magic = 0x0BADCAFE;
1274 #endif /* NETDATA_INTERNAL_CHECKS */
1276 return (struct file_descriptor *)avl_search(&all_files_index, (avl *) &tmp);
1279 #define file_descriptor_add(fd) avl_insert(&all_files_index, (avl *)(fd))
1280 #define file_descriptor_remove(fd) avl_remove(&all_files_index, (avl *)(fd))
1282 // ----------------------------------------------------------------------------
1284 static inline void file_descriptor_not_used(int id)
1286 if(id > 0 && id < all_files_size) {
1288 #ifdef NETDATA_INTERNAL_CHECKS
1289 if(all_files[id].magic != 0x0BADCAFE) {
1290 error("Ignoring request to remove empty file id %d.", id);
1293 #endif /* NETDATA_INTERNAL_CHECKS */
1296 fprintf(stderr, "apps.plugin: decreasing slot %d (count = %d).\n", id, all_files[id].count);
1298 if(all_files[id].count > 0) {
1299 all_files[id].count--;
1301 if(!all_files[id].count) {
1303 fprintf(stderr, "apps.plugin: >> slot %d is empty.\n", id);
1305 if(unlikely(file_descriptor_remove(&all_files[id]) != (void *)&all_files[id]))
1306 error("INTERNAL ERROR: removal of unused fd from index, removed a different fd");
1308 #ifdef NETDATA_INTERNAL_CHECKS
1309 all_files[id].magic = 0x00000000;
1310 #endif /* NETDATA_INTERNAL_CHECKS */
1315 error("Request to decrease counter of fd %d (%s), while the use counter is 0", id, all_files[id].name);
1317 else error("Request to decrease counter of fd %d, which is outside the array size (1 to %d)", id, all_files_size);
1320 static inline void all_files_grow() {
1321 void *old = all_files;
1324 // there is no empty slot
1326 fprintf(stderr, "apps.plugin: extending fd array to %d entries\n", all_files_size + FILE_DESCRIPTORS_INCREASE_STEP);
1328 all_files = reallocz(all_files, (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP) * sizeof(struct file_descriptor));
1330 // if the address changed, we have to rebuild the index
1331 // since all pointers are now invalid
1333 if(unlikely(old && old != (void *)all_files)) {
1335 fprintf(stderr, "apps.plugin: >> re-indexing.\n");
1337 all_files_index.root = NULL;
1338 for(i = 0; i < all_files_size; i++) {
1339 if(!all_files[i].count) continue;
1340 if(unlikely(file_descriptor_add(&all_files[i]) != (void *)&all_files[i]))
1341 error("INTERNAL ERROR: duplicate indexing of fd during realloc.");
1345 fprintf(stderr, "apps.plugin: >> re-indexing done.\n");
1348 // initialize the newly added entries
1350 for(i = all_files_size; i < (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP); i++) {
1351 all_files[i].count = 0;
1352 all_files[i].name = NULL;
1353 #ifdef NETDATA_INTERNAL_CHECKS
1354 all_files[i].magic = 0x00000000;
1355 #endif /* NETDATA_INTERNAL_CHECKS */
1356 all_files[i].pos = i;
1359 if(unlikely(!all_files_size)) all_files_len = 1;
1360 all_files_size += FILE_DESCRIPTORS_INCREASE_STEP;
1363 static inline int file_descriptor_set_on_empty_slot(const char *name, uint32_t hash, FD_FILETYPE type) {
1364 // check we have enough memory to add it
1365 if(!all_files || all_files_len == all_files_size)
1369 fprintf(stderr, "apps.plugin: >> searching for empty slot.\n");
1371 // search for an empty slot
1373 static int last_pos = 0;
1375 for(i = 0, c = last_pos ; i < all_files_size ; i++, c++) {
1376 if(c >= all_files_size) c = 0;
1377 if(c == 0) continue;
1379 if(!all_files[c].count) {
1381 fprintf(stderr, "apps.plugin: >> Examining slot %d.\n", c);
1383 #ifdef NETDATA_INTERNAL_CHECKS
1384 if(all_files[c].magic == 0x0BADCAFE && all_files[c].name && file_descriptor_find(all_files[c].name, all_files[c].hash))
1385 error("fd on position %d is not cleared properly. It still has %s in it.\n", c, all_files[c].name);
1386 #endif /* NETDATA_INTERNAL_CHECKS */
1389 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);
1391 freez((void *)all_files[c].name);
1392 all_files[c].name = NULL;
1400 if(i == all_files_size) {
1401 fatal("We should find an empty slot, but there isn't any");
1404 // else we have an empty slot in 'c'
1407 fprintf(stderr, "apps.plugin: >> updating slot %d.\n", c);
1409 all_files[c].name = strdupz(name);
1410 all_files[c].hash = hash;
1411 all_files[c].type = type;
1412 all_files[c].pos = c;
1413 all_files[c].count = 1;
1414 #ifdef NETDATA_INTERNAL_CHECKS
1415 all_files[c].magic = 0x0BADCAFE;
1416 #endif /* NETDATA_INTERNAL_CHECKS */
1417 if(unlikely(file_descriptor_add(&all_files[c]) != (void *)&all_files[c]))
1418 error("INTERNAL ERROR: duplicate indexing of fd.");
1421 fprintf(stderr, "apps.plugin: using fd position %d (name: %s)\n", c, all_files[c].name);
1426 static inline int file_descriptor_find_or_add(const char *name)
1428 uint32_t hash = simple_hash(name);
1431 fprintf(stderr, "apps.plugin: adding or finding name '%s' with hash %u\n", name, hash);
1433 struct file_descriptor *fd = file_descriptor_find(name, hash);
1437 fprintf(stderr, "apps.plugin: >> found on slot %d\n", fd->pos);
1445 if(likely(name[0] == '/')) type = FILETYPE_FILE;
1446 else if(likely(strncmp(name, "pipe:", 5) == 0)) type = FILETYPE_PIPE;
1447 else if(likely(strncmp(name, "socket:", 7) == 0)) type = FILETYPE_SOCKET;
1448 else if(likely(strncmp(name, "anon_inode:", 11) == 0)) {
1449 const char *t = &name[11];
1451 if(strcmp(t, "inotify") == 0) type = FILETYPE_INOTIFY;
1452 else if(strcmp(t, "[eventfd]") == 0) type = FILETYPE_EVENTFD;
1453 else if(strcmp(t, "[eventpoll]") == 0) type = FILETYPE_EVENTPOLL;
1454 else if(strcmp(t, "[timerfd]") == 0) type = FILETYPE_TIMERFD;
1455 else if(strcmp(t, "[signalfd]") == 0) type = FILETYPE_SIGNALFD;
1458 fprintf(stderr, "apps.plugin: FIXME: unknown anonymous inode: %s\n", name);
1460 type = FILETYPE_OTHER;
1463 else if(likely(strcmp(name, "inotify") == 0)) type = FILETYPE_INOTIFY;
1466 fprintf(stderr, "apps.plugin: FIXME: cannot understand linkname: %s\n", name);
1468 type = FILETYPE_OTHER;
1471 return file_descriptor_set_on_empty_slot(name, hash, type);
1474 static inline void make_all_pid_fds_negative(struct pid_stat *p) {
1475 int *fd = p->fds, *end = &p->fds[p->fds_size];
1482 static inline void cleanup_negative_pid_fds(struct pid_stat *p) {
1483 int *fd = p->fds, *fdend = &p->fds[p->fds_size];
1486 if(unlikely(*fd < 0)) {
1487 file_descriptor_not_used(-(*fd));
1495 static inline void zero_pid_fds(struct pid_stat *p, int first, int size) {
1496 int *fd = &p->fds[first], *end = &p->fds[first + size];
1497 while(fd < end) *fd++ = 0;
1500 static inline int read_pid_file_descriptors(struct pid_stat *p, void *ptr) {
1505 struct kinfo_file *fds;
1506 static char *fdsbuf;
1507 char *bfdsbuf, *efdsbuf;
1508 char fdsname[FILENAME_MAX + 1];
1510 // we make all pid fds negative, so that
1511 // we can detect unused file descriptors
1512 // at the end, to free them
1513 make_all_pid_fds_negative(p);
1517 mib[2] = KERN_PROC_FILEDESC;
1520 if (unlikely(sysctl(mib, 4, NULL, &size, NULL, 0))) {
1521 error("sysctl error: Can't get file descriptors data size for pid %d", p->pid);
1524 if (likely(size > 0))
1525 fdsbuf = reallocz(fdsbuf, size);
1526 if (unlikely(sysctl(mib, 4, fdsbuf, &size, NULL, 0))) {
1527 error("sysctl error: Can't get file descriptors data for pid %d", p->pid);
1532 efdsbuf = fdsbuf + size;
1533 while (bfdsbuf < efdsbuf) {
1534 fds = (struct kinfo_file *)(uintptr_t)bfdsbuf;
1535 if (unlikely(fds->kf_structsize == 0))
1538 // do not process file descriptors for current working directory, root directory,
1539 // jail directory, ktrace vnode, text vnode and controlling terminal
1540 if (unlikely(fds->kf_fd < 0)) {
1541 bfdsbuf += fds->kf_structsize;
1545 // get file descriptors array index
1546 int fdid = fds->kf_fd;
1548 // check if the fds array is small
1549 if (unlikely(fdid >= p->fds_size)) {
1550 // it is small, extend it
1552 if (unlikely(debug))
1553 fprintf(stderr, "apps.plugin: extending fd memory slots for %s from %d to %d\n", p->comm, p->fds_size, fdid + MAX_SPARE_FDS);
1555 p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(int));
1557 // and initialize it
1558 zero_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
1559 p->fds_size = fdid + MAX_SPARE_FDS;
1562 if (unlikely(p->fds[fdid] == 0)) {
1563 // we don't know this fd, get it
1565 switch (fds->kf_type) {
1568 if (unlikely(!fds->kf_path[0])) {
1569 sprintf(fdsname, "other: inode: %lu", fds->kf_un.kf_file.kf_file_fileid);
1572 sprintf(fdsname, "%s", fds->kf_path);
1574 case KF_TYPE_SOCKET:
1575 switch (fds->kf_sock_domain) {
1578 if (fds->kf_sock_protocol == IPPROTO_TCP)
1579 sprintf(fdsname, "socket: %d %lx", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sock_inpcb);
1581 sprintf(fdsname, "socket: %d %lx", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sock_pcb);
1584 /* print address of pcb and connected pcb */
1585 sprintf(fdsname, "socket: %lx %lx", fds->kf_un.kf_sock.kf_sock_pcb, fds->kf_un.kf_sock.kf_sock_unpconn);
1588 /* print protocol number and socket address */
1589 sprintf(fdsname, "socket: other: %d %s %s", fds->kf_sock_protocol, fds->kf_sa_local.__ss_pad1, fds->kf_sa_local.__ss_pad2);
1593 sprintf(fdsname, "pipe: %lu %lu", fds->kf_un.kf_pipe.kf_pipe_addr, fds->kf_un.kf_pipe.kf_pipe_peer);
1596 sprintf(fdsname, "other: pts: %u", fds->kf_un.kf_pts.kf_pts_dev);
1599 sprintf(fdsname, "other: shm: %s size: %lu", fds->kf_path, fds->kf_un.kf_file.kf_file_size);
1602 sprintf(fdsname, "other: sem: %u", fds->kf_un.kf_sem.kf_sem_value);
1605 sprintf(fdsname, "other: pid: %d fd: %d", fds->kf_un.kf_proc.kf_pid, fds->kf_fd);
1608 // if another process already has this, we will get
1610 p->fds[fdid] = file_descriptor_find_or_add(fdsname);
1613 // else make it positive again, we need it
1614 // of course, the actual file may have changed, but we don't care so much
1615 // FIXME: we could compare the inode as returned by readdir dirent structure
1618 p->fds[fdid] = -p->fds[fdid];
1620 bfdsbuf += fds->kf_structsize;
1623 if(unlikely(!p->fds_dirname)) {
1624 char dirname[FILENAME_MAX+1];
1625 snprintfz(dirname, FILENAME_MAX, "%s/proc/%d/fd", netdata_configured_host_prefix, p->pid);
1626 p->fds_dirname = strdupz(dirname);
1629 DIR *fds = opendir(p->fds_dirname);
1630 if(unlikely(!fds)) return 0;
1633 char fdname[FILENAME_MAX + 1];
1634 char linkname[FILENAME_MAX + 1];
1636 // we make all pid fds negative, so that
1637 // we can detect unused file descriptors
1638 // at the end, to free them
1639 make_all_pid_fds_negative(p);
1641 while((de = readdir(fds))) {
1642 // we need only files with numeric names
1644 if(unlikely(de->d_name[0] < '0' || de->d_name[0] > '9'))
1648 int fdid = (int) str2l(de->d_name);
1649 if(unlikely(fdid < 0)) continue;
1651 // check if the fds array is small
1652 if(unlikely(fdid >= p->fds_size)) {
1653 // it is small, extend it
1657 , "apps.plugin: extending fd memory slots for %s from %d to %d\n"
1660 , fdid + MAX_SPARE_FDS
1663 p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(int));
1665 // and initialize it
1666 zero_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
1667 p->fds_size = fdid + MAX_SPARE_FDS;
1670 if(unlikely(p->fds[fdid] == 0)) {
1671 // we don't know this fd, get it
1673 sprintf(fdname, "%s/proc/%d/fd/%s", netdata_configured_host_prefix, p->pid, de->d_name);
1674 ssize_t l = readlink(fdname, linkname, FILENAME_MAX);
1675 if(unlikely(l == -1)) {
1676 if(debug || (p->target && p->target->debug)) {
1677 if(debug || (p->target && p->target->debug))
1678 error("Cannot read link %s", fdname);
1687 // if another process already has this, we will get
1689 p->fds[fdid] = file_descriptor_find_or_add(linkname);
1692 // else make it positive again, we need it
1693 // of course, the actual file may have changed, but we don't care so much
1694 // FIXME: we could compare the inode as returned by readdir dirent structure
1695 // UPDATE: no we cannot use inodes - under /proc inodes don't change when the link is changed
1698 p->fds[fdid] = -p->fds[fdid];
1703 cleanup_negative_pid_fds(p);
1708 // ----------------------------------------------------------------------------
1710 static inline int print_process_and_parents(struct pid_stat *p, usec_t time) {
1711 char *prefix = "\\_ ";
1715 indent = print_process_and_parents(p->parent, p->stat_collected_usec);
1719 char buffer[indent + 1];
1722 for(i = 0; i < indent ;i++) buffer[i] = ' ';
1725 fprintf(stderr, " %s %s%s (%d %s %llu"
1730 , p->updated?"running":"exited"
1731 , p->stat_collected_usec - time
1734 if(p->utime) fprintf(stderr, " utime=" KERNEL_UINT_FORMAT, p->utime);
1735 if(p->stime) fprintf(stderr, " stime=" KERNEL_UINT_FORMAT, p->stime);
1736 if(p->gtime) fprintf(stderr, " gtime=" KERNEL_UINT_FORMAT, p->gtime);
1737 if(p->cutime) fprintf(stderr, " cutime=" KERNEL_UINT_FORMAT, p->cutime);
1738 if(p->cstime) fprintf(stderr, " cstime=" KERNEL_UINT_FORMAT, p->cstime);
1739 if(p->cgtime) fprintf(stderr, " cgtime=" KERNEL_UINT_FORMAT, p->cgtime);
1740 if(p->minflt) fprintf(stderr, " minflt=" KERNEL_UINT_FORMAT, p->minflt);
1741 if(p->cminflt) fprintf(stderr, " cminflt=" KERNEL_UINT_FORMAT, p->cminflt);
1742 if(p->majflt) fprintf(stderr, " majflt=" KERNEL_UINT_FORMAT, p->majflt);
1743 if(p->cmajflt) fprintf(stderr, " cmajflt=" KERNEL_UINT_FORMAT, p->cmajflt);
1744 fprintf(stderr, ")\n");
1749 static inline void print_process_tree(struct pid_stat *p, char *msg) {
1751 fprintf(stderr, "%s: process %s (%d, %s) with parents:\n", msg, p->comm, p->pid, p->updated?"running":"exited");
1752 print_process_and_parents(p, p->stat_collected_usec);
1755 static inline void find_lost_child_debug(struct pid_stat *pe, kernel_uint_t lost, int type) {
1757 struct pid_stat *p = NULL;
1759 for(p = root_of_pids; p ; p = p->next) {
1760 if(p == pe) continue;
1764 if(p->cminflt > lost) {
1765 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);
1771 if(p->cmajflt > lost) {
1772 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);
1778 if(p->cutime > lost) {
1779 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);
1785 if(p->cstime > lost) {
1786 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);
1792 if(p->cgtime > lost) {
1793 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);
1803 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);
1807 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);
1811 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);
1815 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);
1819 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);
1825 static inline kernel_uint_t remove_exited_child_from_parent(kernel_uint_t *field, kernel_uint_t *pfield) {
1826 kernel_uint_t absorbed = 0;
1828 if(*field > *pfield) {
1829 absorbed += *pfield;
1842 static inline void process_exited_processes() {
1845 for(p = root_of_pids; p ; p = p->next) {
1846 if(p->updated || !p->stat_collected_usec)
1849 kernel_uint_t utime = (p->utime_raw + p->cutime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1850 kernel_uint_t stime = (p->stime_raw + p->cstime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1851 kernel_uint_t gtime = (p->gtime_raw + p->cgtime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1852 kernel_uint_t minflt = (p->minflt_raw + p->cminflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1853 kernel_uint_t majflt = (p->majflt_raw + p->cmajflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1855 if(utime + stime + gtime + minflt + majflt == 0)
1858 if(unlikely(debug)) {
1860 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"
1863 , p->updated?"running":"exited"
1870 print_process_tree(p, "Searching parents");
1873 struct pid_stat *pp;
1874 for(pp = p->parent; pp ; pp = pp->parent) {
1875 if(!pp->updated) continue;
1877 kernel_uint_t absorbed;
1878 absorbed = remove_exited_child_from_parent(&utime, &pp->cutime);
1879 if(unlikely(debug && absorbed))
1880 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);
1882 absorbed = remove_exited_child_from_parent(&stime, &pp->cstime);
1883 if(unlikely(debug && absorbed))
1884 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);
1886 absorbed = remove_exited_child_from_parent(>ime, &pp->cgtime);
1887 if(unlikely(debug && absorbed))
1888 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);
1890 absorbed = remove_exited_child_from_parent(&minflt, &pp->cminflt);
1891 if(unlikely(debug && absorbed))
1892 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);
1894 absorbed = remove_exited_child_from_parent(&majflt, &pp->cmajflt);
1895 if(unlikely(debug && absorbed))
1896 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);
1899 if(unlikely(utime + stime + gtime + minflt + majflt > 0)) {
1900 if(unlikely(debug)) {
1901 if(utime) find_lost_child_debug(p, utime, 3);
1902 if(stime) find_lost_child_debug(p, stime, 4);
1903 if(gtime) find_lost_child_debug(p, gtime, 5);
1904 if(minflt) find_lost_child_debug(p, minflt, 1);
1905 if(majflt) find_lost_child_debug(p, majflt, 2);
1911 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"
1914 , p->updated?"running":"exited"
1922 for(pp = p->parent; pp ; pp = pp->parent) {
1923 if(pp->updated) break;
1927 fprintf(stderr, " > - KEEP - parent for another loop: %s (%d %s)\n"
1930 , pp->updated?"running":"exited"
1934 p->utime_raw = utime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1935 p->stime_raw = stime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1936 p->gtime_raw = gtime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1937 p->minflt_raw = minflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1938 p->majflt_raw = majflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1939 p->cutime_raw = p->cstime_raw = p->cgtime_raw = p->cminflt_raw = p->cmajflt_raw = 0;
1942 fprintf(stderr, "\n");
1944 else if(unlikely(debug)) {
1945 fprintf(stderr, " > totally absorbed - DONE - %s (%d %s)\n"
1948 , p->updated?"running":"exited"
1954 static inline void link_all_processes_to_their_parents(void) {
1955 struct pid_stat *p, *pp;
1957 // link all children to their parents
1958 // and update children count on parents
1959 for(p = root_of_pids; p ; p = p->next) {
1960 // for each process found
1965 if(unlikely(!p->ppid)) {
1970 pp = all_pids[p->ppid];
1973 pp->children_count++;
1975 if(unlikely(debug || (p->target && p->target->debug)))
1976 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);
1980 error("pid %d %s states parent %d, but the later does not exist.", p->pid, p->comm, p->ppid);
1985 // ----------------------------------------------------------------------------
1987 // 1. read all files in /proc
1988 // 2. for each numeric directory:
1989 // i. read /proc/pid/stat
1990 // ii. read /proc/pid/statm
1991 // iii. read /proc/pid/io (requires root access)
1992 // iii. read the entries in directory /proc/pid/fd (requires root access)
1994 // a. find or create a struct file_descriptor
1995 // b. cleanup any old/unused file_descriptors
1997 // after all these, some pids may be linked to targets, while others may not
1999 // in case of errors, only 1 every 1000 errors is printed
2000 // to avoid filling up all disk space
2001 // if debug is enabled, all errors are printed
2003 static int compar_pid(const void *pid1, const void *pid2) {
2005 struct pid_stat *p1 = all_pids[*((pid_t *)pid1)];
2006 struct pid_stat *p2 = all_pids[*((pid_t *)pid2)];
2008 if(p1->sortlist > p2->sortlist)
2014 static inline int collect_data_for_pid(pid_t pid, void *ptr) {
2015 if(unlikely(pid < INIT_PID || pid > pid_max)) {
2016 error("Invalid pid %d read (expected %d to %d). Ignoring process.", pid, INIT_PID, pid_max);
2020 struct pid_stat *p = get_pid_entry(pid);
2021 if(unlikely(!p || p->read)) return 0;
2024 // fprintf(stderr, "Reading process %d (%s), sortlist %d\n", p->pid, p->comm, p->sortlist);
2026 // --------------------------------------------------------------------
2029 if(unlikely(!managed_log(p, PID_LOG_STAT, read_proc_pid_stat(p, ptr))))
2030 // there is no reason to proceed if we cannot get its status
2033 read_proc_pid_ownership(p, ptr);
2035 // check its parent pid
2036 if(unlikely(p->ppid < 0 || p->ppid > pid_max)) {
2037 error("Pid %d (command '%s') states invalid parent pid %d. Using 0.", pid, p->comm, p->ppid);
2041 // --------------------------------------------------------------------
2044 managed_log(p, PID_LOG_IO, read_proc_pid_io(p, ptr));
2046 // --------------------------------------------------------------------
2047 // /proc/<pid>/statm
2049 if(unlikely(!managed_log(p, PID_LOG_STATM, read_proc_pid_statm(p, ptr))))
2050 // there is no reason to proceed if we cannot get its memory status
2053 // --------------------------------------------------------------------
2056 if(enable_file_charts)
2057 managed_log(p, PID_LOG_FDS, read_pid_file_descriptors(p, ptr));
2059 // --------------------------------------------------------------------
2062 if(unlikely(debug && include_exited_childs && all_pids_count && p->ppid && all_pids[p->ppid] && !all_pids[p->ppid]->read))
2063 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);
2065 // mark it as updated
2073 static int collect_data_for_all_processes(void) {
2074 struct pid_stat *p = NULL;
2078 size_t procbase_size;
2079 static struct kinfo_proc *procbase;
2085 mib[2] = KERN_PROC_PROC;
2086 if (unlikely(sysctl(mib, 3, NULL, &procbase_size, NULL, 0))) {
2087 error("sysctl error: Can't get processes data size");
2090 procbase = reallocz(procbase, procbase_size);
2091 if (unlikely(sysctl(mib, 3, procbase, &procbase_size, NULL, 0))) {
2092 error("sysctl error: Can't get processes data");
2095 procnum = procbase_size / sizeof(struct kinfo_proc);
2098 if(all_pids_count) {
2100 for(p = root_of_pids; p ; p = p->next) {
2101 p->read = 0; // mark it as not read, so that collect_data_for_pid() will read it
2104 p->children_count = 0;
2107 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
2108 all_pids_sortlist[slc++] = p->pid;
2112 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
2113 if(unlikely(slc != all_pids_count)) {
2114 error("Internal error: I was thinking I had %zu processes in my arrays, but it seems there are more.", all_pids_count);
2115 all_pids_count = slc;
2118 if(include_exited_childs) {
2119 // Read parents before childs
2120 // This is needed to prevent a situation where
2121 // a child is found running, but until we read
2122 // its parent, it has exited and its parent
2123 // has accumulated its resources.
2125 qsort((void *)all_pids_sortlist, (size_t)all_pids_count, sizeof(pid_t), compar_pid);
2127 // we forward read all running processes
2128 // collect_data_for_pid() is smart enough,
2129 // not to read the same pid twice per iteration
2130 for(slc = 0; slc < all_pids_count; slc++)
2131 collect_data_for_pid(all_pids_sortlist[slc], NULL);
2137 for (i = INIT_PID; i < procnum - INIT_PID; ++i) {
2138 pid_t pid = procbase[i].ki_pid;
2139 collect_data_for_pid(pid, &procbase[i]);
2142 char dirname[FILENAME_MAX + 1];
2144 snprintfz(dirname, FILENAME_MAX, "%s/proc", netdata_configured_host_prefix);
2145 DIR *dir = opendir(dirname);
2148 struct dirent *de = NULL;
2150 while((de = readdir(dir))) {
2151 char *endptr = de->d_name;
2153 if(unlikely(de->d_type != DT_DIR || de->d_name[0] < '0' || de->d_name[0] > '9'))
2156 pid_t pid = (pid_t) strtoul(de->d_name, &endptr, 10);
2158 // make sure we read a valid number
2159 if(unlikely(endptr == de->d_name || *endptr != '\0'))
2162 collect_data_for_pid(pid, NULL);
2170 // we need /proc/stat to normalize the cpu consumption of the exited childs
2173 // build the process tree
2174 link_all_processes_to_their_parents();
2176 // normally this is done
2177 // however we may have processes exited while we collected values
2178 // so let's find the exited ones
2179 // we do this by collecting the ownership of process
2180 // if we manage to get the ownership, the process still runs
2181 process_exited_processes();
2186 // ----------------------------------------------------------------------------
2187 // update statistics on the targets
2189 // 1. link all childs to their parents
2190 // 2. go from bottom to top, marking as merged all childs to their parents
2191 // this step links all parents without a target to the child target, if any
2192 // 3. link all top level processes (the ones not merged) to the default target
2193 // 4. go from top to bottom, linking all childs without a target, to their parent target
2194 // after this step, all processes have a target
2195 // [5. for each killed pid (updated = 0), remove its usage from its target]
2196 // 6. zero all apps_groups_targets
2197 // 7. concentrate all values on the apps_groups_targets
2198 // 8. remove all killed processes
2199 // 9. find the unique file count for each target
2200 // check: update_apps_groups_statistics()
2202 static void cleanup_exited_pids(void) {
2204 struct pid_stat *p = NULL;
2206 for(p = root_of_pids; p ;) {
2207 if(!p->updated && (!p->keep || p->keeploops > 0)) {
2208 if(unlikely(debug && (p->keep || p->keeploops)))
2209 fprintf(stderr, " > CLEANUP cannot keep exited process %d (%s) anymore - removing it.\n", p->pid, p->comm);
2211 for(c = 0; c < p->fds_size; c++)
2213 file_descriptor_not_used(p->fds[c]);
2222 if(unlikely(p->keep)) p->keeploops++;
2229 static void apply_apps_groups_targets_inheritance(void) {
2230 struct pid_stat *p = NULL;
2232 // children that do not have a target
2233 // inherit their target from their parent
2234 int found = 1, loops = 0;
2236 if(unlikely(debug)) loops++;
2238 for(p = root_of_pids; p ; p = p->next) {
2239 // if this process does not have a target
2240 // and it has a parent
2241 // and its parent has a target
2242 // then, set the parent's target to this process
2243 if(unlikely(!p->target && p->parent && p->parent->target)) {
2244 p->target = p->parent->target;
2247 if(debug || (p->target && p->target->debug))
2248 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);
2253 // find all the procs with 0 childs and merge them to their parents
2254 // repeat, until nothing more can be done.
2258 if(unlikely(debug)) loops++;
2261 for(p = root_of_pids; p ; p = p->next) {
2262 if(unlikely(!p->sortlist && !p->children_count))
2263 p->sortlist = sortlist++;
2265 // if this process does not have any children
2266 // and is not already merged
2268 // and its parent has children
2269 // and the target of this process and its parent is the same, or the parent does not have a target
2270 // and its parent is not init
2271 // then, mark them as merged.
2276 && p->parent->children_count
2277 && (p->target == p->parent->target || !p->parent->target)
2278 && p->ppid != INIT_PID
2280 p->parent->children_count--;
2283 // the parent inherits the child's target, if it does not have a target itself
2284 if(unlikely(p->target && !p->parent->target)) {
2285 p->parent->target = p->target;
2287 if(debug || (p->target && p->target->debug))
2288 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);
2296 fprintf(stderr, "apps.plugin: TARGET INHERITANCE: merged %d processes\n", found);
2299 // init goes always to default target
2300 if(all_pids[INIT_PID])
2301 all_pids[INIT_PID]->target = apps_groups_default_target;
2303 // give a default target on all top level processes
2304 if(unlikely(debug)) loops++;
2305 for(p = root_of_pids; p ; p = p->next) {
2306 // if the process is not merged itself
2307 // then is is a top level process
2308 if(unlikely(!p->merged && !p->target))
2309 p->target = apps_groups_default_target;
2311 // make sure all processes have a sortlist
2312 if(unlikely(!p->sortlist))
2313 p->sortlist = sortlist++;
2317 all_pids[1]->sortlist = sortlist++;
2319 // give a target to all merged child processes
2322 if(unlikely(debug)) loops++;
2324 for(p = root_of_pids; p ; p = p->next) {
2325 if(unlikely(!p->target && p->merged && p->parent && p->parent->target)) {
2326 p->target = p->parent->target;
2329 if(debug || (p->target && p->target->debug))
2330 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);
2336 fprintf(stderr, "apps.plugin: apply_apps_groups_targets_inheritance() made %d loops on the process tree\n", loops);
2339 static size_t zero_all_targets(struct target *root) {
2343 for (w = root; w ; w = w->next) {
2361 w->statm_resident = 0;
2363 // w->statm_text = 0;
2364 // w->statm_lib = 0;
2365 // w->statm_data = 0;
2366 // w->statm_dirty = 0;
2368 w->io_logical_bytes_read = 0;
2369 w->io_logical_bytes_written = 0;
2370 // w->io_read_calls = 0;
2371 // w->io_write_calls = 0;
2372 w->io_storage_bytes_read = 0;
2373 w->io_storage_bytes_written = 0;
2374 // w->io_cancelled_write_bytes = 0;
2376 // zero file counters
2378 memset(w->target_fds, 0, sizeof(int) * w->target_fds_size);
2382 w->openinotifies = 0;
2383 w->openeventfds = 0;
2384 w->opentimerfds = 0;
2385 w->opensignalfds = 0;
2386 w->openeventpolls = 0;
2394 static inline void reallocate_target_fds(struct target *w) {
2398 if(unlikely(!w->target_fds || w->target_fds_size < all_files_size)) {
2399 w->target_fds = reallocz(w->target_fds, sizeof(int) * all_files_size);
2400 memset(&w->target_fds[w->target_fds_size], 0, sizeof(int) * (all_files_size - w->target_fds_size));
2401 w->target_fds_size = all_files_size;
2405 static inline void aggregate_fd_on_target(int fd, struct target *w) {
2409 if(unlikely(w->target_fds[fd])) {
2410 // it is already aggregated
2411 // just increase its usage counter
2412 w->target_fds[fd]++;
2416 // increase its usage counter
2417 // so that we will not add it again
2418 w->target_fds[fd]++;
2420 switch(all_files[fd].type) {
2429 case FILETYPE_SOCKET:
2433 case FILETYPE_INOTIFY:
2437 case FILETYPE_EVENTFD:
2441 case FILETYPE_TIMERFD:
2445 case FILETYPE_SIGNALFD:
2449 case FILETYPE_EVENTPOLL:
2450 w->openeventpolls++;
2453 case FILETYPE_OTHER:
2459 static inline void aggregate_pid_fds_on_targets(struct pid_stat *p) {
2461 if(unlikely(!p->updated)) {
2462 // the process is not running
2466 struct target *w = p->target, *u = p->user_target, *g = p->group_target;
2468 reallocate_target_fds(w);
2469 reallocate_target_fds(u);
2470 reallocate_target_fds(g);
2472 int c, size = p->fds_size, *fds = p->fds;
2473 for(c = 0; c < size ;c++) {
2476 if(likely(fd <= 0 || fd >= all_files_size))
2479 aggregate_fd_on_target(fd, w);
2480 aggregate_fd_on_target(fd, u);
2481 aggregate_fd_on_target(fd, g);
2485 static inline void aggregate_pid_on_target(struct target *w, struct pid_stat *p, struct target *o) {
2488 if(unlikely(!p->updated)) {
2489 // the process is not running
2494 error("pid %d %s was left without a target!", p->pid, p->comm);
2498 w->cutime += p->cutime;
2499 w->cstime += p->cstime;
2500 w->cgtime += p->cgtime;
2501 w->cminflt += p->cminflt;
2502 w->cmajflt += p->cmajflt;
2504 w->utime += p->utime;
2505 w->stime += p->stime;
2506 w->gtime += p->gtime;
2507 w->minflt += p->minflt;
2508 w->majflt += p->majflt;
2510 // w->rss += p->rss;
2512 w->statm_size += p->statm_size;
2513 w->statm_resident += p->statm_resident;
2514 w->statm_share += p->statm_share;
2515 // w->statm_text += p->statm_text;
2516 // w->statm_lib += p->statm_lib;
2517 // w->statm_data += p->statm_data;
2518 // w->statm_dirty += p->statm_dirty;
2520 w->io_logical_bytes_read += p->io_logical_bytes_read;
2521 w->io_logical_bytes_written += p->io_logical_bytes_written;
2522 // w->io_read_calls += p->io_read_calls;
2523 // w->io_write_calls += p->io_write_calls;
2524 w->io_storage_bytes_read += p->io_storage_bytes_read;
2525 w->io_storage_bytes_written += p->io_storage_bytes_written;
2526 // w->io_cancelled_write_bytes += p->io_cancelled_write_bytes;
2529 w->num_threads += p->num_threads;
2531 if(unlikely(debug || w->debug))
2532 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);
2535 static void calculate_netdata_statistics(void) {
2537 apply_apps_groups_targets_inheritance();
2539 zero_all_targets(users_root_target);
2540 zero_all_targets(groups_root_target);
2541 apps_groups_targets_count = zero_all_targets(apps_groups_root_target);
2543 // this has to be done, before the cleanup
2544 struct pid_stat *p = NULL;
2545 struct target *w = NULL, *o = NULL;
2547 // concentrate everything on the targets
2548 for(p = root_of_pids; p ; p = p->next) {
2550 // --------------------------------------------------------------------
2551 // apps_groups target
2553 aggregate_pid_on_target(p->target, p, NULL);
2556 // --------------------------------------------------------------------
2560 if(likely(p->user_target && p->user_target->uid == p->uid))
2563 if(unlikely(debug && p->user_target))
2564 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);
2566 w = p->user_target = get_users_target(p->uid);
2569 aggregate_pid_on_target(w, p, o);
2572 // --------------------------------------------------------------------
2573 // user group target
2575 o = p->group_target;
2576 if(likely(p->group_target && p->group_target->gid == p->gid))
2577 w = p->group_target;
2579 if(unlikely(debug && p->group_target))
2580 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);
2582 w = p->group_target = get_groups_target(p->gid);
2585 aggregate_pid_on_target(w, p, o);
2588 // --------------------------------------------------------------------
2589 // aggregate all file descriptors
2591 if(enable_file_charts)
2592 aggregate_pid_fds_on_targets(p);
2595 cleanup_exited_pids();
2598 // ----------------------------------------------------------------------------
2599 // update chart dimensions
2601 int print_calculated_number(char *str, calculated_number value) { (void)str; (void)value; return 0; }
2603 static inline void send_BEGIN(const char *type, const char *id, usec_t usec) {
2604 fprintf(stdout, "BEGIN %s.%s %llu\n", type, id, usec);
2607 static inline void send_SET(const char *name, kernel_uint_t value) {
2608 fprintf(stdout, "SET %s = " KERNEL_UINT_FORMAT "\n", name, value);
2611 static inline void send_END(void) {
2612 fprintf(stdout, "END\n");
2615 static usec_t send_resource_usage_to_netdata() {
2616 static struct timeval last = { 0, 0 };
2617 static struct rusage me_last;
2627 now_monotonic_timeval(&last);
2628 getrusage(RUSAGE_SELF, &me_last);
2630 // the first time, give a zero to allow
2631 // netdata calibrate to the current time
2632 // usec = update_every * USEC_PER_SEC;
2638 now_monotonic_timeval(&now);
2639 getrusage(RUSAGE_SELF, &me);
2641 usec = dt_usec(&now, &last);
2642 cpuuser = me.ru_utime.tv_sec * USEC_PER_SEC + me.ru_utime.tv_usec;
2643 cpusyst = me.ru_stime.tv_sec * USEC_PER_SEC + me.ru_stime.tv_usec;
2645 memmove(&last, &now, sizeof(struct timeval));
2646 memmove(&me_last, &me, sizeof(struct rusage));
2649 static char created_charts = 0;
2650 if(unlikely(!created_charts)) {
2654 , "CHART netdata.apps_cpu '' 'Apps Plugin CPU' 'milliseconds/s' apps.plugin netdata.apps_cpu stacked 140000 %1$d\n"
2655 "DIMENSION user '' incremental 1 1000\n"
2656 "DIMENSION system '' incremental 1 1000\n"
2657 "CHART netdata.apps_sizes '' 'Apps Plugin Files' 'files/s' apps.plugin netdata.apps_sizes line 140001 %1$d\n"
2658 "DIMENSION calls '' incremental 1 1\n"
2659 "DIMENSION files '' incremental 1 1\n"
2660 "DIMENSION pids '' absolute 1 1\n"
2661 "DIMENSION fds '' absolute 1 1\n"
2662 "DIMENSION targets '' absolute 1 1\n"
2663 "DIMENSION new_pids 'new pids' incremental 1 1\n"
2664 "CHART netdata.apps_fix '' 'Apps Plugin Normalization Ratios' 'percentage' apps.plugin netdata.apps_fix line 140002 %1$d\n"
2665 "DIMENSION utime '' absolute 1 %2$llu\n"
2666 "DIMENSION stime '' absolute 1 %2$llu\n"
2667 "DIMENSION gtime '' absolute 1 %2$llu\n"
2668 "DIMENSION minflt '' absolute 1 %2$llu\n"
2669 "DIMENSION majflt '' absolute 1 %2$llu\n"
2674 if(include_exited_childs)
2676 , "CHART netdata.apps_children_fix '' 'Apps Plugin Exited Children Normalization Ratios' 'percentage' apps.plugin netdata.apps_children_fix line 140003 %1$d\n"
2677 "DIMENSION cutime '' absolute 1 %2$llu\n"
2678 "DIMENSION cstime '' absolute 1 %2$llu\n"
2679 "DIMENSION cgtime '' absolute 1 %2$llu\n"
2680 "DIMENSION cminflt '' absolute 1 %2$llu\n"
2681 "DIMENSION cmajflt '' absolute 1 %2$llu\n"
2688 "BEGIN netdata.apps_cpu %llu\n"
2690 "SET system = %llu\n"
2692 "BEGIN netdata.apps_sizes %llu\n"
2697 "SET targets = %zu\n"
2698 "SET new_pids = %zu\n"
2700 "BEGIN netdata.apps_fix %llu\n"
2715 , apps_groups_targets_count
2716 , targets_assignment_counter
2718 , (unsigned int)(utime_fix_ratio * 100 * RATES_DETAIL)
2719 , (unsigned int)(stime_fix_ratio * 100 * RATES_DETAIL)
2720 , (unsigned int)(gtime_fix_ratio * 100 * RATES_DETAIL)
2721 , (unsigned int)(minflt_fix_ratio * 100 * RATES_DETAIL)
2722 , (unsigned int)(majflt_fix_ratio * 100 * RATES_DETAIL)
2725 if(include_exited_childs)
2727 "BEGIN netdata.apps_children_fix %llu\n"
2731 "SET cminflt = %u\n"
2732 "SET cmajflt = %u\n"
2735 , (unsigned int)(cutime_fix_ratio * 100 * RATES_DETAIL)
2736 , (unsigned int)(cstime_fix_ratio * 100 * RATES_DETAIL)
2737 , (unsigned int)(cgtime_fix_ratio * 100 * RATES_DETAIL)
2738 , (unsigned int)(cminflt_fix_ratio * 100 * RATES_DETAIL)
2739 , (unsigned int)(cmajflt_fix_ratio * 100 * RATES_DETAIL)
2745 static void normalize_utilization(struct target *root) {
2748 // childs processing introduces spikes
2749 // here we try to eliminate them by disabling childs processing either for specific dimensions
2750 // or entirely. Of course, either way, we disable it just a single iteration.
2752 kernel_uint_t max_time = processors * hz * RATES_DETAIL;
2753 kernel_uint_t utime = 0, cutime = 0, stime = 0, cstime = 0, gtime = 0, cgtime = 0, minflt = 0, cminflt = 0, majflt = 0, cmajflt = 0;
2755 if(global_utime > max_time) global_utime = max_time;
2756 if(global_stime > max_time) global_stime = max_time;
2757 if(global_gtime > max_time) global_gtime = max_time;
2759 for(w = root; w ; w = w->next) {
2760 if(w->target || (!w->processes && !w->exposed)) continue;
2765 cutime += w->cutime;
2766 cstime += w->cstime;
2767 cgtime += w->cgtime;
2769 minflt += w->minflt;
2770 majflt += w->majflt;
2771 cminflt += w->cminflt;
2772 cmajflt += w->cmajflt;
2775 if((global_utime || global_stime || global_gtime) && (utime || stime || gtime)) {
2776 if(global_utime + global_stime + global_gtime > utime + cutime + stime + cstime + gtime + cgtime) {
2777 // everything we collected fits
2783 cgtime_fix_ratio = 1.0; //(double)(global_utime + global_stime) / (double)(utime + cutime + stime + cstime);
2785 else if(global_utime + global_stime > utime + stime) {
2786 // childrens resources are too high
2787 // lower only the children resources
2790 gtime_fix_ratio = 1.0;
2793 cgtime_fix_ratio = (double)((global_utime + global_stime) - (utime + stime)) / (double)(cutime + cstime);
2796 // even running processes are unrealistic
2797 // zero the children resources
2798 // lower the running processes resources
2801 gtime_fix_ratio = (double)(global_utime + global_stime) / (double)(utime + stime);
2804 cgtime_fix_ratio = 0.0;
2813 cgtime_fix_ratio = 0.0;
2816 if(utime_fix_ratio > 1.0) utime_fix_ratio = 1.0;
2817 if(cutime_fix_ratio > 1.0) cutime_fix_ratio = 1.0;
2818 if(stime_fix_ratio > 1.0) stime_fix_ratio = 1.0;
2819 if(cstime_fix_ratio > 1.0) cstime_fix_ratio = 1.0;
2820 if(gtime_fix_ratio > 1.0) gtime_fix_ratio = 1.0;
2821 if(cgtime_fix_ratio > 1.0) cgtime_fix_ratio = 1.0;
2823 // if(utime_fix_ratio < 0.0) utime_fix_ratio = 0.0;
2824 // if(cutime_fix_ratio < 0.0) cutime_fix_ratio = 0.0;
2825 // if(stime_fix_ratio < 0.0) stime_fix_ratio = 0.0;
2826 // if(cstime_fix_ratio < 0.0) cstime_fix_ratio = 0.0;
2827 // if(gtime_fix_ratio < 0.0) gtime_fix_ratio = 0.0;
2828 // if(cgtime_fix_ratio < 0.0) cgtime_fix_ratio = 0.0;
2831 // we use cpu time to normalize page faults
2832 // the problem is that to find the proper max values
2833 // for page faults we have to parse /proc/vmstat
2834 // which is quite big to do it again (netdata does it already)
2836 // a better solution could be to somehow have netdata
2837 // do this normalization for us
2839 if(utime || stime || gtime)
2841 minflt_fix_ratio = (double)(utime * utime_fix_ratio + stime * stime_fix_ratio + gtime * gtime_fix_ratio) / (double)(utime + stime + gtime);
2844 majflt_fix_ratio = 1.0;
2846 if(cutime || cstime || cgtime)
2848 cminflt_fix_ratio = (double)(cutime * cutime_fix_ratio + cstime * cstime_fix_ratio + cgtime * cgtime_fix_ratio) / (double)(cutime + cstime + cgtime);
2851 cmajflt_fix_ratio = 1.0;
2855 if(unlikely(debug)) {
2857 "SYSTEM: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
2858 "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 " "
2859 "DELTA: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
2860 "FIX: u=%0.2f s=%0.2f g=%0.2f cu=%0.2f cs=%0.2f cg=%0.2f "
2861 "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 " "
2872 , utime + cutime - global_utime
2873 , stime + cstime - global_stime
2874 , gtime + cgtime - global_gtime
2881 , (kernel_uint_t)(utime * utime_fix_ratio)
2882 , (kernel_uint_t)(stime * stime_fix_ratio)
2883 , (kernel_uint_t)(gtime * gtime_fix_ratio)
2884 , (kernel_uint_t)(cutime * cutime_fix_ratio)
2885 , (kernel_uint_t)(cstime * cstime_fix_ratio)
2886 , (kernel_uint_t)(cgtime * cgtime_fix_ratio)
2891 static void send_collected_data_to_netdata(struct target *root, const char *type, usec_t usec) {
2894 send_BEGIN(type, "cpu", usec);
2895 for (w = root; w ; w = w->next) {
2896 if(unlikely(w->exposed))
2897 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));
2901 send_BEGIN(type, "cpu_user", usec);
2902 for (w = root; w ; w = w->next) {
2903 if(unlikely(w->exposed))
2904 send_SET(w->name, (kernel_uint_t)(w->utime * utime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cutime * cutime_fix_ratio)):0ULL));
2908 send_BEGIN(type, "cpu_system", usec);
2909 for (w = root; w ; w = w->next) {
2910 if(unlikely(w->exposed))
2911 send_SET(w->name, (kernel_uint_t)(w->stime * stime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cstime * cstime_fix_ratio)):0ULL));
2915 if(show_guest_time) {
2916 send_BEGIN(type, "cpu_guest", usec);
2917 for (w = root; w ; w = w->next) {
2918 if(unlikely(w->exposed))
2919 send_SET(w->name, (kernel_uint_t)(w->gtime * gtime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cgtime * cgtime_fix_ratio)):0ULL));
2924 send_BEGIN(type, "threads", usec);
2925 for (w = root; w ; w = w->next) {
2926 if(unlikely(w->exposed))
2927 send_SET(w->name, w->num_threads);
2931 send_BEGIN(type, "processes", usec);
2932 for (w = root; w ; w = w->next) {
2933 if(unlikely(w->exposed))
2934 send_SET(w->name, w->processes);
2938 send_BEGIN(type, "mem", usec);
2939 for (w = root; w ; w = w->next) {
2940 if(unlikely(w->exposed))
2941 send_SET(w->name, (w->statm_resident > w->statm_share)?(w->statm_resident - w->statm_share):0ULL);
2945 send_BEGIN(type, "vmem", usec);
2946 for (w = root; w ; w = w->next) {
2947 if(unlikely(w->exposed))
2948 send_SET(w->name, w->statm_size);
2952 send_BEGIN(type, "minor_faults", usec);
2953 for (w = root; w ; w = w->next) {
2954 if(unlikely(w->exposed))
2955 send_SET(w->name, (kernel_uint_t)(w->minflt * minflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cminflt * cminflt_fix_ratio)):0ULL));
2959 send_BEGIN(type, "major_faults", usec);
2960 for (w = root; w ; w = w->next) {
2961 if(unlikely(w->exposed))
2962 send_SET(w->name, (kernel_uint_t)(w->majflt * majflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cmajflt * cmajflt_fix_ratio)):0ULL));
2967 send_BEGIN(type, "lreads", usec);
2968 for (w = root; w ; w = w->next) {
2969 if(unlikely(w->exposed))
2970 send_SET(w->name, w->io_logical_bytes_read);
2974 send_BEGIN(type, "lwrites", usec);
2975 for (w = root; w ; w = w->next) {
2976 if(unlikely(w->exposed))
2977 send_SET(w->name, w->io_logical_bytes_written);
2982 send_BEGIN(type, "preads", usec);
2983 for (w = root; w ; w = w->next) {
2984 if(unlikely(w->exposed))
2985 send_SET(w->name, w->io_storage_bytes_read);
2989 send_BEGIN(type, "pwrites", usec);
2990 for (w = root; w ; w = w->next) {
2991 if(unlikely(w->exposed))
2992 send_SET(w->name, w->io_storage_bytes_written);
2996 if(enable_file_charts) {
2997 send_BEGIN(type, "files", usec);
2998 for (w = root; w; w = w->next) {
2999 if (unlikely(w->exposed))
3000 send_SET(w->name, w->openfiles);
3004 send_BEGIN(type, "sockets", usec);
3005 for (w = root; w; w = w->next) {
3006 if (unlikely(w->exposed))
3007 send_SET(w->name, w->opensockets);
3011 send_BEGIN(type, "pipes", usec);
3012 for (w = root; w; w = w->next) {
3013 if (unlikely(w->exposed))
3014 send_SET(w->name, w->openpipes);
3021 // ----------------------------------------------------------------------------
3022 // generate the charts
3024 static void send_charts_updates_to_netdata(struct target *root, const char *type, const char *title)
3027 int newly_added = 0;
3029 for(w = root ; w ; w = w->next) {
3030 if (w->target) continue;
3032 if (!w->exposed && w->processes) {
3035 if (debug || w->debug) fprintf(stderr, "apps.plugin: %s just added - regenerating charts.\n", w->name);
3039 // nothing more to show
3040 if(!newly_added && show_guest_time == show_guest_time_old) return;
3042 // we have something new to show
3043 // update the charts
3044 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);
3045 for (w = root; w ; w = w->next) {
3046 if(unlikely(w->exposed))
3047 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu %s\n", w->name, hz * RATES_DETAIL / 100, w->hidden ? "hidden" : "");
3050 fprintf(stdout, "CHART %s.mem '' '%s Real Memory (w/o shared)' 'MB' mem %s.mem stacked 20003 %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.vmem '' '%s Virtual Memory Size' 'MB' mem %s.vmem stacked 20004 %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 %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
3062 fprintf(stdout, "CHART %s.threads '' '%s Threads' 'threads' processes %s.threads stacked 20005 %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.processes '' '%s Processes' 'processes' processes %s.processes stacked 20004 %d\n", type, title, type, update_every);
3069 for (w = root; w ; w = w->next) {
3070 if(unlikely(w->exposed))
3071 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3074 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);
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 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);
3081 for (w = root; w ; w = w->next) {
3082 if(unlikely(w->exposed))
3083 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3086 if(show_guest_time) {
3087 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);
3088 for (w = root; w; w = w->next) {
3089 if(unlikely(w->exposed))
3090 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3094 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);
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);
3100 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);
3101 for (w = root; w ; w = w->next) {
3102 if(unlikely(w->exposed))
3103 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3107 fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'blocks/s' disk %s.preads stacked 20002 %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, RATES_DETAIL);
3113 fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'blocks/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
3114 for (w = root; w ; w = w->next) {
3115 if(unlikely(w->exposed))
3116 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3119 fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'kilobytes/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
3120 for (w = root; w ; w = w->next) {
3121 if(unlikely(w->exposed))
3122 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3125 fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'kilobytes/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
3126 for (w = root; w ; w = w->next) {
3127 if(unlikely(w->exposed))
3128 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3131 fprintf(stdout, "CHART %s.lreads '' '%s Disk Logical Reads' 'kilobytes/s' disk %s.lreads stacked 20042 %d\n", type, title, type, update_every);
3132 for (w = root; w ; w = w->next) {
3133 if(unlikely(w->exposed))
3134 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3137 fprintf(stdout, "CHART %s.lwrites '' '%s I/O Logical Writes' 'kilobytes/s' disk %s.lwrites stacked 20042 %d\n", type, title, type, update_every);
3138 for (w = root; w ; w = w->next) {
3139 if(unlikely(w->exposed))
3140 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3144 if(enable_file_charts) {
3145 fprintf(stdout, "CHART %s.files '' '%s Open Files' 'open files' disk %s.files stacked 20050 %d\n", type,
3146 title, type, update_every);
3147 for (w = root; w; w = w->next) {
3148 if (unlikely(w->exposed))
3149 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3152 fprintf(stdout, "CHART %s.sockets '' '%s Open Sockets' 'open sockets' net %s.sockets stacked 20051 %d\n",
3153 type, title, type, update_every);
3154 for (w = root; w; w = w->next) {
3155 if (unlikely(w->exposed))
3156 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3159 fprintf(stdout, "CHART %s.pipes '' '%s Pipes' 'open pipes' processes %s.pipes stacked 20053 %d\n", type,
3160 title, type, update_every);
3161 for (w = root; w; w = w->next) {
3162 if (unlikely(w->exposed))
3163 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3169 // ----------------------------------------------------------------------------
3170 // parse command line arguments
3172 int check_proc_1_io() {
3175 procfile *ff = procfile_open("/proc/1/io", NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
3176 if(!ff) goto cleanup;
3178 ff = procfile_readall(ff);
3179 if(!ff) goto cleanup;
3188 static void parse_args(int argc, char **argv)
3193 for(i = 1; i < argc; i++) {
3195 int n = (int)str2l(argv[i]);
3202 if(strcmp("version", argv[i]) == 0 || strcmp("-v", argv[i]) == 0 || strcmp("-V", argv[i]) == 0) {
3203 printf("apps.plugin %s\n", VERSION);
3207 if(strcmp("test-permissions", argv[i]) == 0 || strcmp("-t", argv[i]) == 0) {
3208 if(!check_proc_1_io()) {
3209 perror("Tried to read /proc/1/io and it failed");
3216 if(strcmp("debug", argv[i]) == 0) {
3218 // debug_flags = 0xffffffff;
3222 if(strcmp("no-childs", argv[i]) == 0 || strcmp("without-childs", argv[i]) == 0) {
3223 include_exited_childs = 0;
3227 if(strcmp("with-childs", argv[i]) == 0) {
3228 include_exited_childs = 1;
3232 if(strcmp("with-guest", argv[i]) == 0) {
3233 enable_guest_charts = 1;
3237 if(strcmp("no-guest", argv[i]) == 0 || strcmp("without-guest", argv[i]) == 0) {
3238 enable_guest_charts = 0;
3242 if(strcmp("with-files", argv[i]) == 0) {
3243 enable_file_charts = 1;
3247 if(strcmp("no-files", argv[i]) == 0 || strcmp("without-files", argv[i]) == 0) {
3248 enable_file_charts = 0;
3252 if(strcmp("no-users", argv[i]) == 0 || strcmp("without-users", argv[i]) == 0) {
3253 enable_users_charts = 0;
3257 if(strcmp("no-groups", argv[i]) == 0 || strcmp("without-groups", argv[i]) == 0) {
3258 enable_groups_charts = 0;
3262 if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0) {
3265 " netdata apps.plugin %s\n"
3266 " Copyright (C) 2016-2017 Costa Tsaousis <costa@tsaousis.gr>\n"
3267 " Released under GNU General Public License v3 or later.\n"
3268 " All rights reserved.\n"
3270 " This program is a data collector plugin for netdata.\n"
3272 " Available command line options:\n"
3274 " SECONDS set the data collection frequency\n"
3276 " debug enable debugging (lot of output)\n"
3279 " without-childs enable / disable aggregating exited\n"
3280 " children resources into parents\n"
3281 " (default is enabled)\n"
3284 " without-guest enable / disable reporting guest charts\n"
3285 " (default is disabled)\n"
3288 " without-files enable / disable reporting files, sockets, pipes\n"
3289 " (default is enabled)\n"
3291 " NAME read apps_NAME.conf instead of\n"
3292 " apps_groups.conf\n"
3293 " (default NAME=groups)\n"
3295 " version or -v or -V print program version and exit\n"
3307 error("Cannot understand option %s", argv[i]);
3311 if(freq > 0) update_every = freq;
3312 if(!name) name = "groups";
3314 if(read_apps_groups_conf(name)) {
3315 error("Cannot read process groups '%s/apps_%s.conf'. There are no internal defaults. Failing.", config_dir, name);
3320 static int am_i_running_as_root() {
3321 uid_t uid = getuid(), euid = geteuid();
3323 if(uid == 0 || euid == 0) {
3324 if(debug) info("I am running with escalated privileges, uid = %u, euid = %u.", uid, euid);
3328 if(debug) info("I am not running with escalated privileges, uid = %u, euid = %u.", uid, euid);
3332 #ifdef HAVE_CAPABILITY
3333 static int check_capabilities() {
3334 cap_t caps = cap_get_proc();
3336 error("Cannot get current capabilities.");
3340 info("Received my capabilities from the system.");
3344 cap_flag_value_t cfv = CAP_CLEAR;
3345 if(cap_get_flag(caps, CAP_DAC_READ_SEARCH, CAP_EFFECTIVE, &cfv) == -1) {
3346 error("Cannot find if CAP_DAC_READ_SEARCH is effective.");
3350 if(cfv != CAP_SET) {
3351 error("apps.plugin should run with CAP_DAC_READ_SEARCH.");
3355 info("apps.plugin runs with CAP_DAC_READ_SEARCH.");
3359 if(cap_get_flag(caps, CAP_SYS_PTRACE, CAP_EFFECTIVE, &cfv) == -1) {
3360 error("Cannot find if CAP_SYS_PTRACE is effective.");
3364 if(cfv != CAP_SET) {
3365 error("apps.plugin should run with CAP_SYS_PTRACE.");
3369 info("apps.plugin runs with CAP_SYS_PTRACE.");
3377 static int check_capabilities() {
3382 int main(int argc, char **argv) {
3383 // debug_flags = D_PROCFILE;
3385 // set the name for logging
3386 program_name = "apps.plugin";
3388 // disable syslog for apps.plugin
3389 error_log_syslog = 0;
3391 // set errors flood protection to 100 logs per hour
3392 error_log_errors_per_period = 100;
3393 error_log_throttle_period = 3600;
3395 netdata_configured_host_prefix = getenv("NETDATA_HOST_PREFIX");
3396 if(netdata_configured_host_prefix == NULL) {
3397 // info("NETDATA_HOST_PREFIX is not passed from netdata");
3398 netdata_configured_host_prefix = "";
3400 // else info("Found NETDATA_HOST_PREFIX='%s'", netdata_configured_host_prefix);
3402 config_dir = getenv("NETDATA_CONFIG_DIR");
3403 if(config_dir == NULL) {
3404 // info("NETDATA_CONFIG_DIR is not passed from netdata");
3405 config_dir = CONFIG_DIR;
3407 // else info("Found NETDATA_CONFIG_DIR='%s'", config_dir);
3409 #ifdef NETDATA_INTERNAL_CHECKS
3410 if(debug_flags != 0) {
3411 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
3412 if(setrlimit(RLIMIT_CORE, &rl) != 0)
3413 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
3414 #ifdef HAVE_SYS_PRCTL_H
3415 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
3418 #endif /* NETDATA_INTERNAL_CHECKS */
3420 procfile_adaptive_initial_allocation = 1;
3422 time_t started_t = now_monotonic_sec();
3424 get_system_pid_max();
3427 parse_args(argc, argv);
3429 if(!check_capabilities() && !am_i_running_as_root() && !check_proc_1_io()) {
3430 uid_t uid = getuid(), euid = geteuid();
3431 #ifdef HAVE_CAPABILITY
3432 error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
3433 "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
3434 "To enable capabilities run: sudo setcap cap_dac_read_search,cap_sys_ptrace+ep %s; "
3435 "To enable setuid to root run: sudo chown root %s; sudo chmod 4755 %s; "
3436 , uid, euid, argv[0], argv[0], argv[0]
3439 error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
3440 "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
3441 "Your system does not support capabilities. "
3442 "To enable setuid to root run: sudo chown root %s; sudo chmod 4755 %s; "
3443 , uid, euid, argv[0], argv[0]
3448 info("started on pid %d", getpid());
3450 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
3451 all_pids_sortlist = callocz(sizeof(pid_t), (size_t)pid_max);
3454 all_pids = callocz(sizeof(struct pid_stat *), (size_t) pid_max);
3456 usec_t step = update_every * USEC_PER_SEC;
3457 global_iterations_counter = 1;
3459 heartbeat_init(&hb);
3460 for(;1; global_iterations_counter++) {
3462 #ifdef NETDATA_PROFILING
3463 #warning "compiling for profiling"
3464 static int profiling_count=0;
3466 if(unlikely(profiling_count > 1000)) exit(0);
3468 heartbeat_next(&hb, step);
3471 if(!collect_data_for_all_processes()) {
3472 error("Cannot collect /proc data for running processes. Disabling apps.plugin...");
3473 printf("DISABLE\n");
3477 calculate_netdata_statistics();
3478 normalize_utilization(apps_groups_root_target);
3480 usec_t dt = send_resource_usage_to_netdata();
3482 // this is smart enough to show only newly added apps, when needed
3483 send_charts_updates_to_netdata(apps_groups_root_target, "apps", "Apps");
3485 if(likely(enable_users_charts))
3486 send_charts_updates_to_netdata(users_root_target, "users", "Users");
3488 if(likely(enable_groups_charts))
3489 send_charts_updates_to_netdata(groups_root_target, "groups", "User Groups");
3491 send_collected_data_to_netdata(apps_groups_root_target, "apps", dt);
3493 if(likely(enable_users_charts))
3494 send_collected_data_to_netdata(users_root_target, "users", dt);
3496 if(likely(enable_groups_charts))
3497 send_collected_data_to_netdata(groups_root_target, "groups", dt);
3501 show_guest_time_old = show_guest_time;
3504 fprintf(stderr, "apps.plugin: done Loop No %zu\n", global_iterations_counter);
3506 // restart check (14400 seconds)
3507 if(now_monotonic_sec() - started_t > 14400) exit(0);