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));
1086 p->statm_resident = 0;
1088 // p->statm_text = 0;
1089 // p->statm_lib = 0;
1090 // p->statm_data = 0;
1091 // p->statm_dirty = 0;
1096 static inline int read_proc_pid_io(struct pid_stat *p, void *ptr) {
1099 struct kinfo_proc *proc_info = (struct kinfo_proc *)ptr;
1101 static procfile *ff = NULL;
1103 if(unlikely(!p->io_filename)) {
1104 char filename[FILENAME_MAX + 1];
1105 snprintfz(filename, FILENAME_MAX, "%s/proc/%d/io", netdata_configured_host_prefix, p->pid);
1106 p->io_filename = strdupz(filename);
1110 ff = procfile_reopen(ff, p->io_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
1111 if(unlikely(!ff)) goto cleanup;
1113 ff = procfile_readall(ff);
1114 if(unlikely(!ff)) goto cleanup;
1119 p->last_io_collected_usec = p->io_collected_usec;
1120 p->io_collected_usec = now_monotonic_usec();
1123 pid_incremental_rate(io, p->io_storage_bytes_read, proc_info->ki_rusage.ru_inblock);
1124 pid_incremental_rate(io, p->io_storage_bytes_written, proc_info->ki_rusage.ru_oublock);
1126 pid_incremental_rate(io, p->io_logical_bytes_read, str2kernel_uint_t(procfile_lineword(ff, 0, 1)));
1127 pid_incremental_rate(io, p->io_logical_bytes_written, str2kernel_uint_t(procfile_lineword(ff, 1, 1)));
1128 // pid_incremental_rate(io, p->io_read_calls, str2kernel_uint_t(procfile_lineword(ff, 2, 1)));
1129 // pid_incremental_rate(io, p->io_write_calls, str2kernel_uint_t(procfile_lineword(ff, 3, 1)));
1130 pid_incremental_rate(io, p->io_storage_bytes_read, str2kernel_uint_t(procfile_lineword(ff, 4, 1)));
1131 pid_incremental_rate(io, p->io_storage_bytes_written, str2kernel_uint_t(procfile_lineword(ff, 5, 1)));
1132 // pid_incremental_rate(io, p->io_cancelled_write_bytes, str2kernel_uint_t(procfile_lineword(ff, 6, 1)));
1135 if(unlikely(global_iterations_counter == 1)) {
1136 p->io_logical_bytes_read = 0;
1137 p->io_logical_bytes_written = 0;
1138 // p->io_read_calls = 0;
1139 // p->io_write_calls = 0;
1140 p->io_storage_bytes_read = 0;
1141 p->io_storage_bytes_written = 0;
1142 // p->io_cancelled_write_bytes = 0;
1149 p->io_logical_bytes_read = 0;
1150 p->io_logical_bytes_written = 0;
1151 // p->io_read_calls = 0;
1152 // p->io_write_calls = 0;
1153 p->io_storage_bytes_read = 0;
1154 p->io_storage_bytes_written = 0;
1155 // p->io_cancelled_write_bytes = 0;
1160 static inline int read_proc_stat() {
1162 long cp_time[CPUSTATES];
1163 static kernel_uint_t utime_raw = 0, stime_raw = 0, ntime_raw = 0;
1165 if (unlikely(CPUSTATES != 5)) {
1166 error("FREEBSD: There are %d CPU states (5 was expected)", CPUSTATES);
1169 if (unlikely(GETSYSCTL_BY_NAME("kern.cp_time", cp_time))) goto cleanup;
1171 static char filename[FILENAME_MAX + 1] = "";
1172 static procfile *ff = NULL;
1173 static kernel_uint_t utime_raw = 0, stime_raw = 0, gtime_raw = 0, gntime_raw = 0, ntime_raw = 0;
1175 static usec_t collected_usec = 0, last_collected_usec = 0;
1179 snprintfz(filename, FILENAME_MAX, "%s/proc/stat", netdata_configured_host_prefix);
1180 ff = procfile_open(filename, " \t:", PROCFILE_FLAG_DEFAULT);
1181 if(unlikely(!ff)) goto cleanup;
1184 ff = procfile_readall(ff);
1185 if(unlikely(!ff)) goto cleanup;
1188 last_collected_usec = collected_usec;
1189 collected_usec = now_monotonic_usec();
1193 // temporary - it is added global_ntime;
1194 kernel_uint_t global_ntime = 0;
1197 incremental_rate(global_utime, utime_raw, cp_time[0], collected_usec, last_collected_usec);
1198 incremental_rate(global_ntime, ntime_raw, cp_time[1], collected_usec, last_collected_usec);
1199 incremental_rate(global_stime, stime_raw, cp_time[2], collected_usec, last_collected_usec);
1201 incremental_rate(global_utime, utime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 1)), collected_usec, last_collected_usec);
1202 incremental_rate(global_ntime, ntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 2)), collected_usec, last_collected_usec);
1203 incremental_rate(global_stime, stime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 3)), collected_usec, last_collected_usec);
1204 incremental_rate(global_gtime, gtime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 10)), collected_usec, last_collected_usec);
1207 global_utime += global_ntime;
1210 if(enable_guest_charts) {
1211 enable_guest_charts = 0;
1212 info("Guest charts aren't supported by FreeBSD");
1215 if(enable_guest_charts) {
1216 // temporary - it is added global_ntime;
1217 kernel_uint_t global_gntime = 0;
1219 // guest nice time, on guest time
1220 incremental_rate(global_gntime, gntime_raw, str2kernel_uint_t(procfile_lineword(ff, 0, 11)), collected_usec, last_collected_usec);
1222 global_gtime += global_gntime;
1224 // remove guest time from user time
1225 global_utime -= (global_utime > global_gtime) ? global_gtime : global_utime;
1229 if(unlikely(global_iterations_counter == 1)) {
1245 // ----------------------------------------------------------------------------
1247 int file_descriptor_compare(void* a, void* b) {
1248 #ifdef NETDATA_INTERNAL_CHECKS
1249 if(((struct file_descriptor *)a)->magic != 0x0BADCAFE || ((struct file_descriptor *)b)->magic != 0x0BADCAFE)
1250 error("Corrupted index data detected. Please report this.");
1251 #endif /* NETDATA_INTERNAL_CHECKS */
1253 if(((struct file_descriptor *)a)->hash < ((struct file_descriptor *)b)->hash)
1256 else if(((struct file_descriptor *)a)->hash > ((struct file_descriptor *)b)->hash)
1260 return strcmp(((struct file_descriptor *)a)->name, ((struct file_descriptor *)b)->name);
1263 int file_descriptor_iterator(avl *a) { if(a) {}; return 0; }
1265 avl_tree all_files_index = {
1267 file_descriptor_compare
1270 static struct file_descriptor *file_descriptor_find(const char *name, uint32_t hash) {
1271 struct file_descriptor tmp;
1272 tmp.hash = (hash)?hash:simple_hash(name);
1276 #ifdef NETDATA_INTERNAL_CHECKS
1277 tmp.magic = 0x0BADCAFE;
1278 #endif /* NETDATA_INTERNAL_CHECKS */
1280 return (struct file_descriptor *)avl_search(&all_files_index, (avl *) &tmp);
1283 #define file_descriptor_add(fd) avl_insert(&all_files_index, (avl *)(fd))
1284 #define file_descriptor_remove(fd) avl_remove(&all_files_index, (avl *)(fd))
1286 // ----------------------------------------------------------------------------
1288 static inline void file_descriptor_not_used(int id)
1290 if(id > 0 && id < all_files_size) {
1292 #ifdef NETDATA_INTERNAL_CHECKS
1293 if(all_files[id].magic != 0x0BADCAFE) {
1294 error("Ignoring request to remove empty file id %d.", id);
1297 #endif /* NETDATA_INTERNAL_CHECKS */
1300 fprintf(stderr, "apps.plugin: decreasing slot %d (count = %d).\n", id, all_files[id].count);
1302 if(all_files[id].count > 0) {
1303 all_files[id].count--;
1305 if(!all_files[id].count) {
1307 fprintf(stderr, "apps.plugin: >> slot %d is empty.\n", id);
1309 if(unlikely(file_descriptor_remove(&all_files[id]) != (void *)&all_files[id]))
1310 error("INTERNAL ERROR: removal of unused fd from index, removed a different fd");
1312 #ifdef NETDATA_INTERNAL_CHECKS
1313 all_files[id].magic = 0x00000000;
1314 #endif /* NETDATA_INTERNAL_CHECKS */
1319 error("Request to decrease counter of fd %d (%s), while the use counter is 0", id, all_files[id].name);
1321 else error("Request to decrease counter of fd %d, which is outside the array size (1 to %d)", id, all_files_size);
1324 static inline void all_files_grow() {
1325 void *old = all_files;
1328 // there is no empty slot
1330 fprintf(stderr, "apps.plugin: extending fd array to %d entries\n", all_files_size + FILE_DESCRIPTORS_INCREASE_STEP);
1332 all_files = reallocz(all_files, (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP) * sizeof(struct file_descriptor));
1334 // if the address changed, we have to rebuild the index
1335 // since all pointers are now invalid
1337 if(unlikely(old && old != (void *)all_files)) {
1339 fprintf(stderr, "apps.plugin: >> re-indexing.\n");
1341 all_files_index.root = NULL;
1342 for(i = 0; i < all_files_size; i++) {
1343 if(!all_files[i].count) continue;
1344 if(unlikely(file_descriptor_add(&all_files[i]) != (void *)&all_files[i]))
1345 error("INTERNAL ERROR: duplicate indexing of fd during realloc.");
1349 fprintf(stderr, "apps.plugin: >> re-indexing done.\n");
1352 // initialize the newly added entries
1354 for(i = all_files_size; i < (all_files_size + FILE_DESCRIPTORS_INCREASE_STEP); i++) {
1355 all_files[i].count = 0;
1356 all_files[i].name = NULL;
1357 #ifdef NETDATA_INTERNAL_CHECKS
1358 all_files[i].magic = 0x00000000;
1359 #endif /* NETDATA_INTERNAL_CHECKS */
1360 all_files[i].pos = i;
1363 if(unlikely(!all_files_size)) all_files_len = 1;
1364 all_files_size += FILE_DESCRIPTORS_INCREASE_STEP;
1367 static inline int file_descriptor_set_on_empty_slot(const char *name, uint32_t hash, FD_FILETYPE type) {
1368 // check we have enough memory to add it
1369 if(!all_files || all_files_len == all_files_size)
1373 fprintf(stderr, "apps.plugin: >> searching for empty slot.\n");
1375 // search for an empty slot
1377 static int last_pos = 0;
1379 for(i = 0, c = last_pos ; i < all_files_size ; i++, c++) {
1380 if(c >= all_files_size) c = 0;
1381 if(c == 0) continue;
1383 if(!all_files[c].count) {
1385 fprintf(stderr, "apps.plugin: >> Examining slot %d.\n", c);
1387 #ifdef NETDATA_INTERNAL_CHECKS
1388 if(all_files[c].magic == 0x0BADCAFE && all_files[c].name && file_descriptor_find(all_files[c].name, all_files[c].hash))
1389 error("fd on position %d is not cleared properly. It still has %s in it.\n", c, all_files[c].name);
1390 #endif /* NETDATA_INTERNAL_CHECKS */
1393 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);
1395 freez((void *)all_files[c].name);
1396 all_files[c].name = NULL;
1404 if(i == all_files_size) {
1405 fatal("We should find an empty slot, but there isn't any");
1408 // else we have an empty slot in 'c'
1411 fprintf(stderr, "apps.plugin: >> updating slot %d.\n", c);
1413 all_files[c].name = strdupz(name);
1414 all_files[c].hash = hash;
1415 all_files[c].type = type;
1416 all_files[c].pos = c;
1417 all_files[c].count = 1;
1418 #ifdef NETDATA_INTERNAL_CHECKS
1419 all_files[c].magic = 0x0BADCAFE;
1420 #endif /* NETDATA_INTERNAL_CHECKS */
1421 if(unlikely(file_descriptor_add(&all_files[c]) != (void *)&all_files[c]))
1422 error("INTERNAL ERROR: duplicate indexing of fd.");
1425 fprintf(stderr, "apps.plugin: using fd position %d (name: %s)\n", c, all_files[c].name);
1430 static inline int file_descriptor_find_or_add(const char *name)
1432 uint32_t hash = simple_hash(name);
1435 fprintf(stderr, "apps.plugin: adding or finding name '%s' with hash %u\n", name, hash);
1437 struct file_descriptor *fd = file_descriptor_find(name, hash);
1441 fprintf(stderr, "apps.plugin: >> found on slot %d\n", fd->pos);
1449 if(likely(name[0] == '/')) type = FILETYPE_FILE;
1450 else if(likely(strncmp(name, "pipe:", 5) == 0)) type = FILETYPE_PIPE;
1451 else if(likely(strncmp(name, "socket:", 7) == 0)) type = FILETYPE_SOCKET;
1452 else if(likely(strncmp(name, "anon_inode:", 11) == 0)) {
1453 const char *t = &name[11];
1455 if(strcmp(t, "inotify") == 0) type = FILETYPE_INOTIFY;
1456 else if(strcmp(t, "[eventfd]") == 0) type = FILETYPE_EVENTFD;
1457 else if(strcmp(t, "[eventpoll]") == 0) type = FILETYPE_EVENTPOLL;
1458 else if(strcmp(t, "[timerfd]") == 0) type = FILETYPE_TIMERFD;
1459 else if(strcmp(t, "[signalfd]") == 0) type = FILETYPE_SIGNALFD;
1462 fprintf(stderr, "apps.plugin: FIXME: unknown anonymous inode: %s\n", name);
1464 type = FILETYPE_OTHER;
1467 else if(likely(strcmp(name, "inotify") == 0)) type = FILETYPE_INOTIFY;
1470 fprintf(stderr, "apps.plugin: FIXME: cannot understand linkname: %s\n", name);
1472 type = FILETYPE_OTHER;
1475 return file_descriptor_set_on_empty_slot(name, hash, type);
1478 static inline void make_all_pid_fds_negative(struct pid_stat *p) {
1479 int *fd = p->fds, *end = &p->fds[p->fds_size];
1486 static inline void cleanup_negative_pid_fds(struct pid_stat *p) {
1487 int *fd = p->fds, *fdend = &p->fds[p->fds_size];
1490 if(unlikely(*fd < 0)) {
1491 file_descriptor_not_used(-(*fd));
1499 static inline void zero_pid_fds(struct pid_stat *p, int first, int size) {
1500 int *fd = &p->fds[first], *end = &p->fds[first + size];
1501 while(fd < end) *fd++ = 0;
1504 static inline int read_pid_file_descriptors(struct pid_stat *p, void *ptr) {
1509 struct kinfo_file *fds;
1510 static char *fdsbuf;
1511 char *bfdsbuf, *efdsbuf;
1512 char fdsname[FILENAME_MAX + 1];
1514 // we make all pid fds negative, so that
1515 // we can detect unused file descriptors
1516 // at the end, to free them
1517 make_all_pid_fds_negative(p);
1521 mib[2] = KERN_PROC_FILEDESC;
1524 if (unlikely(sysctl(mib, 4, NULL, &size, NULL, 0))) {
1525 error("sysctl error: Can't get file descriptors data size for pid %d", p->pid);
1528 if (likely(size > 0))
1529 fdsbuf = reallocz(fdsbuf, size);
1530 if (unlikely(sysctl(mib, 4, fdsbuf, &size, NULL, 0))) {
1531 error("sysctl error: Can't get file descriptors data for pid %d", p->pid);
1536 efdsbuf = fdsbuf + size;
1537 while (bfdsbuf < efdsbuf) {
1538 fds = (struct kinfo_file *)(uintptr_t)bfdsbuf;
1539 if (unlikely(fds->kf_structsize == 0))
1542 // do not process file descriptors for current working directory, root directory,
1543 // jail directory, ktrace vnode, text vnode and controlling terminal
1544 if (unlikely(fds->kf_fd < 0)) {
1545 bfdsbuf += fds->kf_structsize;
1549 // get file descriptors array index
1550 int fdid = fds->kf_fd;
1552 // check if the fds array is small
1553 if (unlikely(fdid >= p->fds_size)) {
1554 // it is small, extend it
1556 if (unlikely(debug))
1557 fprintf(stderr, "apps.plugin: extending fd memory slots for %s from %d to %d\n", p->comm, p->fds_size, fdid + MAX_SPARE_FDS);
1559 p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(int));
1561 // and initialize it
1562 zero_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
1563 p->fds_size = fdid + MAX_SPARE_FDS;
1566 if (unlikely(p->fds[fdid] == 0)) {
1567 // we don't know this fd, get it
1569 switch (fds->kf_type) {
1572 if (unlikely(!fds->kf_path[0])) {
1573 sprintf(fdsname, "other: inode: %lu", fds->kf_un.kf_file.kf_file_fileid);
1576 sprintf(fdsname, "%s", fds->kf_path);
1578 case KF_TYPE_SOCKET:
1579 switch (fds->kf_sock_domain) {
1582 if (fds->kf_sock_protocol == IPPROTO_TCP)
1583 sprintf(fdsname, "socket: %d %lx", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sock_inpcb);
1585 sprintf(fdsname, "socket: %d %lx", fds->kf_sock_protocol, fds->kf_un.kf_sock.kf_sock_pcb);
1588 /* print address of pcb and connected pcb */
1589 sprintf(fdsname, "socket: %lx %lx", fds->kf_un.kf_sock.kf_sock_pcb, fds->kf_un.kf_sock.kf_sock_unpconn);
1592 /* print protocol number and socket address */
1593 sprintf(fdsname, "socket: other: %d %s %s", fds->kf_sock_protocol, fds->kf_sa_local.__ss_pad1, fds->kf_sa_local.__ss_pad2);
1597 sprintf(fdsname, "pipe: %lu %lu", fds->kf_un.kf_pipe.kf_pipe_addr, fds->kf_un.kf_pipe.kf_pipe_peer);
1600 sprintf(fdsname, "other: pts: %u", fds->kf_un.kf_pts.kf_pts_dev);
1603 sprintf(fdsname, "other: shm: %s size: %lu", fds->kf_path, fds->kf_un.kf_file.kf_file_size);
1606 sprintf(fdsname, "other: sem: %u", fds->kf_un.kf_sem.kf_sem_value);
1609 sprintf(fdsname, "other: pid: %d fd: %d", fds->kf_un.kf_proc.kf_pid, fds->kf_fd);
1612 // if another process already has this, we will get
1614 p->fds[fdid] = file_descriptor_find_or_add(fdsname);
1617 // else make it positive again, we need it
1618 // of course, the actual file may have changed, but we don't care so much
1619 // FIXME: we could compare the inode as returned by readdir dirent structure
1622 p->fds[fdid] = -p->fds[fdid];
1624 bfdsbuf += fds->kf_structsize;
1627 if(unlikely(!p->fds_dirname)) {
1628 char dirname[FILENAME_MAX+1];
1629 snprintfz(dirname, FILENAME_MAX, "%s/proc/%d/fd", netdata_configured_host_prefix, p->pid);
1630 p->fds_dirname = strdupz(dirname);
1633 DIR *fds = opendir(p->fds_dirname);
1634 if(unlikely(!fds)) return 0;
1637 char fdname[FILENAME_MAX + 1];
1638 char linkname[FILENAME_MAX + 1];
1640 // we make all pid fds negative, so that
1641 // we can detect unused file descriptors
1642 // at the end, to free them
1643 make_all_pid_fds_negative(p);
1645 while((de = readdir(fds))) {
1646 // we need only files with numeric names
1648 if(unlikely(de->d_name[0] < '0' || de->d_name[0] > '9'))
1652 int fdid = (int) str2l(de->d_name);
1653 if(unlikely(fdid < 0)) continue;
1655 // check if the fds array is small
1656 if(unlikely(fdid >= p->fds_size)) {
1657 // it is small, extend it
1661 , "apps.plugin: extending fd memory slots for %s from %d to %d\n"
1664 , fdid + MAX_SPARE_FDS
1667 p->fds = reallocz(p->fds, (fdid + MAX_SPARE_FDS) * sizeof(int));
1669 // and initialize it
1670 zero_pid_fds(p, p->fds_size, (fdid + MAX_SPARE_FDS) - p->fds_size);
1671 p->fds_size = fdid + MAX_SPARE_FDS;
1674 if(unlikely(p->fds[fdid] == 0)) {
1675 // we don't know this fd, get it
1677 sprintf(fdname, "%s/proc/%d/fd/%s", netdata_configured_host_prefix, p->pid, de->d_name);
1678 ssize_t l = readlink(fdname, linkname, FILENAME_MAX);
1679 if(unlikely(l == -1)) {
1680 if(debug || (p->target && p->target->debug)) {
1681 if(debug || (p->target && p->target->debug))
1682 error("Cannot read link %s", fdname);
1691 // if another process already has this, we will get
1693 p->fds[fdid] = file_descriptor_find_or_add(linkname);
1696 // else make it positive again, we need it
1697 // of course, the actual file may have changed, but we don't care so much
1698 // FIXME: we could compare the inode as returned by readdir dirent structure
1699 // UPDATE: no we cannot use inodes - under /proc inodes don't change when the link is changed
1702 p->fds[fdid] = -p->fds[fdid];
1707 cleanup_negative_pid_fds(p);
1712 // ----------------------------------------------------------------------------
1714 static inline int print_process_and_parents(struct pid_stat *p, usec_t time) {
1715 char *prefix = "\\_ ";
1719 indent = print_process_and_parents(p->parent, p->stat_collected_usec);
1723 char buffer[indent + 1];
1726 for(i = 0; i < indent ;i++) buffer[i] = ' ';
1729 fprintf(stderr, " %s %s%s (%d %s %llu"
1734 , p->updated?"running":"exited"
1735 , p->stat_collected_usec - time
1738 if(p->utime) fprintf(stderr, " utime=" KERNEL_UINT_FORMAT, p->utime);
1739 if(p->stime) fprintf(stderr, " stime=" KERNEL_UINT_FORMAT, p->stime);
1740 if(p->gtime) fprintf(stderr, " gtime=" KERNEL_UINT_FORMAT, p->gtime);
1741 if(p->cutime) fprintf(stderr, " cutime=" KERNEL_UINT_FORMAT, p->cutime);
1742 if(p->cstime) fprintf(stderr, " cstime=" KERNEL_UINT_FORMAT, p->cstime);
1743 if(p->cgtime) fprintf(stderr, " cgtime=" KERNEL_UINT_FORMAT, p->cgtime);
1744 if(p->minflt) fprintf(stderr, " minflt=" KERNEL_UINT_FORMAT, p->minflt);
1745 if(p->cminflt) fprintf(stderr, " cminflt=" KERNEL_UINT_FORMAT, p->cminflt);
1746 if(p->majflt) fprintf(stderr, " majflt=" KERNEL_UINT_FORMAT, p->majflt);
1747 if(p->cmajflt) fprintf(stderr, " cmajflt=" KERNEL_UINT_FORMAT, p->cmajflt);
1748 fprintf(stderr, ")\n");
1753 static inline void print_process_tree(struct pid_stat *p, char *msg) {
1755 fprintf(stderr, "%s: process %s (%d, %s) with parents:\n", msg, p->comm, p->pid, p->updated?"running":"exited");
1756 print_process_and_parents(p, p->stat_collected_usec);
1759 static inline void find_lost_child_debug(struct pid_stat *pe, kernel_uint_t lost, int type) {
1761 struct pid_stat *p = NULL;
1763 for(p = root_of_pids; p ; p = p->next) {
1764 if(p == pe) continue;
1768 if(p->cminflt > lost) {
1769 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);
1775 if(p->cmajflt > lost) {
1776 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);
1782 if(p->cutime > lost) {
1783 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);
1789 if(p->cstime > lost) {
1790 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);
1796 if(p->cgtime > lost) {
1797 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);
1807 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);
1811 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);
1815 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);
1819 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);
1823 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);
1829 static inline kernel_uint_t remove_exited_child_from_parent(kernel_uint_t *field, kernel_uint_t *pfield) {
1830 kernel_uint_t absorbed = 0;
1832 if(*field > *pfield) {
1833 absorbed += *pfield;
1846 static inline void process_exited_processes() {
1849 for(p = root_of_pids; p ; p = p->next) {
1850 if(p->updated || !p->stat_collected_usec)
1853 kernel_uint_t utime = (p->utime_raw + p->cutime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1854 kernel_uint_t stime = (p->stime_raw + p->cstime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1855 kernel_uint_t gtime = (p->gtime_raw + p->cgtime_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1856 kernel_uint_t minflt = (p->minflt_raw + p->cminflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1857 kernel_uint_t majflt = (p->majflt_raw + p->cmajflt_raw) * (USEC_PER_SEC * RATES_DETAIL) / (p->stat_collected_usec - p->last_stat_collected_usec);
1859 if(utime + stime + gtime + minflt + majflt == 0)
1862 if(unlikely(debug)) {
1864 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"
1867 , p->updated?"running":"exited"
1874 print_process_tree(p, "Searching parents");
1877 struct pid_stat *pp;
1878 for(pp = p->parent; pp ; pp = pp->parent) {
1879 if(!pp->updated) continue;
1881 kernel_uint_t absorbed;
1882 absorbed = remove_exited_child_from_parent(&utime, &pp->cutime);
1883 if(unlikely(debug && absorbed))
1884 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);
1886 absorbed = remove_exited_child_from_parent(&stime, &pp->cstime);
1887 if(unlikely(debug && absorbed))
1888 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);
1890 absorbed = remove_exited_child_from_parent(>ime, &pp->cgtime);
1891 if(unlikely(debug && absorbed))
1892 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);
1894 absorbed = remove_exited_child_from_parent(&minflt, &pp->cminflt);
1895 if(unlikely(debug && absorbed))
1896 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);
1898 absorbed = remove_exited_child_from_parent(&majflt, &pp->cmajflt);
1899 if(unlikely(debug && absorbed))
1900 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);
1903 if(unlikely(utime + stime + gtime + minflt + majflt > 0)) {
1904 if(unlikely(debug)) {
1905 if(utime) find_lost_child_debug(p, utime, 3);
1906 if(stime) find_lost_child_debug(p, stime, 4);
1907 if(gtime) find_lost_child_debug(p, gtime, 5);
1908 if(minflt) find_lost_child_debug(p, minflt, 1);
1909 if(majflt) find_lost_child_debug(p, majflt, 2);
1915 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"
1918 , p->updated?"running":"exited"
1926 for(pp = p->parent; pp ; pp = pp->parent) {
1927 if(pp->updated) break;
1931 fprintf(stderr, " > - KEEP - parent for another loop: %s (%d %s)\n"
1934 , pp->updated?"running":"exited"
1938 p->utime_raw = utime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1939 p->stime_raw = stime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1940 p->gtime_raw = gtime * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1941 p->minflt_raw = minflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1942 p->majflt_raw = majflt * (p->stat_collected_usec - p->last_stat_collected_usec) / (USEC_PER_SEC * RATES_DETAIL);
1943 p->cutime_raw = p->cstime_raw = p->cgtime_raw = p->cminflt_raw = p->cmajflt_raw = 0;
1946 fprintf(stderr, "\n");
1948 else if(unlikely(debug)) {
1949 fprintf(stderr, " > totally absorbed - DONE - %s (%d %s)\n"
1952 , p->updated?"running":"exited"
1958 static inline void link_all_processes_to_their_parents(void) {
1959 struct pid_stat *p, *pp;
1961 // link all children to their parents
1962 // and update children count on parents
1963 for(p = root_of_pids; p ; p = p->next) {
1964 // for each process found
1969 if(unlikely(!p->ppid)) {
1974 pp = all_pids[p->ppid];
1977 pp->children_count++;
1979 if(unlikely(debug || (p->target && p->target->debug)))
1980 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);
1984 error("pid %d %s states parent %d, but the later does not exist.", p->pid, p->comm, p->ppid);
1989 // ----------------------------------------------------------------------------
1991 // 1. read all files in /proc
1992 // 2. for each numeric directory:
1993 // i. read /proc/pid/stat
1994 // ii. read /proc/pid/statm
1995 // iii. read /proc/pid/io (requires root access)
1996 // iii. read the entries in directory /proc/pid/fd (requires root access)
1998 // a. find or create a struct file_descriptor
1999 // b. cleanup any old/unused file_descriptors
2001 // after all these, some pids may be linked to targets, while others may not
2003 // in case of errors, only 1 every 1000 errors is printed
2004 // to avoid filling up all disk space
2005 // if debug is enabled, all errors are printed
2008 static int compar_pid(const void *pid1, const void *pid2) {
2010 struct pid_stat *p1 = all_pids[*((pid_t *)pid1)];
2011 struct pid_stat *p2 = all_pids[*((pid_t *)pid2)];
2013 if(p1->sortlist > p2->sortlist)
2020 static inline int collect_data_for_pid(pid_t pid, void *ptr) {
2021 if(unlikely(pid < INIT_PID || pid > pid_max)) {
2022 error("Invalid pid %d read (expected %d to %d). Ignoring process.", pid, INIT_PID, pid_max);
2026 struct pid_stat *p = get_pid_entry(pid);
2027 if(unlikely(!p || p->read)) return 0;
2030 // fprintf(stderr, "Reading process %d (%s), sortlist %d\n", p->pid, p->comm, p->sortlist);
2032 // --------------------------------------------------------------------
2035 if(unlikely(!managed_log(p, PID_LOG_STAT, read_proc_pid_stat(p, ptr))))
2036 // there is no reason to proceed if we cannot get its status
2039 read_proc_pid_ownership(p, ptr);
2041 // check its parent pid
2042 if(unlikely(p->ppid < 0 || p->ppid > pid_max)) {
2043 error("Pid %d (command '%s') states invalid parent pid %d. Using 0.", pid, p->comm, p->ppid);
2047 // --------------------------------------------------------------------
2050 managed_log(p, PID_LOG_IO, read_proc_pid_io(p, ptr));
2052 // --------------------------------------------------------------------
2053 // /proc/<pid>/statm
2055 if(unlikely(!managed_log(p, PID_LOG_STATM, read_proc_pid_statm(p, ptr))))
2056 // there is no reason to proceed if we cannot get its memory status
2059 // --------------------------------------------------------------------
2062 if(enable_file_charts)
2063 managed_log(p, PID_LOG_FDS, read_pid_file_descriptors(p, ptr));
2065 // --------------------------------------------------------------------
2068 if(unlikely(debug && include_exited_childs && all_pids_count && p->ppid && all_pids[p->ppid] && !all_pids[p->ppid]->read))
2069 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);
2071 // mark it as updated
2079 static int collect_data_for_all_processes(void) {
2080 struct pid_stat *p = NULL;
2084 size_t procbase_size;
2085 static struct kinfo_proc *procbase;
2091 mib[2] = KERN_PROC_PROC;
2092 if (unlikely(sysctl(mib, 3, NULL, &procbase_size, NULL, 0))) {
2093 error("sysctl error: Can't get processes data size");
2096 procbase = reallocz(procbase, procbase_size);
2097 if (unlikely(sysctl(mib, 3, procbase, &procbase_size, NULL, 0))) {
2098 error("sysctl error: Can't get processes data");
2101 procnum = procbase_size / sizeof(struct kinfo_proc);
2104 if(all_pids_count) {
2108 for(p = root_of_pids; p ; p = p->next) {
2109 p->read = 0; // mark it as not read, so that collect_data_for_pid() will read it
2112 p->children_count = 0;
2115 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
2116 all_pids_sortlist[slc++] = p->pid;
2120 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
2121 if(unlikely(slc != all_pids_count)) {
2122 error("Internal error: I was thinking I had %zu processes in my arrays, but it seems there are more.", all_pids_count);
2123 all_pids_count = slc;
2126 if(include_exited_childs) {
2127 // Read parents before childs
2128 // This is needed to prevent a situation where
2129 // a child is found running, but until we read
2130 // its parent, it has exited and its parent
2131 // has accumulated its resources.
2133 qsort((void *)all_pids_sortlist, (size_t)all_pids_count, sizeof(pid_t), compar_pid);
2135 // we forward read all running processes
2136 // collect_data_for_pid() is smart enough,
2137 // not to read the same pid twice per iteration
2138 for(slc = 0; slc < all_pids_count; slc++)
2139 collect_data_for_pid(all_pids_sortlist[slc], NULL);
2145 for (i = INIT_PID; i < procnum - INIT_PID; ++i) {
2146 pid_t pid = procbase[i].ki_pid;
2147 collect_data_for_pid(pid, &procbase[i]);
2150 char dirname[FILENAME_MAX + 1];
2152 snprintfz(dirname, FILENAME_MAX, "%s/proc", netdata_configured_host_prefix);
2153 DIR *dir = opendir(dirname);
2156 struct dirent *de = NULL;
2158 while((de = readdir(dir))) {
2159 char *endptr = de->d_name;
2161 if(unlikely(de->d_type != DT_DIR || de->d_name[0] < '0' || de->d_name[0] > '9'))
2164 pid_t pid = (pid_t) strtoul(de->d_name, &endptr, 10);
2166 // make sure we read a valid number
2167 if(unlikely(endptr == de->d_name || *endptr != '\0'))
2170 collect_data_for_pid(pid, NULL);
2178 // we need /proc/stat to normalize the cpu consumption of the exited childs
2181 // build the process tree
2182 link_all_processes_to_their_parents();
2184 // normally this is done
2185 // however we may have processes exited while we collected values
2186 // so let's find the exited ones
2187 // we do this by collecting the ownership of process
2188 // if we manage to get the ownership, the process still runs
2189 process_exited_processes();
2194 // ----------------------------------------------------------------------------
2195 // update statistics on the targets
2197 // 1. link all childs to their parents
2198 // 2. go from bottom to top, marking as merged all childs to their parents
2199 // this step links all parents without a target to the child target, if any
2200 // 3. link all top level processes (the ones not merged) to the default target
2201 // 4. go from top to bottom, linking all childs without a target, to their parent target
2202 // after this step, all processes have a target
2203 // [5. for each killed pid (updated = 0), remove its usage from its target]
2204 // 6. zero all apps_groups_targets
2205 // 7. concentrate all values on the apps_groups_targets
2206 // 8. remove all killed processes
2207 // 9. find the unique file count for each target
2208 // check: update_apps_groups_statistics()
2210 static void cleanup_exited_pids(void) {
2212 struct pid_stat *p = NULL;
2214 for(p = root_of_pids; p ;) {
2215 if(!p->updated && (!p->keep || p->keeploops > 0)) {
2216 if(unlikely(debug && (p->keep || p->keeploops)))
2217 fprintf(stderr, " > CLEANUP cannot keep exited process %d (%s) anymore - removing it.\n", p->pid, p->comm);
2219 for(c = 0; c < p->fds_size; c++)
2221 file_descriptor_not_used(p->fds[c]);
2230 if(unlikely(p->keep)) p->keeploops++;
2237 static void apply_apps_groups_targets_inheritance(void) {
2238 struct pid_stat *p = NULL;
2240 // children that do not have a target
2241 // inherit their target from their parent
2242 int found = 1, loops = 0;
2244 if(unlikely(debug)) loops++;
2246 for(p = root_of_pids; p ; p = p->next) {
2247 // if this process does not have a target
2248 // and it has a parent
2249 // and its parent has a target
2250 // then, set the parent's target to this process
2251 if(unlikely(!p->target && p->parent && p->parent->target)) {
2252 p->target = p->parent->target;
2255 if(debug || (p->target && p->target->debug))
2256 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);
2261 // find all the procs with 0 childs and merge them to their parents
2262 // repeat, until nothing more can be done.
2266 if(unlikely(debug)) loops++;
2269 for(p = root_of_pids; p ; p = p->next) {
2270 if(unlikely(!p->sortlist && !p->children_count))
2271 p->sortlist = sortlist++;
2273 // if this process does not have any children
2274 // and is not already merged
2276 // and its parent has children
2277 // and the target of this process and its parent is the same, or the parent does not have a target
2278 // and its parent is not init
2279 // then, mark them as merged.
2284 && p->parent->children_count
2285 && (p->target == p->parent->target || !p->parent->target)
2286 && p->ppid != INIT_PID
2288 p->parent->children_count--;
2291 // the parent inherits the child's target, if it does not have a target itself
2292 if(unlikely(p->target && !p->parent->target)) {
2293 p->parent->target = p->target;
2295 if(debug || (p->target && p->target->debug))
2296 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);
2304 fprintf(stderr, "apps.plugin: TARGET INHERITANCE: merged %d processes\n", found);
2307 // init goes always to default target
2308 if(all_pids[INIT_PID])
2309 all_pids[INIT_PID]->target = apps_groups_default_target;
2311 // give a default target on all top level processes
2312 if(unlikely(debug)) loops++;
2313 for(p = root_of_pids; p ; p = p->next) {
2314 // if the process is not merged itself
2315 // then is is a top level process
2316 if(unlikely(!p->merged && !p->target))
2317 p->target = apps_groups_default_target;
2319 // make sure all processes have a sortlist
2320 if(unlikely(!p->sortlist))
2321 p->sortlist = sortlist++;
2325 all_pids[1]->sortlist = sortlist++;
2327 // give a target to all merged child processes
2330 if(unlikely(debug)) loops++;
2332 for(p = root_of_pids; p ; p = p->next) {
2333 if(unlikely(!p->target && p->merged && p->parent && p->parent->target)) {
2334 p->target = p->parent->target;
2337 if(debug || (p->target && p->target->debug))
2338 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);
2344 fprintf(stderr, "apps.plugin: apply_apps_groups_targets_inheritance() made %d loops on the process tree\n", loops);
2347 static size_t zero_all_targets(struct target *root) {
2351 for (w = root; w ; w = w->next) {
2369 w->statm_resident = 0;
2371 // w->statm_text = 0;
2372 // w->statm_lib = 0;
2373 // w->statm_data = 0;
2374 // w->statm_dirty = 0;
2376 w->io_logical_bytes_read = 0;
2377 w->io_logical_bytes_written = 0;
2378 // w->io_read_calls = 0;
2379 // w->io_write_calls = 0;
2380 w->io_storage_bytes_read = 0;
2381 w->io_storage_bytes_written = 0;
2382 // w->io_cancelled_write_bytes = 0;
2384 // zero file counters
2386 memset(w->target_fds, 0, sizeof(int) * w->target_fds_size);
2390 w->openinotifies = 0;
2391 w->openeventfds = 0;
2392 w->opentimerfds = 0;
2393 w->opensignalfds = 0;
2394 w->openeventpolls = 0;
2402 static inline void reallocate_target_fds(struct target *w) {
2406 if(unlikely(!w->target_fds || w->target_fds_size < all_files_size)) {
2407 w->target_fds = reallocz(w->target_fds, sizeof(int) * all_files_size);
2408 memset(&w->target_fds[w->target_fds_size], 0, sizeof(int) * (all_files_size - w->target_fds_size));
2409 w->target_fds_size = all_files_size;
2413 static inline void aggregate_fd_on_target(int fd, struct target *w) {
2417 if(unlikely(w->target_fds[fd])) {
2418 // it is already aggregated
2419 // just increase its usage counter
2420 w->target_fds[fd]++;
2424 // increase its usage counter
2425 // so that we will not add it again
2426 w->target_fds[fd]++;
2428 switch(all_files[fd].type) {
2437 case FILETYPE_SOCKET:
2441 case FILETYPE_INOTIFY:
2445 case FILETYPE_EVENTFD:
2449 case FILETYPE_TIMERFD:
2453 case FILETYPE_SIGNALFD:
2457 case FILETYPE_EVENTPOLL:
2458 w->openeventpolls++;
2461 case FILETYPE_OTHER:
2467 static inline void aggregate_pid_fds_on_targets(struct pid_stat *p) {
2469 if(unlikely(!p->updated)) {
2470 // the process is not running
2474 struct target *w = p->target, *u = p->user_target, *g = p->group_target;
2476 reallocate_target_fds(w);
2477 reallocate_target_fds(u);
2478 reallocate_target_fds(g);
2480 int c, size = p->fds_size, *fds = p->fds;
2481 for(c = 0; c < size ;c++) {
2484 if(likely(fd <= 0 || fd >= all_files_size))
2487 aggregate_fd_on_target(fd, w);
2488 aggregate_fd_on_target(fd, u);
2489 aggregate_fd_on_target(fd, g);
2493 static inline void aggregate_pid_on_target(struct target *w, struct pid_stat *p, struct target *o) {
2496 if(unlikely(!p->updated)) {
2497 // the process is not running
2502 error("pid %d %s was left without a target!", p->pid, p->comm);
2506 w->cutime += p->cutime;
2507 w->cstime += p->cstime;
2508 w->cgtime += p->cgtime;
2509 w->cminflt += p->cminflt;
2510 w->cmajflt += p->cmajflt;
2512 w->utime += p->utime;
2513 w->stime += p->stime;
2514 w->gtime += p->gtime;
2515 w->minflt += p->minflt;
2516 w->majflt += p->majflt;
2518 // w->rss += p->rss;
2520 w->statm_size += p->statm_size;
2521 w->statm_resident += p->statm_resident;
2522 w->statm_share += p->statm_share;
2523 // w->statm_text += p->statm_text;
2524 // w->statm_lib += p->statm_lib;
2525 // w->statm_data += p->statm_data;
2526 // w->statm_dirty += p->statm_dirty;
2528 w->io_logical_bytes_read += p->io_logical_bytes_read;
2529 w->io_logical_bytes_written += p->io_logical_bytes_written;
2530 // w->io_read_calls += p->io_read_calls;
2531 // w->io_write_calls += p->io_write_calls;
2532 w->io_storage_bytes_read += p->io_storage_bytes_read;
2533 w->io_storage_bytes_written += p->io_storage_bytes_written;
2534 // w->io_cancelled_write_bytes += p->io_cancelled_write_bytes;
2537 w->num_threads += p->num_threads;
2539 if(unlikely(debug || w->debug))
2540 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);
2543 static void calculate_netdata_statistics(void) {
2545 apply_apps_groups_targets_inheritance();
2547 zero_all_targets(users_root_target);
2548 zero_all_targets(groups_root_target);
2549 apps_groups_targets_count = zero_all_targets(apps_groups_root_target);
2551 // this has to be done, before the cleanup
2552 struct pid_stat *p = NULL;
2553 struct target *w = NULL, *o = NULL;
2555 // concentrate everything on the targets
2556 for(p = root_of_pids; p ; p = p->next) {
2558 // --------------------------------------------------------------------
2559 // apps_groups target
2561 aggregate_pid_on_target(p->target, p, NULL);
2564 // --------------------------------------------------------------------
2568 if(likely(p->user_target && p->user_target->uid == p->uid))
2571 if(unlikely(debug && p->user_target))
2572 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);
2574 w = p->user_target = get_users_target(p->uid);
2577 aggregate_pid_on_target(w, p, o);
2580 // --------------------------------------------------------------------
2581 // user group target
2583 o = p->group_target;
2584 if(likely(p->group_target && p->group_target->gid == p->gid))
2585 w = p->group_target;
2587 if(unlikely(debug && p->group_target))
2588 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);
2590 w = p->group_target = get_groups_target(p->gid);
2593 aggregate_pid_on_target(w, p, o);
2596 // --------------------------------------------------------------------
2597 // aggregate all file descriptors
2599 if(enable_file_charts)
2600 aggregate_pid_fds_on_targets(p);
2603 cleanup_exited_pids();
2606 // ----------------------------------------------------------------------------
2607 // update chart dimensions
2609 int print_calculated_number(char *str, calculated_number value) { (void)str; (void)value; return 0; }
2611 static inline void send_BEGIN(const char *type, const char *id, usec_t usec) {
2612 fprintf(stdout, "BEGIN %s.%s %llu\n", type, id, usec);
2615 static inline void send_SET(const char *name, kernel_uint_t value) {
2616 fprintf(stdout, "SET %s = " KERNEL_UINT_FORMAT "\n", name, value);
2619 static inline void send_END(void) {
2620 fprintf(stdout, "END\n");
2623 static usec_t send_resource_usage_to_netdata() {
2624 static struct timeval last = { 0, 0 };
2625 static struct rusage me_last;
2635 now_monotonic_timeval(&last);
2636 getrusage(RUSAGE_SELF, &me_last);
2638 // the first time, give a zero to allow
2639 // netdata calibrate to the current time
2640 // usec = update_every * USEC_PER_SEC;
2646 now_monotonic_timeval(&now);
2647 getrusage(RUSAGE_SELF, &me);
2649 usec = dt_usec(&now, &last);
2650 cpuuser = me.ru_utime.tv_sec * USEC_PER_SEC + me.ru_utime.tv_usec;
2651 cpusyst = me.ru_stime.tv_sec * USEC_PER_SEC + me.ru_stime.tv_usec;
2653 memmove(&last, &now, sizeof(struct timeval));
2654 memmove(&me_last, &me, sizeof(struct rusage));
2657 static char created_charts = 0;
2658 if(unlikely(!created_charts)) {
2662 , "CHART netdata.apps_cpu '' 'Apps Plugin CPU' 'milliseconds/s' apps.plugin netdata.apps_cpu stacked 140000 %1$d\n"
2663 "DIMENSION user '' incremental 1 1000\n"
2664 "DIMENSION system '' incremental 1 1000\n"
2665 "CHART netdata.apps_sizes '' 'Apps Plugin Files' 'files/s' apps.plugin netdata.apps_sizes line 140001 %1$d\n"
2666 "DIMENSION calls '' incremental 1 1\n"
2667 "DIMENSION files '' incremental 1 1\n"
2668 "DIMENSION pids '' absolute 1 1\n"
2669 "DIMENSION fds '' absolute 1 1\n"
2670 "DIMENSION targets '' absolute 1 1\n"
2671 "DIMENSION new_pids 'new pids' incremental 1 1\n"
2672 "CHART netdata.apps_fix '' 'Apps Plugin Normalization Ratios' 'percentage' apps.plugin netdata.apps_fix line 140002 %1$d\n"
2673 "DIMENSION utime '' absolute 1 %2$llu\n"
2674 "DIMENSION stime '' absolute 1 %2$llu\n"
2675 "DIMENSION gtime '' absolute 1 %2$llu\n"
2676 "DIMENSION minflt '' absolute 1 %2$llu\n"
2677 "DIMENSION majflt '' absolute 1 %2$llu\n"
2682 if(include_exited_childs)
2684 , "CHART netdata.apps_children_fix '' 'Apps Plugin Exited Children Normalization Ratios' 'percentage' apps.plugin netdata.apps_children_fix line 140003 %1$d\n"
2685 "DIMENSION cutime '' absolute 1 %2$llu\n"
2686 "DIMENSION cstime '' absolute 1 %2$llu\n"
2687 "DIMENSION cgtime '' absolute 1 %2$llu\n"
2688 "DIMENSION cminflt '' absolute 1 %2$llu\n"
2689 "DIMENSION cmajflt '' absolute 1 %2$llu\n"
2696 "BEGIN netdata.apps_cpu %llu\n"
2698 "SET system = %llu\n"
2700 "BEGIN netdata.apps_sizes %llu\n"
2705 "SET targets = %zu\n"
2706 "SET new_pids = %zu\n"
2708 "BEGIN netdata.apps_fix %llu\n"
2723 , apps_groups_targets_count
2724 , targets_assignment_counter
2726 , (unsigned int)(utime_fix_ratio * 100 * RATES_DETAIL)
2727 , (unsigned int)(stime_fix_ratio * 100 * RATES_DETAIL)
2728 , (unsigned int)(gtime_fix_ratio * 100 * RATES_DETAIL)
2729 , (unsigned int)(minflt_fix_ratio * 100 * RATES_DETAIL)
2730 , (unsigned int)(majflt_fix_ratio * 100 * RATES_DETAIL)
2733 if(include_exited_childs)
2735 "BEGIN netdata.apps_children_fix %llu\n"
2739 "SET cminflt = %u\n"
2740 "SET cmajflt = %u\n"
2743 , (unsigned int)(cutime_fix_ratio * 100 * RATES_DETAIL)
2744 , (unsigned int)(cstime_fix_ratio * 100 * RATES_DETAIL)
2745 , (unsigned int)(cgtime_fix_ratio * 100 * RATES_DETAIL)
2746 , (unsigned int)(cminflt_fix_ratio * 100 * RATES_DETAIL)
2747 , (unsigned int)(cmajflt_fix_ratio * 100 * RATES_DETAIL)
2753 static void normalize_utilization(struct target *root) {
2756 // childs processing introduces spikes
2757 // here we try to eliminate them by disabling childs processing either for specific dimensions
2758 // or entirely. Of course, either way, we disable it just a single iteration.
2760 kernel_uint_t max_time = processors * hz * RATES_DETAIL;
2761 kernel_uint_t utime = 0, cutime = 0, stime = 0, cstime = 0, gtime = 0, cgtime = 0, minflt = 0, cminflt = 0, majflt = 0, cmajflt = 0;
2763 if(global_utime > max_time) global_utime = max_time;
2764 if(global_stime > max_time) global_stime = max_time;
2765 if(global_gtime > max_time) global_gtime = max_time;
2767 for(w = root; w ; w = w->next) {
2768 if(w->target || (!w->processes && !w->exposed)) continue;
2773 cutime += w->cutime;
2774 cstime += w->cstime;
2775 cgtime += w->cgtime;
2777 minflt += w->minflt;
2778 majflt += w->majflt;
2779 cminflt += w->cminflt;
2780 cmajflt += w->cmajflt;
2783 if((global_utime || global_stime || global_gtime) && (utime || stime || gtime)) {
2784 if(global_utime + global_stime + global_gtime > utime + cutime + stime + cstime + gtime + cgtime) {
2785 // everything we collected fits
2791 cgtime_fix_ratio = 1.0; //(double)(global_utime + global_stime) / (double)(utime + cutime + stime + cstime);
2793 else if(global_utime + global_stime > utime + stime) {
2794 // childrens resources are too high
2795 // lower only the children resources
2798 gtime_fix_ratio = 1.0;
2801 cgtime_fix_ratio = (double)((global_utime + global_stime) - (utime + stime)) / (double)(cutime + cstime);
2804 // even running processes are unrealistic
2805 // zero the children resources
2806 // lower the running processes resources
2809 gtime_fix_ratio = (double)(global_utime + global_stime) / (double)(utime + stime);
2812 cgtime_fix_ratio = 0.0;
2821 cgtime_fix_ratio = 0.0;
2824 if(utime_fix_ratio > 1.0) utime_fix_ratio = 1.0;
2825 if(cutime_fix_ratio > 1.0) cutime_fix_ratio = 1.0;
2826 if(stime_fix_ratio > 1.0) stime_fix_ratio = 1.0;
2827 if(cstime_fix_ratio > 1.0) cstime_fix_ratio = 1.0;
2828 if(gtime_fix_ratio > 1.0) gtime_fix_ratio = 1.0;
2829 if(cgtime_fix_ratio > 1.0) cgtime_fix_ratio = 1.0;
2831 // if(utime_fix_ratio < 0.0) utime_fix_ratio = 0.0;
2832 // if(cutime_fix_ratio < 0.0) cutime_fix_ratio = 0.0;
2833 // if(stime_fix_ratio < 0.0) stime_fix_ratio = 0.0;
2834 // if(cstime_fix_ratio < 0.0) cstime_fix_ratio = 0.0;
2835 // if(gtime_fix_ratio < 0.0) gtime_fix_ratio = 0.0;
2836 // if(cgtime_fix_ratio < 0.0) cgtime_fix_ratio = 0.0;
2839 // we use cpu time to normalize page faults
2840 // the problem is that to find the proper max values
2841 // for page faults we have to parse /proc/vmstat
2842 // which is quite big to do it again (netdata does it already)
2844 // a better solution could be to somehow have netdata
2845 // do this normalization for us
2847 if(utime || stime || gtime)
2849 minflt_fix_ratio = (double)(utime * utime_fix_ratio + stime * stime_fix_ratio + gtime * gtime_fix_ratio) / (double)(utime + stime + gtime);
2852 majflt_fix_ratio = 1.0;
2854 if(cutime || cstime || cgtime)
2856 cminflt_fix_ratio = (double)(cutime * cutime_fix_ratio + cstime * cstime_fix_ratio + cgtime * cgtime_fix_ratio) / (double)(cutime + cstime + cgtime);
2859 cmajflt_fix_ratio = 1.0;
2863 if(unlikely(debug)) {
2865 "SYSTEM: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
2866 "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 " "
2867 "DELTA: u=" KERNEL_UINT_FORMAT " s=" KERNEL_UINT_FORMAT " g=" KERNEL_UINT_FORMAT " "
2868 "FIX: u=%0.2f s=%0.2f g=%0.2f cu=%0.2f cs=%0.2f cg=%0.2f "
2869 "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 " "
2880 , utime + cutime - global_utime
2881 , stime + cstime - global_stime
2882 , gtime + cgtime - global_gtime
2889 , (kernel_uint_t)(utime * utime_fix_ratio)
2890 , (kernel_uint_t)(stime * stime_fix_ratio)
2891 , (kernel_uint_t)(gtime * gtime_fix_ratio)
2892 , (kernel_uint_t)(cutime * cutime_fix_ratio)
2893 , (kernel_uint_t)(cstime * cstime_fix_ratio)
2894 , (kernel_uint_t)(cgtime * cgtime_fix_ratio)
2899 static void send_collected_data_to_netdata(struct target *root, const char *type, usec_t usec) {
2902 send_BEGIN(type, "cpu", usec);
2903 for (w = root; w ; w = w->next) {
2904 if(unlikely(w->exposed))
2905 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));
2909 send_BEGIN(type, "cpu_user", usec);
2910 for (w = root; w ; w = w->next) {
2911 if(unlikely(w->exposed))
2912 send_SET(w->name, (kernel_uint_t)(w->utime * utime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cutime * cutime_fix_ratio)):0ULL));
2916 send_BEGIN(type, "cpu_system", usec);
2917 for (w = root; w ; w = w->next) {
2918 if(unlikely(w->exposed))
2919 send_SET(w->name, (kernel_uint_t)(w->stime * stime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cstime * cstime_fix_ratio)):0ULL));
2923 if(show_guest_time) {
2924 send_BEGIN(type, "cpu_guest", usec);
2925 for (w = root; w ; w = w->next) {
2926 if(unlikely(w->exposed))
2927 send_SET(w->name, (kernel_uint_t)(w->gtime * gtime_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cgtime * cgtime_fix_ratio)):0ULL));
2932 send_BEGIN(type, "threads", usec);
2933 for (w = root; w ; w = w->next) {
2934 if(unlikely(w->exposed))
2935 send_SET(w->name, w->num_threads);
2939 send_BEGIN(type, "processes", usec);
2940 for (w = root; w ; w = w->next) {
2941 if(unlikely(w->exposed))
2942 send_SET(w->name, w->processes);
2946 send_BEGIN(type, "mem", usec);
2947 for (w = root; w ; w = w->next) {
2948 if(unlikely(w->exposed))
2949 send_SET(w->name, (w->statm_resident > w->statm_share)?(w->statm_resident - w->statm_share):0ULL);
2953 send_BEGIN(type, "vmem", usec);
2954 for (w = root; w ; w = w->next) {
2955 if(unlikely(w->exposed))
2956 send_SET(w->name, w->statm_size);
2960 send_BEGIN(type, "minor_faults", usec);
2961 for (w = root; w ; w = w->next) {
2962 if(unlikely(w->exposed))
2963 send_SET(w->name, (kernel_uint_t)(w->minflt * minflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cminflt * cminflt_fix_ratio)):0ULL));
2967 send_BEGIN(type, "major_faults", usec);
2968 for (w = root; w ; w = w->next) {
2969 if(unlikely(w->exposed))
2970 send_SET(w->name, (kernel_uint_t)(w->majflt * majflt_fix_ratio) + (include_exited_childs?((kernel_uint_t)(w->cmajflt * cmajflt_fix_ratio)):0ULL));
2975 send_BEGIN(type, "lreads", usec);
2976 for (w = root; w ; w = w->next) {
2977 if(unlikely(w->exposed))
2978 send_SET(w->name, w->io_logical_bytes_read);
2982 send_BEGIN(type, "lwrites", usec);
2983 for (w = root; w ; w = w->next) {
2984 if(unlikely(w->exposed))
2985 send_SET(w->name, w->io_logical_bytes_written);
2990 send_BEGIN(type, "preads", usec);
2991 for (w = root; w ; w = w->next) {
2992 if(unlikely(w->exposed))
2993 send_SET(w->name, w->io_storage_bytes_read);
2997 send_BEGIN(type, "pwrites", usec);
2998 for (w = root; w ; w = w->next) {
2999 if(unlikely(w->exposed))
3000 send_SET(w->name, w->io_storage_bytes_written);
3004 if(enable_file_charts) {
3005 send_BEGIN(type, "files", usec);
3006 for (w = root; w; w = w->next) {
3007 if (unlikely(w->exposed))
3008 send_SET(w->name, w->openfiles);
3012 send_BEGIN(type, "sockets", usec);
3013 for (w = root; w; w = w->next) {
3014 if (unlikely(w->exposed))
3015 send_SET(w->name, w->opensockets);
3019 send_BEGIN(type, "pipes", usec);
3020 for (w = root; w; w = w->next) {
3021 if (unlikely(w->exposed))
3022 send_SET(w->name, w->openpipes);
3029 // ----------------------------------------------------------------------------
3030 // generate the charts
3032 static void send_charts_updates_to_netdata(struct target *root, const char *type, const char *title)
3035 int newly_added = 0;
3037 for(w = root ; w ; w = w->next) {
3038 if (w->target) continue;
3040 if (!w->exposed && w->processes) {
3043 if (debug || w->debug) fprintf(stderr, "apps.plugin: %s just added - regenerating charts.\n", w->name);
3047 // nothing more to show
3048 if(!newly_added && show_guest_time == show_guest_time_old) return;
3050 // we have something new to show
3051 // update the charts
3052 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);
3053 for (w = root; w ; w = w->next) {
3054 if(unlikely(w->exposed))
3055 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu %s\n", w->name, hz * RATES_DETAIL / 100, w->hidden ? "hidden" : "");
3058 fprintf(stdout, "CHART %s.mem '' '%s Real Memory (w/o shared)' 'MB' mem %s.mem stacked 20003 %d\n", type, title, type, update_every);
3059 for (w = root; w ; w = w->next) {
3060 if(unlikely(w->exposed))
3061 fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
3064 fprintf(stdout, "CHART %s.vmem '' '%s Virtual Memory Size' 'MB' mem %s.vmem stacked 20004 %d\n", type, title, type, update_every);
3065 for (w = root; w ; w = w->next) {
3066 if(unlikely(w->exposed))
3067 fprintf(stdout, "DIMENSION %s '' absolute %ld %ld\n", w->name, sysconf(_SC_PAGESIZE), 1024L*1024L);
3070 fprintf(stdout, "CHART %s.threads '' '%s Threads' 'threads' processes %s.threads stacked 20005 %d\n", type, title, type, update_every);
3071 for (w = root; w ; w = w->next) {
3072 if(unlikely(w->exposed))
3073 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3076 fprintf(stdout, "CHART %s.processes '' '%s Processes' 'processes' processes %s.processes stacked 20004 %d\n", type, title, type, update_every);
3077 for (w = root; w ; w = w->next) {
3078 if(unlikely(w->exposed))
3079 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3082 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);
3083 for (w = root; w ; w = w->next) {
3084 if(unlikely(w->exposed))
3085 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3088 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);
3089 for (w = root; w ; w = w->next) {
3090 if(unlikely(w->exposed))
3091 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3094 if(show_guest_time) {
3095 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);
3096 for (w = root; w; w = w->next) {
3097 if(unlikely(w->exposed))
3098 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, hz * RATES_DETAIL / 100LLU);
3102 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);
3103 for (w = root; w ; w = w->next) {
3104 if(unlikely(w->exposed))
3105 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3108 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);
3109 for (w = root; w ; w = w->next) {
3110 if(unlikely(w->exposed))
3111 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3115 fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'blocks/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
3116 for (w = root; w ; w = w->next) {
3117 if(unlikely(w->exposed))
3118 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3121 fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'blocks/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
3122 for (w = root; w ; w = w->next) {
3123 if(unlikely(w->exposed))
3124 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, RATES_DETAIL);
3127 fprintf(stdout, "CHART %s.preads '' '%s Disk Reads' 'kilobytes/s' disk %s.preads stacked 20002 %d\n", type, title, type, update_every);
3128 for (w = root; w ; w = w->next) {
3129 if(unlikely(w->exposed))
3130 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3133 fprintf(stdout, "CHART %s.pwrites '' '%s Disk Writes' 'kilobytes/s' disk %s.pwrites stacked 20002 %d\n", type, title, type, update_every);
3134 for (w = root; w ; w = w->next) {
3135 if(unlikely(w->exposed))
3136 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3139 fprintf(stdout, "CHART %s.lreads '' '%s Disk Logical Reads' 'kilobytes/s' disk %s.lreads stacked 20042 %d\n", type, title, type, update_every);
3140 for (w = root; w ; w = w->next) {
3141 if(unlikely(w->exposed))
3142 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3145 fprintf(stdout, "CHART %s.lwrites '' '%s I/O Logical Writes' 'kilobytes/s' disk %s.lwrites stacked 20042 %d\n", type, title, type, update_every);
3146 for (w = root; w ; w = w->next) {
3147 if(unlikely(w->exposed))
3148 fprintf(stdout, "DIMENSION %s '' absolute 1 %llu\n", w->name, 1024LLU * RATES_DETAIL);
3152 if(enable_file_charts) {
3153 fprintf(stdout, "CHART %s.files '' '%s Open Files' 'open files' disk %s.files stacked 20050 %d\n", type,
3154 title, type, update_every);
3155 for (w = root; w; w = w->next) {
3156 if (unlikely(w->exposed))
3157 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3160 fprintf(stdout, "CHART %s.sockets '' '%s Open Sockets' 'open sockets' net %s.sockets stacked 20051 %d\n",
3161 type, title, type, update_every);
3162 for (w = root; w; w = w->next) {
3163 if (unlikely(w->exposed))
3164 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3167 fprintf(stdout, "CHART %s.pipes '' '%s Pipes' 'open pipes' processes %s.pipes stacked 20053 %d\n", type,
3168 title, type, update_every);
3169 for (w = root; w; w = w->next) {
3170 if (unlikely(w->exposed))
3171 fprintf(stdout, "DIMENSION %s '' absolute 1 1\n", w->name);
3177 // ----------------------------------------------------------------------------
3178 // parse command line arguments
3180 int check_proc_1_io() {
3183 procfile *ff = procfile_open("/proc/1/io", NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
3184 if(!ff) goto cleanup;
3186 ff = procfile_readall(ff);
3187 if(!ff) goto cleanup;
3196 static void parse_args(int argc, char **argv)
3201 for(i = 1; i < argc; i++) {
3203 int n = (int)str2l(argv[i]);
3210 if(strcmp("version", argv[i]) == 0 || strcmp("-v", argv[i]) == 0 || strcmp("-V", argv[i]) == 0) {
3211 printf("apps.plugin %s\n", VERSION);
3215 if(strcmp("test-permissions", argv[i]) == 0 || strcmp("-t", argv[i]) == 0) {
3216 if(!check_proc_1_io()) {
3217 perror("Tried to read /proc/1/io and it failed");
3224 if(strcmp("debug", argv[i]) == 0) {
3226 // debug_flags = 0xffffffff;
3230 if(strcmp("no-childs", argv[i]) == 0 || strcmp("without-childs", argv[i]) == 0) {
3231 include_exited_childs = 0;
3235 if(strcmp("with-childs", argv[i]) == 0) {
3236 include_exited_childs = 1;
3240 if(strcmp("with-guest", argv[i]) == 0) {
3241 enable_guest_charts = 1;
3245 if(strcmp("no-guest", argv[i]) == 0 || strcmp("without-guest", argv[i]) == 0) {
3246 enable_guest_charts = 0;
3250 if(strcmp("with-files", argv[i]) == 0) {
3251 enable_file_charts = 1;
3255 if(strcmp("no-files", argv[i]) == 0 || strcmp("without-files", argv[i]) == 0) {
3256 enable_file_charts = 0;
3260 if(strcmp("no-users", argv[i]) == 0 || strcmp("without-users", argv[i]) == 0) {
3261 enable_users_charts = 0;
3265 if(strcmp("no-groups", argv[i]) == 0 || strcmp("without-groups", argv[i]) == 0) {
3266 enable_groups_charts = 0;
3270 if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0) {
3273 " netdata apps.plugin %s\n"
3274 " Copyright (C) 2016-2017 Costa Tsaousis <costa@tsaousis.gr>\n"
3275 " Released under GNU General Public License v3 or later.\n"
3276 " All rights reserved.\n"
3278 " This program is a data collector plugin for netdata.\n"
3280 " Available command line options:\n"
3282 " SECONDS set the data collection frequency\n"
3284 " debug enable debugging (lot of output)\n"
3287 " without-childs enable / disable aggregating exited\n"
3288 " children resources into parents\n"
3289 " (default is enabled)\n"
3292 " without-guest enable / disable reporting guest charts\n"
3293 " (default is disabled)\n"
3296 " without-files enable / disable reporting files, sockets, pipes\n"
3297 " (default is enabled)\n"
3299 " NAME read apps_NAME.conf instead of\n"
3300 " apps_groups.conf\n"
3301 " (default NAME=groups)\n"
3303 " version or -v or -V print program version and exit\n"
3315 error("Cannot understand option %s", argv[i]);
3319 if(freq > 0) update_every = freq;
3320 if(!name) name = "groups";
3322 if(read_apps_groups_conf(name)) {
3323 error("Cannot read process groups '%s/apps_%s.conf'. There are no internal defaults. Failing.", config_dir, name);
3328 static int am_i_running_as_root() {
3329 uid_t uid = getuid(), euid = geteuid();
3331 if(uid == 0 || euid == 0) {
3332 if(debug) info("I am running with escalated privileges, uid = %u, euid = %u.", uid, euid);
3336 if(debug) info("I am not running with escalated privileges, uid = %u, euid = %u.", uid, euid);
3340 #ifdef HAVE_CAPABILITY
3341 static int check_capabilities() {
3342 cap_t caps = cap_get_proc();
3344 error("Cannot get current capabilities.");
3348 info("Received my capabilities from the system.");
3352 cap_flag_value_t cfv = CAP_CLEAR;
3353 if(cap_get_flag(caps, CAP_DAC_READ_SEARCH, CAP_EFFECTIVE, &cfv) == -1) {
3354 error("Cannot find if CAP_DAC_READ_SEARCH is effective.");
3358 if(cfv != CAP_SET) {
3359 error("apps.plugin should run with CAP_DAC_READ_SEARCH.");
3363 info("apps.plugin runs with CAP_DAC_READ_SEARCH.");
3367 if(cap_get_flag(caps, CAP_SYS_PTRACE, CAP_EFFECTIVE, &cfv) == -1) {
3368 error("Cannot find if CAP_SYS_PTRACE is effective.");
3372 if(cfv != CAP_SET) {
3373 error("apps.plugin should run with CAP_SYS_PTRACE.");
3377 info("apps.plugin runs with CAP_SYS_PTRACE.");
3385 static int check_capabilities() {
3390 int main(int argc, char **argv) {
3391 // debug_flags = D_PROCFILE;
3393 // set the name for logging
3394 program_name = "apps.plugin";
3396 // disable syslog for apps.plugin
3397 error_log_syslog = 0;
3399 // set errors flood protection to 100 logs per hour
3400 error_log_errors_per_period = 100;
3401 error_log_throttle_period = 3600;
3403 netdata_configured_host_prefix = getenv("NETDATA_HOST_PREFIX");
3404 if(netdata_configured_host_prefix == NULL) {
3405 // info("NETDATA_HOST_PREFIX is not passed from netdata");
3406 netdata_configured_host_prefix = "";
3408 // else info("Found NETDATA_HOST_PREFIX='%s'", netdata_configured_host_prefix);
3410 config_dir = getenv("NETDATA_CONFIG_DIR");
3411 if(config_dir == NULL) {
3412 // info("NETDATA_CONFIG_DIR is not passed from netdata");
3413 config_dir = CONFIG_DIR;
3415 // else info("Found NETDATA_CONFIG_DIR='%s'", config_dir);
3417 #ifdef NETDATA_INTERNAL_CHECKS
3418 if(debug_flags != 0) {
3419 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
3420 if(setrlimit(RLIMIT_CORE, &rl) != 0)
3421 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
3422 #ifdef HAVE_SYS_PRCTL_H
3423 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
3426 #endif /* NETDATA_INTERNAL_CHECKS */
3428 procfile_adaptive_initial_allocation = 1;
3430 time_t started_t = now_monotonic_sec();
3432 get_system_pid_max();
3435 parse_args(argc, argv);
3437 if(!check_capabilities() && !am_i_running_as_root() && !check_proc_1_io()) {
3438 uid_t uid = getuid(), euid = geteuid();
3439 #ifdef HAVE_CAPABILITY
3440 error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
3441 "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
3442 "To enable capabilities run: sudo setcap cap_dac_read_search,cap_sys_ptrace+ep %s; "
3443 "To enable setuid to root run: sudo chown root %s; sudo chmod 4755 %s; "
3444 , uid, euid, argv[0], argv[0], argv[0]
3447 error("apps.plugin should either run as root (now running with uid %u, euid %u) or have special capabilities. "
3448 "Without these, apps.plugin cannot report disk I/O utilization of other processes. "
3449 "Your system does not support capabilities. "
3450 "To enable setuid to root run: sudo chown root %s; sudo chmod 4755 %s; "
3451 , uid, euid, argv[0], argv[0]
3456 info("started on pid %d", getpid());
3458 #if (ALL_PIDS_ARE_READ_INSTANTLY == 0)
3459 all_pids_sortlist = callocz(sizeof(pid_t), (size_t)pid_max);
3462 all_pids = callocz(sizeof(struct pid_stat *), (size_t) pid_max);
3464 usec_t step = update_every * USEC_PER_SEC;
3465 global_iterations_counter = 1;
3467 heartbeat_init(&hb);
3468 for(;1; global_iterations_counter++) {
3470 #ifdef NETDATA_PROFILING
3471 #warning "compiling for profiling"
3472 static int profiling_count=0;
3474 if(unlikely(profiling_count > 1000)) exit(0);
3476 heartbeat_next(&hb, step);
3479 if(!collect_data_for_all_processes()) {
3480 error("Cannot collect /proc data for running processes. Disabling apps.plugin...");
3481 printf("DISABLE\n");
3485 calculate_netdata_statistics();
3486 normalize_utilization(apps_groups_root_target);
3488 usec_t dt = send_resource_usage_to_netdata();
3490 // this is smart enough to show only newly added apps, when needed
3491 send_charts_updates_to_netdata(apps_groups_root_target, "apps", "Apps");
3493 if(likely(enable_users_charts))
3494 send_charts_updates_to_netdata(users_root_target, "users", "Users");
3496 if(likely(enable_groups_charts))
3497 send_charts_updates_to_netdata(groups_root_target, "groups", "User Groups");
3499 send_collected_data_to_netdata(apps_groups_root_target, "apps", dt);
3501 if(likely(enable_users_charts))
3502 send_collected_data_to_netdata(users_root_target, "users", dt);
3504 if(likely(enable_groups_charts))
3505 send_collected_data_to_netdata(groups_root_target, "groups", dt);
3509 show_guest_time_old = show_guest_time;
3512 fprintf(stderr, "apps.plugin: done Loop No %zu\n", global_iterations_counter);
3514 // restart check (14400 seconds)
3515 if(now_monotonic_sec() - started_t > 14400) exit(0);