Merge branch 'collectd-5.8'
[collectd.git] / src / processes.c
1 /**
2  * collectd - src/processes.c
3  * Copyright (C) 2005       Lyonel Vincent
4  * Copyright (C) 2006-2010  Florian octo Forster
5  * Copyright (C) 2008       Oleg King
6  * Copyright (C) 2009       Sebastian Harl
7  * Copyright (C) 2009       Andrés J. Díaz
8  * Copyright (C) 2009       Manuel Sanmartin
9  * Copyright (C) 2010       Clément Stenac
10  * Copyright (C) 2012       Cosmin Ioiart
11  *
12  * This program is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU General Public License as published by the
14  * Free Software Foundation; either version 2 of the License, or (at your
15  * option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful, but
18  * WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along
23  * with this program; if not, write to the Free Software Foundation, Inc.,
24  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
25  *
26  * Authors:
27  *   Lyonel Vincent <lyonel at ezix.org>
28  *   Florian octo Forster <octo at collectd.org>
29  *   Oleg King <king2 at kaluga.ru>
30  *   Sebastian Harl <sh at tokkee.org>
31  *   Andrés J. Díaz <ajdiaz at connectical.com>
32  *   Manuel Sanmartin
33  *   Clément Stenac <clement.stenac at diwi.org>
34  *   Cosmin Ioiart <cioiart at gmail.com>
35  *   Pavel Rochnyack <pavel2000 at ngs.ru>
36  *   Wilfried Goesgens <dothebart at citadel.org>
37  **/
38
39 #include "collectd.h"
40
41 #include "common.h"
42 #include "plugin.h"
43
44 /* Include header files for the mach system, if they exist.. */
45 #if HAVE_THREAD_INFO
46 #if HAVE_MACH_MACH_INIT_H
47 #include <mach/mach_init.h>
48 #endif
49 #if HAVE_MACH_HOST_PRIV_H
50 #include <mach/host_priv.h>
51 #endif
52 #if HAVE_MACH_MACH_ERROR_H
53 #include <mach/mach_error.h>
54 #endif
55 #if HAVE_MACH_MACH_HOST_H
56 #include <mach/mach_host.h>
57 #endif
58 #if HAVE_MACH_MACH_PORT_H
59 #include <mach/mach_port.h>
60 #endif
61 #if HAVE_MACH_MACH_TYPES_H
62 #include <mach/mach_types.h>
63 #endif
64 #if HAVE_MACH_MESSAGE_H
65 #include <mach/message.h>
66 #endif
67 #if HAVE_MACH_PROCESSOR_SET_H
68 #include <mach/processor_set.h>
69 #endif
70 #if HAVE_MACH_TASK_H
71 #include <mach/task.h>
72 #endif
73 #if HAVE_MACH_THREAD_ACT_H
74 #include <mach/thread_act.h>
75 #endif
76 #if HAVE_MACH_VM_REGION_H
77 #include <mach/vm_region.h>
78 #endif
79 #if HAVE_MACH_VM_MAP_H
80 #include <mach/vm_map.h>
81 #endif
82 #if HAVE_MACH_VM_PROT_H
83 #include <mach/vm_prot.h>
84 #endif
85 #if HAVE_SYS_SYSCTL_H
86 #include <sys/sysctl.h>
87 #endif
88 /* #endif HAVE_THREAD_INFO */
89
90 #elif KERNEL_LINUX
91 #if HAVE_LINUX_CONFIG_H
92 #include <linux/config.h>
93 #endif
94 #ifndef CONFIG_HZ
95 #define CONFIG_HZ 100
96 #endif
97 /* #endif KERNEL_LINUX */
98
99 #elif HAVE_LIBKVM_GETPROCS &&                                                  \
100     (HAVE_STRUCT_KINFO_PROC_FREEBSD || HAVE_STRUCT_KINFO_PROC_OPENBSD)
101 #include <kvm.h>
102 #include <sys/param.h>
103 #include <sys/proc.h>
104 #include <sys/sysctl.h>
105 #include <sys/user.h>
106 /* #endif HAVE_LIBKVM_GETPROCS && (HAVE_STRUCT_KINFO_PROC_FREEBSD ||
107  * HAVE_STRUCT_KINFO_PROC_OPENBSD) */
108
109 #elif HAVE_PROCINFO_H
110 #include <procinfo.h>
111 #include <sys/types.h>
112
113 #define MAXPROCENTRY 32
114 #define MAXTHRDENTRY 16
115 #define MAXARGLN 1024
116 /* #endif HAVE_PROCINFO_H */
117
118 #elif KERNEL_SOLARIS
119 /* Hack: Avoid #error when building a 32-bit binary with
120  * _FILE_OFFSET_BITS=64. There is a reason for this #error, as one
121  * of the structures in <sys/procfs.h> uses an off_t, but that
122  * isn't relevant to our usage of procfs. */
123 #if !defined(_LP64) && _FILE_OFFSET_BITS == 64
124 #define SAVE_FOB_64
125 #undef _FILE_OFFSET_BITS
126 #endif
127
128 #include <procfs.h>
129
130 #ifdef SAVE_FOB_64
131 #define _FILE_OFFSET_BITS 64
132 #undef SAVE_FOB_64
133 #endif
134
135 #include <dirent.h>
136 #include <sys/user.h>
137
138 #ifndef MAXCOMLEN
139 #define MAXCOMLEN 16
140 #endif
141
142 /* #endif KERNEL_SOLARIS */
143
144 #else
145 #error "No applicable input method."
146 #endif
147
148 #if HAVE_REGEX_H
149 #include <regex.h>
150 #endif
151
152 #if HAVE_KSTAT_H
153 #include <kstat.h>
154 #endif
155
156 #ifndef CMDLINE_BUFFER_SIZE
157 #if defined(ARG_MAX) && (ARG_MAX < 4096)
158 #define CMDLINE_BUFFER_SIZE ARG_MAX
159 #else
160 #define CMDLINE_BUFFER_SIZE 4096
161 #endif
162 #endif
163
164 #define PROCSTAT_NAME_LEN 256
165 typedef struct process_entry_s {
166   unsigned long id;
167   char name[PROCSTAT_NAME_LEN];
168
169   unsigned long num_proc;
170   unsigned long num_lwp;
171   unsigned long num_fd;
172   unsigned long num_maps;
173   unsigned long vmem_size;
174   unsigned long vmem_rss;
175   unsigned long vmem_data;
176   unsigned long vmem_code;
177   unsigned long stack_size;
178
179   derive_t vmem_minflt_counter;
180   derive_t vmem_majflt_counter;
181
182   derive_t cpu_user_counter;
183   derive_t cpu_system_counter;
184
185   /* io data */
186   derive_t io_rchar;
187   derive_t io_wchar;
188   derive_t io_syscr;
189   derive_t io_syscw;
190   derive_t io_diskr;
191   derive_t io_diskw;
192   _Bool has_io;
193
194   derive_t cswitch_vol;
195   derive_t cswitch_invol;
196   _Bool has_cswitch;
197
198   _Bool has_fd;
199
200   _Bool has_maps;
201 } process_entry_t;
202
203 typedef struct procstat_entry_s {
204   unsigned long id;
205   unsigned long age;
206
207   derive_t vmem_minflt_counter;
208   derive_t vmem_majflt_counter;
209
210   derive_t cpu_user_counter;
211   derive_t cpu_system_counter;
212
213   /* io data */
214   derive_t io_rchar;
215   derive_t io_wchar;
216   derive_t io_syscr;
217   derive_t io_syscw;
218   derive_t io_diskr;
219   derive_t io_diskw;
220
221   derive_t cswitch_vol;
222   derive_t cswitch_invol;
223
224   struct procstat_entry_s *next;
225 } procstat_entry_t;
226
227 typedef struct procstat {
228   char name[PROCSTAT_NAME_LEN];
229 #if HAVE_REGEX_H
230   regex_t *re;
231 #endif
232
233   unsigned long num_proc;
234   unsigned long num_lwp;
235   unsigned long num_fd;
236   unsigned long num_maps;
237   unsigned long vmem_size;
238   unsigned long vmem_rss;
239   unsigned long vmem_data;
240   unsigned long vmem_code;
241   unsigned long stack_size;
242
243   derive_t vmem_minflt_counter;
244   derive_t vmem_majflt_counter;
245
246   derive_t cpu_user_counter;
247   derive_t cpu_system_counter;
248
249   /* io data */
250   derive_t io_rchar;
251   derive_t io_wchar;
252   derive_t io_syscr;
253   derive_t io_syscw;
254   derive_t io_diskr;
255   derive_t io_diskw;
256
257   derive_t cswitch_vol;
258   derive_t cswitch_invol;
259
260   _Bool report_fd_num;
261   _Bool report_maps_num;
262   _Bool report_ctx_switch;
263
264   struct procstat *next;
265   struct procstat_entry_s *instances;
266 } procstat_t;
267
268 static procstat_t *list_head_g = NULL;
269
270 static _Bool want_init = 1;
271 static _Bool report_ctx_switch = 0;
272 static _Bool report_fd_num = 0;
273 static _Bool report_maps_num = 0;
274
275 #if HAVE_THREAD_INFO
276 static mach_port_t port_host_self;
277 static mach_port_t port_task_self;
278
279 static processor_set_name_array_t pset_list;
280 static mach_msg_type_number_t pset_list_len;
281 /* #endif HAVE_THREAD_INFO */
282
283 #elif KERNEL_LINUX
284 static long pagesize_g;
285 static void ps_fill_details(const procstat_t *ps, process_entry_t *entry);
286 /* #endif KERNEL_LINUX */
287
288 #elif HAVE_LIBKVM_GETPROCS &&                                                  \
289     (HAVE_STRUCT_KINFO_PROC_FREEBSD || HAVE_STRUCT_KINFO_PROC_OPENBSD)
290 static int pagesize;
291 /* #endif HAVE_LIBKVM_GETPROCS && (HAVE_STRUCT_KINFO_PROC_FREEBSD ||
292  * HAVE_STRUCT_KINFO_PROC_OPENBSD) */
293
294 #elif HAVE_PROCINFO_H
295 static struct procentry64 procentry[MAXPROCENTRY];
296 static struct thrdentry64 thrdentry[MAXTHRDENTRY];
297 static int pagesize;
298
299 #ifndef _AIXVERSION_610
300 int getprocs64(void *procsinfo, int sizproc, void *fdsinfo, int sizfd,
301                pid_t *index, int count);
302 int getthrds64(pid_t, void *, int, tid64_t *, int);
303 #endif
304 int getargs(void *processBuffer, int bufferLen, char *argsBuffer, int argsLen);
305 #endif /* HAVE_PROCINFO_H */
306
307 /* put name of process from config to list_head_g tree
308  * list_head_g is a list of 'procstat_t' structs with
309  * processes names we want to watch */
310 static procstat_t *ps_list_register(const char *name, const char *regexp) {
311   procstat_t *new;
312   procstat_t *ptr;
313   int status;
314
315   new = calloc(1, sizeof(*new));
316   if (new == NULL) {
317     ERROR("processes plugin: ps_list_register: calloc failed.");
318     return NULL;
319   }
320   sstrncpy(new->name, name, sizeof(new->name));
321
322   new->io_rchar = -1;
323   new->io_wchar = -1;
324   new->io_syscr = -1;
325   new->io_syscw = -1;
326   new->io_diskr = -1;
327   new->io_diskw = -1;
328   new->cswitch_vol = -1;
329   new->cswitch_invol = -1;
330
331   new->report_fd_num = report_fd_num;
332   new->report_maps_num = report_maps_num;
333   new->report_ctx_switch = report_ctx_switch;
334
335 #if HAVE_REGEX_H
336   if (regexp != NULL) {
337     DEBUG("ProcessMatch: adding \"%s\" as criteria to process %s.", regexp,
338           name);
339     new->re = malloc(sizeof(*new->re));
340     if (new->re == NULL) {
341       ERROR("processes plugin: ps_list_register: malloc failed.");
342       sfree(new);
343       return NULL;
344     }
345
346     status = regcomp(new->re, regexp, REG_EXTENDED | REG_NOSUB);
347     if (status != 0) {
348       DEBUG("ProcessMatch: compiling the regular expression \"%s\" failed.",
349             regexp);
350       sfree(new->re);
351       sfree(new);
352       return NULL;
353     }
354   }
355 #else
356   if (regexp != NULL) {
357     ERROR("processes plugin: ps_list_register: "
358           "Regular expression \"%s\" found in config "
359           "file, but support for regular expressions "
360           "has been disabled at compile time.",
361           regexp);
362     sfree(new);
363     return NULL;
364   }
365 #endif
366
367   for (ptr = list_head_g; ptr != NULL; ptr = ptr->next) {
368     if (strcmp(ptr->name, name) == 0) {
369       WARNING("processes plugin: You have configured more "
370               "than one `Process' or "
371               "`ProcessMatch' with the same name. "
372               "All but the first setting will be "
373               "ignored.");
374 #if HAVE_REGEX_H
375       sfree(new->re);
376 #endif
377       sfree(new);
378       return NULL;
379     }
380
381     if (ptr->next == NULL)
382       break;
383   }
384
385   if (ptr == NULL)
386     list_head_g = new;
387   else
388     ptr->next = new;
389
390   return new;
391 } /* void ps_list_register */
392
393 /* try to match name against entry, returns 1 if success */
394 static int ps_list_match(const char *name, const char *cmdline,
395                          procstat_t *ps) {
396 #if HAVE_REGEX_H
397   if (ps->re != NULL) {
398     int status;
399     const char *str;
400
401     str = cmdline;
402     if ((str == NULL) || (str[0] == 0))
403       str = name;
404
405     assert(str != NULL);
406
407     status = regexec(ps->re, str,
408                      /* nmatch = */ 0,
409                      /* pmatch = */ NULL,
410                      /* eflags = */ 0);
411     if (status == 0)
412       return 1;
413   } else
414 #endif
415       if (strcmp(ps->name, name) == 0)
416     return 1;
417
418   return 0;
419 } /* int ps_list_match */
420
421 static void ps_update_counter(derive_t *group_counter, derive_t *curr_counter,
422                               derive_t new_counter) {
423   unsigned long curr_value;
424
425   if (want_init) {
426     *curr_counter = new_counter;
427     return;
428   }
429
430   if (new_counter < *curr_counter)
431     curr_value = new_counter + (ULONG_MAX - *curr_counter);
432   else
433     curr_value = new_counter - *curr_counter;
434
435   if (*group_counter == -1)
436     *group_counter = 0;
437
438   *curr_counter = new_counter;
439   *group_counter += curr_value;
440 }
441
442 /* add process entry to 'instances' of process 'name' (or refresh it) */
443 static void ps_list_add(const char *name, const char *cmdline,
444                         process_entry_t *entry) {
445   procstat_entry_t *pse;
446
447   if (entry->id == 0)
448     return;
449
450   for (procstat_t *ps = list_head_g; ps != NULL; ps = ps->next) {
451     if ((ps_list_match(name, cmdline, ps)) == 0)
452       continue;
453
454 #if KERNEL_LINUX
455     ps_fill_details(ps, entry);
456 #endif
457
458     for (pse = ps->instances; pse != NULL; pse = pse->next)
459       if ((pse->id == entry->id) || (pse->next == NULL))
460         break;
461
462     if ((pse == NULL) || (pse->id != entry->id)) {
463       procstat_entry_t *new;
464
465       new = calloc(1, sizeof(*new));
466       if (new == NULL)
467         return;
468       new->id = entry->id;
469
470       if (pse == NULL)
471         ps->instances = new;
472       else
473         pse->next = new;
474
475       pse = new;
476     }
477
478     pse->age = 0;
479
480     ps->num_proc += entry->num_proc;
481     ps->num_lwp += entry->num_lwp;
482     ps->num_fd += entry->num_fd;
483     ps->num_maps += entry->num_maps;
484     ps->vmem_size += entry->vmem_size;
485     ps->vmem_rss += entry->vmem_rss;
486     ps->vmem_data += entry->vmem_data;
487     ps->vmem_code += entry->vmem_code;
488     ps->stack_size += entry->stack_size;
489
490     if ((entry->io_rchar != -1) && (entry->io_wchar != -1)) {
491       ps_update_counter(&ps->io_rchar, &pse->io_rchar, entry->io_rchar);
492       ps_update_counter(&ps->io_wchar, &pse->io_wchar, entry->io_wchar);
493     }
494
495     if ((entry->io_syscr != -1) && (entry->io_syscw != -1)) {
496       ps_update_counter(&ps->io_syscr, &pse->io_syscr, entry->io_syscr);
497       ps_update_counter(&ps->io_syscw, &pse->io_syscw, entry->io_syscw);
498     }
499
500     if ((entry->io_diskr != -1) && (entry->io_diskw != -1)) {
501       ps_update_counter(&ps->io_diskr, &pse->io_diskr, entry->io_diskr);
502       ps_update_counter(&ps->io_diskw, &pse->io_diskw, entry->io_diskw);
503     }
504
505     if ((entry->cswitch_vol != -1) && (entry->cswitch_invol != -1)) {
506       ps_update_counter(&ps->cswitch_vol, &pse->cswitch_vol,
507                         entry->cswitch_vol);
508       ps_update_counter(&ps->cswitch_invol, &pse->cswitch_invol,
509                         entry->cswitch_invol);
510     }
511
512     ps_update_counter(&ps->vmem_minflt_counter, &pse->vmem_minflt_counter,
513                       entry->vmem_minflt_counter);
514     ps_update_counter(&ps->vmem_majflt_counter, &pse->vmem_majflt_counter,
515                       entry->vmem_majflt_counter);
516
517     ps_update_counter(&ps->cpu_user_counter, &pse->cpu_user_counter,
518                       entry->cpu_user_counter);
519     ps_update_counter(&ps->cpu_system_counter, &pse->cpu_system_counter,
520                       entry->cpu_system_counter);
521   }
522 }
523
524 /* remove old entries from instances of processes in list_head_g */
525 static void ps_list_reset(void) {
526   procstat_entry_t *pse;
527   procstat_entry_t *pse_prev;
528
529   for (procstat_t *ps = list_head_g; ps != NULL; ps = ps->next) {
530     ps->num_proc = 0;
531     ps->num_lwp = 0;
532     ps->num_fd = 0;
533     ps->num_maps = 0;
534     ps->vmem_size = 0;
535     ps->vmem_rss = 0;
536     ps->vmem_data = 0;
537     ps->vmem_code = 0;
538     ps->stack_size = 0;
539
540     pse_prev = NULL;
541     pse = ps->instances;
542     while (pse != NULL) {
543       if (pse->age > 10) {
544         DEBUG("Removing this procstat entry cause it's too old: "
545               "id = %lu; name = %s;",
546               pse->id, ps->name);
547
548         if (pse_prev == NULL) {
549           ps->instances = pse->next;
550           free(pse);
551           pse = ps->instances;
552         } else {
553           pse_prev->next = pse->next;
554           free(pse);
555           pse = pse_prev->next;
556         }
557       } else {
558         pse->age++;
559         pse_prev = pse;
560         pse = pse->next;
561       }
562     } /* while (pse != NULL) */
563   }   /* for (ps = list_head_g; ps != NULL; ps = ps->next) */
564 }
565
566 static void ps_tune_instance(oconfig_item_t *ci, procstat_t *ps) {
567   for (int i = 0; i < ci->children_num; i++) {
568     oconfig_item_t *c = ci->children + i;
569
570     if (strcasecmp(c->key, "CollectContextSwitch") == 0)
571       cf_util_get_boolean(c, &ps->report_ctx_switch);
572     else if (strcasecmp(c->key, "CollectFileDescriptor") == 0)
573       cf_util_get_boolean(c, &ps->report_fd_num);
574     else if (strcasecmp(c->key, "CollectMemoryMaps") == 0)
575       cf_util_get_boolean(c, &ps->report_maps_num);
576     else {
577       ERROR("processes plugin: Option `%s' not allowed here.", c->key);
578     }
579   } /* for (ci->children) */
580 } /* void ps_tune_instance */
581
582 /* put all pre-defined 'Process' names from config to list_head_g tree */
583 static int ps_config(oconfig_item_t *ci) {
584 #if KERNEL_LINUX
585   const size_t max_procname_len = 15;
586 #elif KERNEL_SOLARIS || KERNEL_FREEBSD
587   const size_t max_procname_len = MAXCOMLEN - 1;
588 #endif
589
590   procstat_t *ps;
591
592   for (int i = 0; i < ci->children_num; ++i) {
593     oconfig_item_t *c = ci->children + i;
594
595     if (strcasecmp(c->key, "Process") == 0) {
596       if ((c->values_num != 1) || (OCONFIG_TYPE_STRING != c->values[0].type)) {
597         ERROR("processes plugin: `Process' expects exactly "
598               "one string argument (got %i).",
599               c->values_num);
600         continue;
601       }
602
603 #if KERNEL_LINUX || KERNEL_SOLARIS || KERNEL_FREEBSD
604       if (strlen(c->values[0].value.string) > max_procname_len) {
605         WARNING("processes plugin: this platform has a %zu character limit "
606                 "to process names. The `Process \"%s\"' option will "
607                 "not work as expected.",
608                 max_procname_len, c->values[0].value.string);
609       }
610 #endif
611
612       ps = ps_list_register(c->values[0].value.string, NULL);
613
614       if (c->children_num != 0 && ps != NULL)
615         ps_tune_instance(c, ps);
616     } else if (strcasecmp(c->key, "ProcessMatch") == 0) {
617       if ((c->values_num != 2) || (OCONFIG_TYPE_STRING != c->values[0].type) ||
618           (OCONFIG_TYPE_STRING != c->values[1].type)) {
619         ERROR("processes plugin: `ProcessMatch' needs exactly "
620               "two string arguments (got %i).",
621               c->values_num);
622         continue;
623       }
624
625       ps = ps_list_register(c->values[0].value.string,
626                             c->values[1].value.string);
627
628       if (c->children_num != 0 && ps != NULL)
629         ps_tune_instance(c, ps);
630     } else if (strcasecmp(c->key, "CollectContextSwitch") == 0) {
631       cf_util_get_boolean(c, &report_ctx_switch);
632     } else if (strcasecmp(c->key, "CollectFileDescriptor") == 0) {
633       cf_util_get_boolean(c, &report_fd_num);
634     } else if (strcasecmp(c->key, "CollectMemoryMaps") == 0) {
635       cf_util_get_boolean(c, &report_maps_num);
636     } else {
637       ERROR("processes plugin: The `%s' configuration option is not "
638             "understood and will be ignored.",
639             c->key);
640       continue;
641     }
642   }
643
644   return 0;
645 }
646
647 static int ps_init(void) {
648 #if HAVE_THREAD_INFO
649   kern_return_t status;
650
651   port_host_self = mach_host_self();
652   port_task_self = mach_task_self();
653
654   if (pset_list != NULL) {
655     vm_deallocate(port_task_self, (vm_address_t)pset_list,
656                   pset_list_len * sizeof(processor_set_t));
657     pset_list = NULL;
658     pset_list_len = 0;
659   }
660
661   if ((status = host_processor_sets(port_host_self, &pset_list,
662                                     &pset_list_len)) != KERN_SUCCESS) {
663     ERROR("host_processor_sets failed: %s\n", mach_error_string(status));
664     pset_list = NULL;
665     pset_list_len = 0;
666     return -1;
667   }
668 /* #endif HAVE_THREAD_INFO */
669
670 #elif KERNEL_LINUX
671   pagesize_g = sysconf(_SC_PAGESIZE);
672   DEBUG("pagesize_g = %li; CONFIG_HZ = %i;", pagesize_g, CONFIG_HZ);
673 /* #endif KERNEL_LINUX */
674
675 #elif HAVE_LIBKVM_GETPROCS &&                                                  \
676     (HAVE_STRUCT_KINFO_PROC_FREEBSD || HAVE_STRUCT_KINFO_PROC_OPENBSD)
677   pagesize = getpagesize();
678 /* #endif HAVE_LIBKVM_GETPROCS && (HAVE_STRUCT_KINFO_PROC_FREEBSD ||
679  * HAVE_STRUCT_KINFO_PROC_OPENBSD) */
680
681 #elif HAVE_PROCINFO_H
682   pagesize = getpagesize();
683 #endif /* HAVE_PROCINFO_H */
684
685   return 0;
686 } /* int ps_init */
687
688 /* submit global state (e.g.: qty of zombies, running, etc..) */
689 static void ps_submit_state(const char *state, double value) {
690   value_list_t vl = VALUE_LIST_INIT;
691
692   vl.values = &(value_t){.gauge = value};
693   vl.values_len = 1;
694   sstrncpy(vl.plugin, "processes", sizeof(vl.plugin));
695   sstrncpy(vl.plugin_instance, "", sizeof(vl.plugin_instance));
696   sstrncpy(vl.type, "ps_state", sizeof(vl.type));
697   sstrncpy(vl.type_instance, state, sizeof(vl.type_instance));
698
699   plugin_dispatch_values(&vl);
700 }
701
702 /* submit info about specific process (e.g.: memory taken, cpu usage, etc..) */
703 static void ps_submit_proc_list(procstat_t *ps) {
704   value_list_t vl = VALUE_LIST_INIT;
705   value_t values[2];
706
707   vl.values = values;
708   sstrncpy(vl.plugin, "processes", sizeof(vl.plugin));
709   sstrncpy(vl.plugin_instance, ps->name, sizeof(vl.plugin_instance));
710
711   sstrncpy(vl.type, "ps_vm", sizeof(vl.type));
712   vl.values[0].gauge = ps->vmem_size;
713   vl.values_len = 1;
714   plugin_dispatch_values(&vl);
715
716   sstrncpy(vl.type, "ps_rss", sizeof(vl.type));
717   vl.values[0].gauge = ps->vmem_rss;
718   vl.values_len = 1;
719   plugin_dispatch_values(&vl);
720
721   sstrncpy(vl.type, "ps_data", sizeof(vl.type));
722   vl.values[0].gauge = ps->vmem_data;
723   vl.values_len = 1;
724   plugin_dispatch_values(&vl);
725
726   sstrncpy(vl.type, "ps_code", sizeof(vl.type));
727   vl.values[0].gauge = ps->vmem_code;
728   vl.values_len = 1;
729   plugin_dispatch_values(&vl);
730
731   sstrncpy(vl.type, "ps_stacksize", sizeof(vl.type));
732   vl.values[0].gauge = ps->stack_size;
733   vl.values_len = 1;
734   plugin_dispatch_values(&vl);
735
736   sstrncpy(vl.type, "ps_cputime", sizeof(vl.type));
737   vl.values[0].derive = ps->cpu_user_counter;
738   vl.values[1].derive = ps->cpu_system_counter;
739   vl.values_len = 2;
740   plugin_dispatch_values(&vl);
741
742   sstrncpy(vl.type, "ps_count", sizeof(vl.type));
743   vl.values[0].gauge = ps->num_proc;
744   vl.values[1].gauge = ps->num_lwp;
745   vl.values_len = 2;
746   plugin_dispatch_values(&vl);
747
748   sstrncpy(vl.type, "ps_pagefaults", sizeof(vl.type));
749   vl.values[0].derive = ps->vmem_minflt_counter;
750   vl.values[1].derive = ps->vmem_majflt_counter;
751   vl.values_len = 2;
752   plugin_dispatch_values(&vl);
753
754   if ((ps->io_rchar != -1) && (ps->io_wchar != -1)) {
755     sstrncpy(vl.type, "io_octets", sizeof(vl.type));
756     vl.values[0].derive = ps->io_rchar;
757     vl.values[1].derive = ps->io_wchar;
758     vl.values_len = 2;
759     plugin_dispatch_values(&vl);
760   }
761
762   if ((ps->io_syscr != -1) && (ps->io_syscw != -1)) {
763     sstrncpy(vl.type, "io_ops", sizeof(vl.type));
764     vl.values[0].derive = ps->io_syscr;
765     vl.values[1].derive = ps->io_syscw;
766     vl.values_len = 2;
767     plugin_dispatch_values(&vl);
768   }
769
770   if ((ps->io_diskr != -1) && (ps->io_diskw != -1)) {
771     sstrncpy(vl.type, "disk_octets", sizeof(vl.type));
772     vl.values[0].derive = ps->io_diskr;
773     vl.values[1].derive = ps->io_diskw;
774     vl.values_len = 2;
775     plugin_dispatch_values(&vl);
776   }
777
778   if (ps->num_fd > 0) {
779     sstrncpy(vl.type, "file_handles", sizeof(vl.type));
780     vl.values[0].gauge = ps->num_fd;
781     vl.values_len = 1;
782     plugin_dispatch_values(&vl);
783   }
784
785   if (ps->num_maps > 0) {
786     sstrncpy(vl.type, "file_handles", sizeof(vl.type));
787     sstrncpy(vl.type_instance, "mapped", sizeof(vl.type_instance));
788     vl.values[0].gauge = ps->num_maps;
789     vl.values_len = 1;
790     plugin_dispatch_values(&vl);
791   }
792
793   if ((ps->cswitch_vol != -1) && (ps->cswitch_invol != -1)) {
794     sstrncpy(vl.type, "contextswitch", sizeof(vl.type));
795     sstrncpy(vl.type_instance, "voluntary", sizeof(vl.type_instance));
796     vl.values[0].derive = ps->cswitch_vol;
797     vl.values_len = 1;
798     plugin_dispatch_values(&vl);
799
800     sstrncpy(vl.type, "contextswitch", sizeof(vl.type));
801     sstrncpy(vl.type_instance, "involuntary", sizeof(vl.type_instance));
802     vl.values[0].derive = ps->cswitch_invol;
803     vl.values_len = 1;
804     plugin_dispatch_values(&vl);
805   }
806
807   DEBUG(
808       "name = %s; num_proc = %lu; num_lwp = %lu; num_fd = %lu; num_maps = %lu; "
809       "vmem_size = %lu; vmem_rss = %lu; vmem_data = %lu; "
810       "vmem_code = %lu; "
811       "vmem_minflt_counter = %" PRIi64 "; vmem_majflt_counter = %" PRIi64 "; "
812       "cpu_user_counter = %" PRIi64 "; cpu_system_counter = %" PRIi64 "; "
813       "io_rchar = %" PRIi64 "; io_wchar = %" PRIi64 "; "
814       "io_syscr = %" PRIi64 "; io_syscw = %" PRIi64 "; "
815       "io_diskr = %" PRIi64 "; io_diskw = %" PRIi64 "; "
816       "cswitch_vol = %" PRIi64 "; cswitch_invol = %" PRIi64 ";",
817       ps->name, ps->num_proc, ps->num_lwp, ps->num_fd, ps->num_maps,
818       ps->vmem_size, ps->vmem_rss, ps->vmem_data, ps->vmem_code,
819       ps->vmem_minflt_counter, ps->vmem_majflt_counter, ps->cpu_user_counter,
820       ps->cpu_system_counter, ps->io_rchar, ps->io_wchar, ps->io_syscr,
821       ps->io_syscw, ps->io_diskr, ps->io_diskw, ps->cswitch_vol,
822       ps->cswitch_invol);
823
824 } /* void ps_submit_proc_list */
825
826 #if KERNEL_LINUX || KERNEL_SOLARIS
827 static void ps_submit_fork_rate(derive_t value) {
828   value_list_t vl = VALUE_LIST_INIT;
829
830   vl.values = &(value_t){.derive = value};
831   vl.values_len = 1;
832   sstrncpy(vl.plugin, "processes", sizeof(vl.plugin));
833   sstrncpy(vl.plugin_instance, "", sizeof(vl.plugin_instance));
834   sstrncpy(vl.type, "fork_rate", sizeof(vl.type));
835   sstrncpy(vl.type_instance, "", sizeof(vl.type_instance));
836
837   plugin_dispatch_values(&vl);
838 }
839 #endif /* KERNEL_LINUX || KERNEL_SOLARIS*/
840
841 /* ------- additional functions for KERNEL_LINUX/HAVE_THREAD_INFO ------- */
842 #if KERNEL_LINUX
843 static int ps_read_tasks_status(process_entry_t *ps) {
844   char dirname[64];
845   DIR *dh;
846   char filename[64];
847   FILE *fh;
848   struct dirent *ent;
849   derive_t cswitch_vol = 0;
850   derive_t cswitch_invol = 0;
851   char buffer[1024];
852   char *fields[8];
853   int numfields;
854
855   snprintf(dirname, sizeof(dirname), "/proc/%li/task", ps->id);
856
857   if ((dh = opendir(dirname)) == NULL) {
858     DEBUG("Failed to open directory `%s'", dirname);
859     return -1;
860   }
861
862   while ((ent = readdir(dh)) != NULL) {
863     char *tpid;
864
865     if (!isdigit((int)ent->d_name[0]))
866       continue;
867
868     tpid = ent->d_name;
869
870     if (snprintf(filename, sizeof(filename), "/proc/%li/task/%s/status", ps->id,
871                  tpid) >= sizeof(filename)) {
872       DEBUG("Filename too long: `%s'", filename);
873       continue;
874     }
875
876     if ((fh = fopen(filename, "r")) == NULL) {
877       DEBUG("Failed to open file `%s'", filename);
878       continue;
879     }
880
881     while (fgets(buffer, sizeof(buffer), fh) != NULL) {
882       derive_t tmp;
883       char *endptr;
884
885       if (strncmp(buffer, "voluntary_ctxt_switches", 23) != 0 &&
886           strncmp(buffer, "nonvoluntary_ctxt_switches", 26) != 0)
887         continue;
888
889       numfields = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
890
891       if (numfields < 2)
892         continue;
893
894       errno = 0;
895       endptr = NULL;
896       tmp = (derive_t)strtoll(fields[1], &endptr, /* base = */ 10);
897       if ((errno == 0) && (endptr != fields[1])) {
898         if (strncmp(buffer, "voluntary_ctxt_switches", 23) == 0) {
899           cswitch_vol += tmp;
900         } else if (strncmp(buffer, "nonvoluntary_ctxt_switches", 26) == 0) {
901           cswitch_invol += tmp;
902         }
903       }
904     } /* while (fgets) */
905
906     if (fclose(fh)) {
907       WARNING("processes: fclose: %s", STRERRNO);
908     }
909   }
910   closedir(dh);
911
912   ps->cswitch_vol = cswitch_vol;
913   ps->cswitch_invol = cswitch_invol;
914
915   return 0;
916 } /* int *ps_read_tasks_status */
917
918 /* Read data from /proc/pid/status */
919 static int ps_read_status(long pid, process_entry_t *ps) {
920   FILE *fh;
921   char buffer[1024];
922   char filename[64];
923   unsigned long lib = 0;
924   unsigned long exe = 0;
925   unsigned long data = 0;
926   unsigned long threads = 0;
927   char *fields[8];
928   int numfields;
929
930   snprintf(filename, sizeof(filename), "/proc/%li/status", pid);
931   if ((fh = fopen(filename, "r")) == NULL)
932     return -1;
933
934   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
935     unsigned long tmp;
936     char *endptr;
937
938     if (strncmp(buffer, "Vm", 2) != 0 && strncmp(buffer, "Threads", 7) != 0)
939       continue;
940
941     numfields = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
942
943     if (numfields < 2)
944       continue;
945
946     errno = 0;
947     endptr = NULL;
948     tmp = strtoul(fields[1], &endptr, /* base = */ 10);
949     if ((errno == 0) && (endptr != fields[1])) {
950       if (strncmp(buffer, "VmData", 6) == 0) {
951         data = tmp;
952       } else if (strncmp(buffer, "VmLib", 5) == 0) {
953         lib = tmp;
954       } else if (strncmp(buffer, "VmExe", 5) == 0) {
955         exe = tmp;
956       } else if (strncmp(buffer, "Threads", 7) == 0) {
957         threads = tmp;
958       }
959     }
960   } /* while (fgets) */
961
962   if (fclose(fh)) {
963     WARNING("processes: fclose: %s", STRERRNO);
964   }
965
966   ps->vmem_data = data * 1024;
967   ps->vmem_code = (exe + lib) * 1024;
968   if (threads != 0)
969     ps->num_lwp = threads;
970
971   return 0;
972 } /* int *ps_read_status */
973
974 static int ps_read_io(process_entry_t *ps) {
975   FILE *fh;
976   char buffer[1024];
977   char filename[64];
978
979   char *fields[8];
980   int numfields;
981
982   snprintf(filename, sizeof(filename), "/proc/%li/io", ps->id);
983   if ((fh = fopen(filename, "r")) == NULL) {
984     DEBUG("ps_read_io: Failed to open file `%s'", filename);
985     return -1;
986   }
987
988   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
989     derive_t *val = NULL;
990     long long tmp;
991     char *endptr;
992
993     if (strncasecmp(buffer, "rchar:", 6) == 0)
994       val = &(ps->io_rchar);
995     else if (strncasecmp(buffer, "wchar:", 6) == 0)
996       val = &(ps->io_wchar);
997     else if (strncasecmp(buffer, "syscr:", 6) == 0)
998       val = &(ps->io_syscr);
999     else if (strncasecmp(buffer, "syscw:", 6) == 0)
1000       val = &(ps->io_syscw);
1001     else if (strncasecmp(buffer, "read_bytes:", 11) == 0)
1002       val = &(ps->io_diskr);
1003     else if (strncasecmp(buffer, "write_bytes:", 12) == 0)
1004       val = &(ps->io_diskw);
1005     else
1006       continue;
1007
1008     numfields = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
1009
1010     if (numfields < 2)
1011       continue;
1012
1013     errno = 0;
1014     endptr = NULL;
1015     tmp = strtoll(fields[1], &endptr, /* base = */ 10);
1016     if ((errno != 0) || (endptr == fields[1]))
1017       *val = -1;
1018     else
1019       *val = (derive_t)tmp;
1020   } /* while (fgets) */
1021
1022   if (fclose(fh)) {
1023     WARNING("processes: fclose: %s", STRERRNO);
1024   }
1025   return 0;
1026 } /* int ps_read_io (...) */
1027
1028 static int ps_count_maps(pid_t pid) {
1029   FILE *fh;
1030   char buffer[1024];
1031   char filename[64];
1032   int count = 0;
1033
1034   snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
1035   if ((fh = fopen(filename, "r")) == NULL) {
1036     DEBUG("ps_count_maps: Failed to open file `%s'", filename);
1037     return -1;
1038   }
1039
1040   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
1041     if (strchr(buffer, '\n')) {
1042       count++;
1043     }
1044   } /* while (fgets) */
1045
1046   if (fclose(fh)) {
1047     WARNING("processes: fclose: %s", STRERRNO);
1048   }
1049   return count;
1050 } /* int ps_count_maps (...) */
1051
1052 static int ps_count_fd(int pid) {
1053   char dirname[64];
1054   DIR *dh;
1055   struct dirent *ent;
1056   int count = 0;
1057
1058   snprintf(dirname, sizeof(dirname), "/proc/%i/fd", pid);
1059
1060   if ((dh = opendir(dirname)) == NULL) {
1061     DEBUG("Failed to open directory `%s'", dirname);
1062     return -1;
1063   }
1064   while ((ent = readdir(dh)) != NULL) {
1065     if (!isdigit((int)ent->d_name[0]))
1066       continue;
1067     else
1068       count++;
1069   }
1070   closedir(dh);
1071
1072   return (count >= 1) ? count : 1;
1073 } /* int ps_count_fd (pid) */
1074
1075 static void ps_fill_details(const procstat_t *ps, process_entry_t *entry) {
1076   if (entry->has_io == 0) {
1077     ps_read_io(entry);
1078     entry->has_io = 1;
1079   }
1080
1081   if (ps->report_ctx_switch) {
1082     if (entry->has_cswitch == 0) {
1083       ps_read_tasks_status(entry);
1084       entry->has_cswitch = 1;
1085     }
1086   }
1087
1088   if (ps->report_maps_num) {
1089     int num_maps;
1090     if (entry->has_maps == 0 && (num_maps = ps_count_maps(entry->id)) > 0) {
1091       entry->num_maps = num_maps;
1092     }
1093     entry->has_maps = 1;
1094   }
1095
1096   if (ps->report_fd_num) {
1097     int num_fd;
1098     if (entry->has_fd == 0 && (num_fd = ps_count_fd(entry->id)) > 0) {
1099       entry->num_fd = num_fd;
1100     }
1101     entry->has_fd = 1;
1102   }
1103 } /* void ps_fill_details (...) */
1104
1105 static int ps_read_process(long pid, process_entry_t *ps, char *state) {
1106   char filename[64];
1107   char buffer[1024];
1108
1109   char *fields[64];
1110   char fields_len;
1111
1112   size_t buffer_len;
1113
1114   char *buffer_ptr;
1115   size_t name_start_pos;
1116   size_t name_end_pos;
1117   size_t name_len;
1118
1119   derive_t cpu_user_counter;
1120   derive_t cpu_system_counter;
1121   long long unsigned vmem_size;
1122   long long unsigned vmem_rss;
1123   long long unsigned stack_size;
1124
1125   ssize_t status;
1126
1127   snprintf(filename, sizeof(filename), "/proc/%li/stat", pid);
1128
1129   status = read_file_contents(filename, buffer, sizeof(buffer) - 1);
1130   if (status <= 0)
1131     return -1;
1132   buffer_len = (size_t)status;
1133   buffer[buffer_len] = 0;
1134
1135   /* The name of the process is enclosed in parens. Since the name can
1136    * contain parens itself, spaces, numbers and pretty much everything
1137    * else, use these to determine the process name. We don't use
1138    * strchr(3) and strrchr(3) to avoid pointer arithmetic which would
1139    * otherwise be required to determine name_len. */
1140   name_start_pos = 0;
1141   while (name_start_pos < buffer_len && buffer[name_start_pos] != '(')
1142     name_start_pos++;
1143
1144   name_end_pos = buffer_len;
1145   while (name_end_pos > 0 && buffer[name_end_pos] != ')')
1146     name_end_pos--;
1147
1148   /* Either '(' or ')' is not found or they are in the wrong order.
1149    * Anyway, something weird that shouldn't happen ever. */
1150   if (name_start_pos >= name_end_pos) {
1151     ERROR("processes plugin: name_start_pos = %zu >= name_end_pos = %zu",
1152           name_start_pos, name_end_pos);
1153     return -1;
1154   }
1155
1156   name_len = (name_end_pos - name_start_pos) - 1;
1157   if (name_len >= sizeof(ps->name))
1158     name_len = sizeof(ps->name) - 1;
1159
1160   sstrncpy(ps->name, &buffer[name_start_pos + 1], name_len + 1);
1161
1162   if ((buffer_len - name_end_pos) < 2)
1163     return -1;
1164   buffer_ptr = &buffer[name_end_pos + 2];
1165
1166   fields_len = strsplit(buffer_ptr, fields, STATIC_ARRAY_SIZE(fields));
1167   if (fields_len < 22) {
1168     DEBUG("processes plugin: ps_read_process (pid = %li):"
1169           " `%s' has only %i fields..",
1170           pid, filename, fields_len);
1171     return -1;
1172   }
1173
1174   *state = fields[0][0];
1175
1176   if (*state == 'Z') {
1177     ps->num_lwp = 0;
1178     ps->num_proc = 0;
1179   } else {
1180     ps->num_lwp = strtoul(fields[17], /* endptr = */ NULL, /* base = */ 10);
1181     if ((ps_read_status(pid, ps)) != 0) {
1182       /* No VMem data */
1183       ps->vmem_data = -1;
1184       ps->vmem_code = -1;
1185       DEBUG("ps_read_process: did not get vmem data for pid %li", pid);
1186     }
1187     if (ps->num_lwp == 0)
1188       ps->num_lwp = 1;
1189     ps->num_proc = 1;
1190   }
1191
1192   /* Leave the rest at zero if this is only a zombi */
1193   if (ps->num_proc == 0) {
1194     DEBUG("processes plugin: This is only a zombie: pid = %li; "
1195           "name = %s;",
1196           pid, ps->name);
1197     return 0;
1198   }
1199
1200   cpu_user_counter = atoll(fields[11]);
1201   cpu_system_counter = atoll(fields[12]);
1202   vmem_size = atoll(fields[20]);
1203   vmem_rss = atoll(fields[21]);
1204   ps->vmem_minflt_counter = atol(fields[7]);
1205   ps->vmem_majflt_counter = atol(fields[9]);
1206
1207   {
1208     unsigned long long stack_start = atoll(fields[25]);
1209     unsigned long long stack_ptr = atoll(fields[26]);
1210
1211     stack_size = (stack_start > stack_ptr) ? stack_start - stack_ptr
1212                                            : stack_ptr - stack_start;
1213   }
1214
1215   /* Convert jiffies to useconds */
1216   cpu_user_counter = cpu_user_counter * 1000000 / CONFIG_HZ;
1217   cpu_system_counter = cpu_system_counter * 1000000 / CONFIG_HZ;
1218   vmem_rss = vmem_rss * pagesize_g;
1219
1220   ps->cpu_user_counter = cpu_user_counter;
1221   ps->cpu_system_counter = cpu_system_counter;
1222   ps->vmem_size = (unsigned long)vmem_size;
1223   ps->vmem_rss = (unsigned long)vmem_rss;
1224   ps->stack_size = (unsigned long)stack_size;
1225
1226   /* no data by default. May be filled by ps_fill_details () */
1227   ps->io_rchar = -1;
1228   ps->io_wchar = -1;
1229   ps->io_syscr = -1;
1230   ps->io_syscw = -1;
1231   ps->io_diskr = -1;
1232   ps->io_diskw = -1;
1233
1234   ps->cswitch_vol = -1;
1235   ps->cswitch_invol = -1;
1236
1237   /* success */
1238   return 0;
1239 } /* int ps_read_process (...) */
1240
1241 static char *ps_get_cmdline(long pid, char *name, char *buf, size_t buf_len) {
1242   char *buf_ptr;
1243   size_t len;
1244
1245   char file[PATH_MAX];
1246   int fd;
1247
1248   size_t n;
1249
1250   if ((pid < 1) || (NULL == buf) || (buf_len < 2))
1251     return NULL;
1252
1253   snprintf(file, sizeof(file), "/proc/%li/cmdline", pid);
1254
1255   errno = 0;
1256   fd = open(file, O_RDONLY);
1257   if (fd < 0) {
1258     /* ENOENT means the process exited while we were handling it.
1259      * Don't complain about this, it only fills the logs. */
1260     if (errno != ENOENT)
1261       WARNING("processes plugin: Failed to open `%s': %s.", file, STRERRNO);
1262     return NULL;
1263   }
1264
1265   buf_ptr = buf;
1266   len = buf_len;
1267
1268   n = 0;
1269
1270   while (42) {
1271     ssize_t status;
1272
1273     status = read(fd, (void *)buf_ptr, len);
1274
1275     if (status < 0) {
1276
1277       if ((EAGAIN == errno) || (EINTR == errno))
1278         continue;
1279
1280       WARNING("processes plugin: Failed to read from `%s': %s.", file,
1281               STRERRNO);
1282       close(fd);
1283       return NULL;
1284     }
1285
1286     n += status;
1287
1288     if (status == 0)
1289       break;
1290
1291     buf_ptr += status;
1292     len -= status;
1293
1294     if (len == 0)
1295       break;
1296   }
1297
1298   close(fd);
1299
1300   if (0 == n) {
1301     /* cmdline not available; e.g. kernel thread, zombie */
1302     if (NULL == name)
1303       return NULL;
1304
1305     snprintf(buf, buf_len, "[%s]", name);
1306     return buf;
1307   }
1308
1309   assert(n <= buf_len);
1310
1311   if (n == buf_len)
1312     --n;
1313   buf[n] = '\0';
1314
1315   --n;
1316   /* remove trailing whitespace */
1317   while ((n > 0) && (isspace(buf[n]) || ('\0' == buf[n]))) {
1318     buf[n] = '\0';
1319     --n;
1320   }
1321
1322   /* arguments are separated by '\0' in /proc/<pid>/cmdline */
1323   while (n > 0) {
1324     if ('\0' == buf[n])
1325       buf[n] = ' ';
1326     --n;
1327   }
1328   return buf;
1329 } /* char *ps_get_cmdline (...) */
1330
1331 static int read_fork_rate(void) {
1332   FILE *proc_stat;
1333   char buffer[1024];
1334   value_t value;
1335   _Bool value_valid = 0;
1336
1337   proc_stat = fopen("/proc/stat", "r");
1338   if (proc_stat == NULL) {
1339     ERROR("processes plugin: fopen (/proc/stat) failed: %s", STRERRNO);
1340     return -1;
1341   }
1342
1343   while (fgets(buffer, sizeof(buffer), proc_stat) != NULL) {
1344     int status;
1345     char *fields[3];
1346     int fields_num;
1347
1348     fields_num = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
1349     if (fields_num != 2)
1350       continue;
1351
1352     if (strcmp("processes", fields[0]) != 0)
1353       continue;
1354
1355     status = parse_value(fields[1], &value, DS_TYPE_DERIVE);
1356     if (status == 0)
1357       value_valid = 1;
1358
1359     break;
1360   }
1361   fclose(proc_stat);
1362
1363   if (!value_valid)
1364     return -1;
1365
1366   ps_submit_fork_rate(value.derive);
1367   return 0;
1368 }
1369 #endif /*KERNEL_LINUX */
1370
1371 #if KERNEL_SOLARIS
1372 static char *ps_get_cmdline(long pid,
1373                             char *name __attribute__((unused)), /* {{{ */
1374                             char *buffer, size_t buffer_size) {
1375   char path[PATH_MAX];
1376   psinfo_t info;
1377   ssize_t status;
1378
1379   snprintf(path, sizeof(path), "/proc/%li/psinfo", pid);
1380
1381   status = read_file_contents(path, (void *)&info, sizeof(info));
1382   if ((status < 0) || (((size_t)status) != sizeof(info))) {
1383     ERROR("processes plugin: Unexpected return value "
1384           "while reading \"%s\": "
1385           "Returned %zd but expected %zu.",
1386           path, status, buffer_size);
1387     return NULL;
1388   }
1389
1390   info.pr_psargs[sizeof(info.pr_psargs) - 1] = 0;
1391   sstrncpy(buffer, info.pr_psargs, buffer_size);
1392
1393   return buffer;
1394 } /* }}} int ps_get_cmdline */
1395
1396 /*
1397  * Reads process information on the Solaris OS. The information comes mainly
1398  * from
1399  * /proc/PID/status, /proc/PID/psinfo and /proc/PID/usage
1400  * The values for input and ouput chars are calculated "by hand"
1401  * Added a few "solaris" specific process states as well
1402  */
1403 static int ps_read_process(long pid, process_entry_t *ps, char *state) {
1404   char filename[64];
1405   char f_psinfo[64], f_usage[64];
1406   char *buffer;
1407
1408   pstatus_t *myStatus;
1409   psinfo_t *myInfo;
1410   prusage_t *myUsage;
1411
1412   snprintf(filename, sizeof(filename), "/proc/%li/status", pid);
1413   snprintf(f_psinfo, sizeof(f_psinfo), "/proc/%li/psinfo", pid);
1414   snprintf(f_usage, sizeof(f_usage), "/proc/%li/usage", pid);
1415
1416   buffer = calloc(1, sizeof(pstatus_t));
1417   read_file_contents(filename, buffer, sizeof(pstatus_t));
1418   myStatus = (pstatus_t *)buffer;
1419
1420   buffer = calloc(1, sizeof(psinfo_t));
1421   read_file_contents(f_psinfo, buffer, sizeof(psinfo_t));
1422   myInfo = (psinfo_t *)buffer;
1423
1424   buffer = calloc(1, sizeof(prusage_t));
1425   read_file_contents(f_usage, buffer, sizeof(prusage_t));
1426   myUsage = (prusage_t *)buffer;
1427
1428   sstrncpy(ps->name, myInfo->pr_fname, sizeof(myInfo->pr_fname));
1429   ps->num_lwp = myStatus->pr_nlwp;
1430   if (myInfo->pr_wstat != 0) {
1431     ps->num_proc = 0;
1432     ps->num_lwp = 0;
1433     *state = (char)'Z';
1434
1435     sfree(myStatus);
1436     sfree(myInfo);
1437     sfree(myUsage);
1438     return 0;
1439   } else {
1440     ps->num_proc = 1;
1441     ps->num_lwp = myInfo->pr_nlwp;
1442   }
1443
1444   /*
1445    * Convert system time and user time from nanoseconds to microseconds
1446    * for compatibility with the linux module
1447    */
1448   ps->cpu_system_counter = myStatus->pr_stime.tv_nsec / 1000;
1449   ps->cpu_user_counter = myStatus->pr_utime.tv_nsec / 1000;
1450
1451   /*
1452    * Convert rssize from KB to bytes to be consistent w/ the linux module
1453    */
1454   ps->vmem_rss = myInfo->pr_rssize * 1024;
1455   ps->vmem_size = myInfo->pr_size * 1024;
1456   ps->vmem_minflt_counter = myUsage->pr_minf;
1457   ps->vmem_majflt_counter = myUsage->pr_majf;
1458
1459   /*
1460    * TODO: Data and code segment calculations for Solaris
1461    */
1462
1463   ps->vmem_data = -1;
1464   ps->vmem_code = -1;
1465   ps->stack_size = myStatus->pr_stksize;
1466
1467   /*
1468    * TODO: File descriptor count for Solaris
1469    */
1470   ps->num_fd = 0;
1471
1472   /* Number of memory mappings */
1473   ps->num_maps = 0;
1474
1475   /*
1476    * Calculating input/ouput chars
1477    * Formula used is total chars / total blocks => chars/block
1478    * then convert input/output blocks to chars
1479    */
1480   ulong_t tot_chars = myUsage->pr_ioch;
1481   ulong_t tot_blocks = myUsage->pr_inblk + myUsage->pr_oublk;
1482   ulong_t chars_per_block = 1;
1483   if (tot_blocks != 0)
1484     chars_per_block = tot_chars / tot_blocks;
1485   ps->io_rchar = myUsage->pr_inblk * chars_per_block;
1486   ps->io_wchar = myUsage->pr_oublk * chars_per_block;
1487   ps->io_syscr = myUsage->pr_sysc;
1488   ps->io_syscw = myUsage->pr_sysc;
1489   ps->io_diskr = -1;
1490   ps->io_diskw = -1;
1491
1492   /*
1493    * TODO: context switch counters for Solaris
1494 */
1495   ps->cswitch_vol = -1;
1496   ps->cswitch_invol = -1;
1497
1498   /*
1499    * TODO: Find way of setting BLOCKED and PAGING status
1500    */
1501
1502   *state = (char)'R';
1503   if (myStatus->pr_flags & PR_ASLEEP)
1504     *state = (char)'S';
1505   else if (myStatus->pr_flags & PR_STOPPED)
1506     *state = (char)'T';
1507   else if (myStatus->pr_flags & PR_DETACH)
1508     *state = (char)'E';
1509   else if (myStatus->pr_flags & PR_DAEMON)
1510     *state = (char)'A';
1511   else if (myStatus->pr_flags & PR_ISSYS)
1512     *state = (char)'Y';
1513   else if (myStatus->pr_flags & PR_ORPHAN)
1514     *state = (char)'O';
1515
1516   sfree(myStatus);
1517   sfree(myInfo);
1518   sfree(myUsage);
1519
1520   return 0;
1521 }
1522
1523 /*
1524  * Reads the number of threads created since the last reboot. On Solaris these
1525  * are retrieved from kstat (module cpu, name sys, class misc, stat nthreads).
1526  * The result is the sum for all the threads created on each cpu
1527  */
1528 static int read_fork_rate(void) {
1529   extern kstat_ctl_t *kc;
1530   derive_t result = 0;
1531
1532   if (kc == NULL)
1533     return -1;
1534
1535   for (kstat_t *ksp_chain = kc->kc_chain; ksp_chain != NULL;
1536        ksp_chain = ksp_chain->ks_next) {
1537     if ((strcmp(ksp_chain->ks_module, "cpu") == 0) &&
1538         (strcmp(ksp_chain->ks_name, "sys") == 0) &&
1539         (strcmp(ksp_chain->ks_class, "misc") == 0)) {
1540       long long tmp;
1541
1542       kstat_read(kc, ksp_chain, NULL);
1543
1544       tmp = get_kstat_value(ksp_chain, "nthreads");
1545       if (tmp != -1LL)
1546         result += tmp;
1547     }
1548   }
1549
1550   ps_submit_fork_rate(result);
1551   return 0;
1552 }
1553 #endif /* KERNEL_SOLARIS */
1554
1555 #if HAVE_THREAD_INFO
1556 static int mach_get_task_name(task_t t, int *pid, char *name,
1557                               size_t name_max_len) {
1558   int mib[4];
1559
1560   struct kinfo_proc kp;
1561   size_t kp_size;
1562
1563   mib[0] = CTL_KERN;
1564   mib[1] = KERN_PROC;
1565   mib[2] = KERN_PROC_PID;
1566
1567   if (pid_for_task(t, pid) != KERN_SUCCESS)
1568     return -1;
1569   mib[3] = *pid;
1570
1571   kp_size = sizeof(kp);
1572   if (sysctl(mib, 4, &kp, &kp_size, NULL, 0) != 0)
1573     return -1;
1574
1575   if (name_max_len > (MAXCOMLEN + 1))
1576     name_max_len = MAXCOMLEN + 1;
1577
1578   strncpy(name, kp.kp_proc.p_comm, name_max_len - 1);
1579   name[name_max_len - 1] = '\0';
1580
1581   DEBUG("pid = %i; name = %s;", *pid, name);
1582
1583   /* We don't do the special handling for `p_comm == "LaunchCFMApp"' as
1584    * `top' does it, because it is a lot of work and only used when
1585    * debugging. -octo */
1586
1587   return 0;
1588 }
1589 #endif /* HAVE_THREAD_INFO */
1590 /* ------- end of additional functions for KERNEL_LINUX/HAVE_THREAD_INFO -------
1591  */
1592
1593 /* do actual readings from kernel */
1594 static int ps_read(void) {
1595 #if HAVE_THREAD_INFO
1596   kern_return_t status;
1597
1598   processor_set_t port_pset_priv;
1599
1600   task_array_t task_list;
1601   mach_msg_type_number_t task_list_len;
1602
1603   int task_pid;
1604   char task_name[MAXCOMLEN + 1];
1605
1606   thread_act_array_t thread_list;
1607   mach_msg_type_number_t thread_list_len;
1608   thread_basic_info_data_t thread_data;
1609   mach_msg_type_number_t thread_data_len;
1610
1611   int running = 0;
1612   int sleeping = 0;
1613   int zombies = 0;
1614   int stopped = 0;
1615   int blocked = 0;
1616
1617   procstat_t *ps;
1618   process_entry_t pse;
1619
1620   ps_list_reset();
1621
1622   /*
1623    * The Mach-concept is a little different from the traditional UNIX
1624    * concept: All the work is done in threads. Threads are contained in
1625    * `tasks'. Therefore, `task status' doesn't make much sense, since
1626    * it's actually a `thread status'.
1627    * Tasks are assigned to sets of processors, so that's where you go to
1628    * get a list.
1629    */
1630   for (mach_msg_type_number_t pset = 0; pset < pset_list_len; pset++) {
1631     if ((status = host_processor_set_priv(port_host_self, pset_list[pset],
1632                                           &port_pset_priv)) != KERN_SUCCESS) {
1633       ERROR("host_processor_set_priv failed: %s\n", mach_error_string(status));
1634       continue;
1635     }
1636
1637     if ((status = processor_set_tasks(port_pset_priv, &task_list,
1638                                       &task_list_len)) != KERN_SUCCESS) {
1639       ERROR("processor_set_tasks failed: %s\n", mach_error_string(status));
1640       mach_port_deallocate(port_task_self, port_pset_priv);
1641       continue;
1642     }
1643
1644     for (mach_msg_type_number_t task = 0; task < task_list_len; task++) {
1645       ps = NULL;
1646       if (mach_get_task_name(task_list[task], &task_pid, task_name,
1647                              PROCSTAT_NAME_LEN) == 0) {
1648         /* search for at least one match */
1649         for (ps = list_head_g; ps != NULL; ps = ps->next)
1650           /* FIXME: cmdline should be here instead of NULL */
1651           if (ps_list_match(task_name, NULL, ps) == 1)
1652             break;
1653       }
1654
1655       /* Collect more detailed statistics for this process */
1656       if (ps != NULL) {
1657         task_basic_info_data_t task_basic_info;
1658         mach_msg_type_number_t task_basic_info_len;
1659         task_events_info_data_t task_events_info;
1660         mach_msg_type_number_t task_events_info_len;
1661         task_absolutetime_info_data_t task_absolutetime_info;
1662         mach_msg_type_number_t task_absolutetime_info_len;
1663
1664         memset(&pse, '\0', sizeof(pse));
1665         pse.id = task_pid;
1666
1667         task_basic_info_len = TASK_BASIC_INFO_COUNT;
1668         status = task_info(task_list[task], TASK_BASIC_INFO,
1669                            (task_info_t)&task_basic_info, &task_basic_info_len);
1670         if (status != KERN_SUCCESS) {
1671           ERROR("task_info failed: %s", mach_error_string(status));
1672           continue; /* with next thread_list */
1673         }
1674
1675         task_events_info_len = TASK_EVENTS_INFO_COUNT;
1676         status =
1677             task_info(task_list[task], TASK_EVENTS_INFO,
1678                       (task_info_t)&task_events_info, &task_events_info_len);
1679         if (status != KERN_SUCCESS) {
1680           ERROR("task_info failed: %s", mach_error_string(status));
1681           continue; /* with next thread_list */
1682         }
1683
1684         task_absolutetime_info_len = TASK_ABSOLUTETIME_INFO_COUNT;
1685         status = task_info(task_list[task], TASK_ABSOLUTETIME_INFO,
1686                            (task_info_t)&task_absolutetime_info,
1687                            &task_absolutetime_info_len);
1688         if (status != KERN_SUCCESS) {
1689           ERROR("task_info failed: %s", mach_error_string(status));
1690           continue; /* with next thread_list */
1691         }
1692
1693         pse.num_proc++;
1694         pse.vmem_size = task_basic_info.virtual_size;
1695         pse.vmem_rss = task_basic_info.resident_size;
1696         /* Does not seem to be easily exposed */
1697         pse.vmem_data = 0;
1698         pse.vmem_code = 0;
1699
1700         pse.io_rchar = -1;
1701         pse.io_wchar = -1;
1702         pse.io_syscr = -1;
1703         pse.io_syscw = -1;
1704         pse.io_diskr = -1;
1705         pse.io_diskw = -1;
1706
1707         /* File descriptor count not implemented */
1708         pse.num_fd = 0;
1709
1710         /* Number of memory mappings */
1711         pse.num_maps = 0;
1712
1713         pse.vmem_minflt_counter = task_events_info.cow_faults;
1714         pse.vmem_majflt_counter = task_events_info.faults;
1715
1716         pse.cpu_user_counter = task_absolutetime_info.total_user;
1717         pse.cpu_system_counter = task_absolutetime_info.total_system;
1718
1719         /* context switch counters not implemented */
1720         pse.cswitch_vol = -1;
1721         pse.cswitch_invol = -1;
1722       }
1723
1724       status = task_threads(task_list[task], &thread_list, &thread_list_len);
1725       if (status != KERN_SUCCESS) {
1726         /* Apple's `top' treats this case a zombie. It
1727          * makes sense to some extend: A `zombie'
1728          * thread is nonsense, since the task/process
1729          * is dead. */
1730         zombies++;
1731         DEBUG("task_threads failed: %s", mach_error_string(status));
1732         if (task_list[task] != port_task_self)
1733           mach_port_deallocate(port_task_self, task_list[task]);
1734         continue; /* with next task_list */
1735       }
1736
1737       for (mach_msg_type_number_t thread = 0; thread < thread_list_len;
1738            thread++) {
1739         thread_data_len = THREAD_BASIC_INFO_COUNT;
1740         status = thread_info(thread_list[thread], THREAD_BASIC_INFO,
1741                              (thread_info_t)&thread_data, &thread_data_len);
1742         if (status != KERN_SUCCESS) {
1743           ERROR("thread_info failed: %s", mach_error_string(status));
1744           if (task_list[task] != port_task_self)
1745             mach_port_deallocate(port_task_self, thread_list[thread]);
1746           continue; /* with next thread_list */
1747         }
1748
1749         if (ps != NULL)
1750           pse.num_lwp++;
1751
1752         switch (thread_data.run_state) {
1753         case TH_STATE_RUNNING:
1754           running++;
1755           break;
1756         case TH_STATE_STOPPED:
1757         /* What exactly is `halted'? */
1758         case TH_STATE_HALTED:
1759           stopped++;
1760           break;
1761         case TH_STATE_WAITING:
1762           sleeping++;
1763           break;
1764         case TH_STATE_UNINTERRUPTIBLE:
1765           blocked++;
1766           break;
1767         /* There is no `zombie' case here,
1768          * since there are no zombie-threads.
1769          * There's only zombie tasks, which are
1770          * handled above. */
1771         default:
1772           WARNING("Unknown thread status: %i", thread_data.run_state);
1773           break;
1774         } /* switch (thread_data.run_state) */
1775
1776         if (task_list[task] != port_task_self) {
1777           status = mach_port_deallocate(port_task_self, thread_list[thread]);
1778           if (status != KERN_SUCCESS)
1779             ERROR("mach_port_deallocate failed: %s", mach_error_string(status));
1780         }
1781       } /* for (thread_list) */
1782
1783       if ((status = vm_deallocate(port_task_self, (vm_address_t)thread_list,
1784                                   thread_list_len * sizeof(thread_act_t))) !=
1785           KERN_SUCCESS) {
1786         ERROR("vm_deallocate failed: %s", mach_error_string(status));
1787       }
1788       thread_list = NULL;
1789       thread_list_len = 0;
1790
1791       /* Only deallocate the task port, if it isn't our own.
1792        * Don't know what would happen in that case, but this
1793        * is what Apple's top does.. ;) */
1794       if (task_list[task] != port_task_self) {
1795         status = mach_port_deallocate(port_task_self, task_list[task]);
1796         if (status != KERN_SUCCESS)
1797           ERROR("mach_port_deallocate failed: %s", mach_error_string(status));
1798       }
1799
1800       if (ps != NULL)
1801         /* FIXME: cmdline should be here instead of NULL */
1802         ps_list_add(task_name, NULL, &pse);
1803     } /* for (task_list) */
1804
1805     if ((status = vm_deallocate(port_task_self, (vm_address_t)task_list,
1806                                 task_list_len * sizeof(task_t))) !=
1807         KERN_SUCCESS) {
1808       ERROR("vm_deallocate failed: %s", mach_error_string(status));
1809     }
1810     task_list = NULL;
1811     task_list_len = 0;
1812
1813     if ((status = mach_port_deallocate(port_task_self, port_pset_priv)) !=
1814         KERN_SUCCESS) {
1815       ERROR("mach_port_deallocate failed: %s", mach_error_string(status));
1816     }
1817   } /* for (pset_list) */
1818
1819   ps_submit_state("running", running);
1820   ps_submit_state("sleeping", sleeping);
1821   ps_submit_state("zombies", zombies);
1822   ps_submit_state("stopped", stopped);
1823   ps_submit_state("blocked", blocked);
1824
1825   for (ps = list_head_g; ps != NULL; ps = ps->next)
1826     ps_submit_proc_list(ps);
1827 /* #endif HAVE_THREAD_INFO */
1828
1829 #elif KERNEL_LINUX
1830   int running = 0;
1831   int sleeping = 0;
1832   int zombies = 0;
1833   int stopped = 0;
1834   int paging = 0;
1835   int blocked = 0;
1836
1837   struct dirent *ent;
1838   DIR *proc;
1839   long pid;
1840
1841   char cmdline[CMDLINE_BUFFER_SIZE];
1842
1843   int status;
1844   process_entry_t pse;
1845   char state;
1846
1847   running = sleeping = zombies = stopped = paging = blocked = 0;
1848   ps_list_reset();
1849
1850   if ((proc = opendir("/proc")) == NULL) {
1851     ERROR("Cannot open `/proc': %s", STRERRNO);
1852     return -1;
1853   }
1854
1855   while ((ent = readdir(proc)) != NULL) {
1856     if (!isdigit(ent->d_name[0]))
1857       continue;
1858
1859     if ((pid = atol(ent->d_name)) < 1)
1860       continue;
1861
1862     memset(&pse, 0, sizeof(pse));
1863     pse.id = pid;
1864
1865     status = ps_read_process(pid, &pse, &state);
1866     if (status != 0) {
1867       DEBUG("ps_read_process failed: %i", status);
1868       continue;
1869     }
1870
1871     switch (state) {
1872     case 'R':
1873       running++;
1874       break;
1875     case 'S':
1876       sleeping++;
1877       break;
1878     case 'D':
1879       blocked++;
1880       break;
1881     case 'Z':
1882       zombies++;
1883       break;
1884     case 'T':
1885       stopped++;
1886       break;
1887     case 'W':
1888       paging++;
1889       break;
1890     }
1891
1892     ps_list_add(pse.name,
1893                 ps_get_cmdline(pid, pse.name, cmdline, sizeof(cmdline)), &pse);
1894   }
1895
1896   closedir(proc);
1897
1898   ps_submit_state("running", running);
1899   ps_submit_state("sleeping", sleeping);
1900   ps_submit_state("zombies", zombies);
1901   ps_submit_state("stopped", stopped);
1902   ps_submit_state("paging", paging);
1903   ps_submit_state("blocked", blocked);
1904
1905   for (procstat_t *ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
1906     ps_submit_proc_list(ps_ptr);
1907
1908   read_fork_rate();
1909 /* #endif KERNEL_LINUX */
1910
1911 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
1912   int running = 0;
1913   int sleeping = 0;
1914   int zombies = 0;
1915   int stopped = 0;
1916   int blocked = 0;
1917   int idle = 0;
1918   int wait = 0;
1919
1920   kvm_t *kd;
1921   char errbuf[_POSIX2_LINE_MAX];
1922   struct kinfo_proc *procs; /* array of processes */
1923   struct kinfo_proc *proc_ptr = NULL;
1924   int count; /* returns number of processes */
1925
1926   process_entry_t pse;
1927
1928   ps_list_reset();
1929
1930   /* Open the kvm interface, get a descriptor */
1931   kd = kvm_openfiles(NULL, "/dev/null", NULL, 0, errbuf);
1932   if (kd == NULL) {
1933     ERROR("processes plugin: Cannot open kvm interface: %s", errbuf);
1934     return 0;
1935   }
1936
1937   /* Get the list of processes. */
1938   procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, &count);
1939   if (procs == NULL) {
1940     ERROR("processes plugin: Cannot get kvm processes list: %s",
1941           kvm_geterr(kd));
1942     kvm_close(kd);
1943     return 0;
1944   }
1945
1946   /* Iterate through the processes in kinfo_proc */
1947   for (int i = 0; i < count; i++) {
1948     /* Create only one process list entry per _process_, i.e.
1949      * filter out threads (duplicate PID entries). */
1950     if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid)) {
1951       char cmdline[CMDLINE_BUFFER_SIZE] = "";
1952       _Bool have_cmdline = 0;
1953
1954       proc_ptr = &(procs[i]);
1955       /* Don't probe system processes and processes without arguments */
1956       if (((procs[i].ki_flag & P_SYSTEM) == 0) && (procs[i].ki_args != NULL)) {
1957         char **argv;
1958         int argc;
1959         int status;
1960
1961         /* retrieve the arguments */
1962         argv = kvm_getargv(kd, proc_ptr, /* nchr = */ 0);
1963         argc = 0;
1964         if ((argv != NULL) && (argv[0] != NULL)) {
1965           while (argv[argc] != NULL)
1966             argc++;
1967
1968           status = strjoin(cmdline, sizeof(cmdline), argv, argc, " ");
1969           if (status < 0)
1970             WARNING("processes plugin: Command line did not fit into buffer.");
1971           else
1972             have_cmdline = 1;
1973         }
1974       } /* if (process has argument list) */
1975
1976       memset(&pse, 0, sizeof(pse));
1977       pse.id = procs[i].ki_pid;
1978
1979       pse.num_proc = 1;
1980       pse.num_lwp = procs[i].ki_numthreads;
1981
1982       pse.vmem_size = procs[i].ki_size;
1983       pse.vmem_rss = procs[i].ki_rssize * pagesize;
1984       pse.vmem_data = procs[i].ki_dsize * pagesize;
1985       pse.vmem_code = procs[i].ki_tsize * pagesize;
1986       pse.stack_size = procs[i].ki_ssize * pagesize;
1987       pse.vmem_minflt_counter = procs[i].ki_rusage.ru_minflt;
1988       pse.vmem_majflt_counter = procs[i].ki_rusage.ru_majflt;
1989
1990       pse.cpu_user_counter = 0;
1991       pse.cpu_system_counter = 0;
1992       /*
1993        * The u-area might be swapped out, and we can't get
1994        * at it because we have a crashdump and no swap.
1995        * If it's here fill in these fields, otherwise, just
1996        * leave them 0.
1997        */
1998       if (procs[i].ki_flag & P_INMEM) {
1999         pse.cpu_user_counter = procs[i].ki_rusage.ru_utime.tv_usec +
2000                                (1000000lu * procs[i].ki_rusage.ru_utime.tv_sec);
2001         pse.cpu_system_counter =
2002             procs[i].ki_rusage.ru_stime.tv_usec +
2003             (1000000lu * procs[i].ki_rusage.ru_stime.tv_sec);
2004       }
2005
2006       /* no I/O data */
2007       pse.io_rchar = -1;
2008       pse.io_wchar = -1;
2009       pse.io_syscr = -1;
2010       pse.io_syscw = -1;
2011       pse.io_diskr = -1;
2012       pse.io_diskw = -1;
2013
2014       /* file descriptor count not implemented */
2015       pse.num_fd = 0;
2016
2017       /* Number of memory mappings */
2018       pse.num_maps = 0;
2019
2020       /* context switch counters not implemented */
2021       pse.cswitch_vol = -1;
2022       pse.cswitch_invol = -1;
2023
2024       ps_list_add(procs[i].ki_comm, have_cmdline ? cmdline : NULL, &pse);
2025
2026       switch (procs[i].ki_stat) {
2027       case SSTOP:
2028         stopped++;
2029         break;
2030       case SSLEEP:
2031         sleeping++;
2032         break;
2033       case SRUN:
2034         running++;
2035         break;
2036       case SIDL:
2037         idle++;
2038         break;
2039       case SWAIT:
2040         wait++;
2041         break;
2042       case SLOCK:
2043         blocked++;
2044         break;
2045       case SZOMB:
2046         zombies++;
2047         break;
2048       }
2049     } /* if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid)) */
2050   }
2051
2052   kvm_close(kd);
2053
2054   ps_submit_state("running", running);
2055   ps_submit_state("sleeping", sleeping);
2056   ps_submit_state("zombies", zombies);
2057   ps_submit_state("stopped", stopped);
2058   ps_submit_state("blocked", blocked);
2059   ps_submit_state("idle", idle);
2060   ps_submit_state("wait", wait);
2061
2062   for (procstat_t *ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2063     ps_submit_proc_list(ps_ptr);
2064 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
2065
2066 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_OPENBSD
2067   int running = 0;
2068   int sleeping = 0;
2069   int zombies = 0;
2070   int stopped = 0;
2071   int onproc = 0;
2072   int idle = 0;
2073   int dead = 0;
2074
2075   kvm_t *kd;
2076   char errbuf[1024];
2077   struct kinfo_proc *procs; /* array of processes */
2078   struct kinfo_proc *proc_ptr = NULL;
2079   int count; /* returns number of processes */
2080
2081   process_entry_t pse;
2082
2083   ps_list_reset();
2084
2085   /* Open the kvm interface, get a descriptor */
2086   kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
2087   if (kd == NULL) {
2088     ERROR("processes plugin: Cannot open kvm interface: %s", errbuf);
2089     return 0;
2090   }
2091
2092   /* Get the list of processes. */
2093   procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc), &count);
2094   if (procs == NULL) {
2095     ERROR("processes plugin: Cannot get kvm processes list: %s",
2096           kvm_geterr(kd));
2097     kvm_close(kd);
2098     return 0;
2099   }
2100
2101   /* Iterate through the processes in kinfo_proc */
2102   for (int i = 0; i < count; i++) {
2103     /* Create only one process list entry per _process_, i.e.
2104      * filter out threads (duplicate PID entries). */
2105     if ((proc_ptr == NULL) || (proc_ptr->p_pid != procs[i].p_pid)) {
2106       char cmdline[CMDLINE_BUFFER_SIZE] = "";
2107       _Bool have_cmdline = 0;
2108
2109       proc_ptr = &(procs[i]);
2110       /* Don't probe zombie processes  */
2111       if (!P_ZOMBIE(proc_ptr)) {
2112         char **argv;
2113         int argc;
2114         int status;
2115
2116         /* retrieve the arguments */
2117         argv = kvm_getargv(kd, proc_ptr, /* nchr = */ 0);
2118         argc = 0;
2119         if ((argv != NULL) && (argv[0] != NULL)) {
2120           while (argv[argc] != NULL)
2121             argc++;
2122
2123           status = strjoin(cmdline, sizeof(cmdline), argv, argc, " ");
2124           if (status < 0)
2125             WARNING("processes plugin: Command line did not fit into buffer.");
2126           else
2127             have_cmdline = 1;
2128         }
2129       } /* if (process has argument list) */
2130
2131       memset(&pse, 0, sizeof(pse));
2132       pse.id = procs[i].p_pid;
2133
2134       pse.num_proc = 1;
2135       pse.num_lwp = 1; /* XXX: accumulate p_tid values for a single p_pid ? */
2136
2137       pse.vmem_rss = procs[i].p_vm_rssize * pagesize;
2138       pse.vmem_data = procs[i].p_vm_dsize * pagesize;
2139       pse.vmem_code = procs[i].p_vm_tsize * pagesize;
2140       pse.stack_size = procs[i].p_vm_ssize * pagesize;
2141       pse.vmem_size = pse.stack_size + pse.vmem_code + pse.vmem_data;
2142       pse.vmem_minflt_counter = procs[i].p_uru_minflt;
2143       pse.vmem_majflt_counter = procs[i].p_uru_majflt;
2144
2145       pse.cpu_user_counter =
2146           procs[i].p_uutime_usec + (1000000lu * procs[i].p_uutime_sec);
2147       pse.cpu_system_counter =
2148           procs[i].p_ustime_usec + (1000000lu * procs[i].p_ustime_sec);
2149
2150       /* no I/O data */
2151       pse.io_rchar = -1;
2152       pse.io_wchar = -1;
2153       pse.io_syscr = -1;
2154       pse.io_syscw = -1;
2155       pse.io_diskr = -1;
2156       pse.io_diskw = -1;
2157
2158       /* file descriptor count not implemented */
2159       pse.num_fd = 0;
2160
2161       /* Number of memory mappings */
2162       pse.num_maps = 0;
2163
2164       /* context switch counters not implemented */
2165       pse.cswitch_vol = -1;
2166       pse.cswitch_invol = -1;
2167
2168       ps_list_add(procs[i].p_comm, have_cmdline ? cmdline : NULL, &pse);
2169
2170       switch (procs[i].p_stat) {
2171       case SSTOP:
2172         stopped++;
2173         break;
2174       case SSLEEP:
2175         sleeping++;
2176         break;
2177       case SRUN:
2178         running++;
2179         break;
2180       case SIDL:
2181         idle++;
2182         break;
2183       case SONPROC:
2184         onproc++;
2185         break;
2186       case SDEAD:
2187         dead++;
2188         break;
2189       case SZOMB:
2190         zombies++;
2191         break;
2192       }
2193     } /* if ((proc_ptr == NULL) || (proc_ptr->p_pid != procs[i].p_pid)) */
2194   }
2195
2196   kvm_close(kd);
2197
2198   ps_submit_state("running", running);
2199   ps_submit_state("sleeping", sleeping);
2200   ps_submit_state("zombies", zombies);
2201   ps_submit_state("stopped", stopped);
2202   ps_submit_state("onproc", onproc);
2203   ps_submit_state("idle", idle);
2204   ps_submit_state("dead", dead);
2205
2206   for (procstat_t *ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2207     ps_submit_proc_list(ps_ptr);
2208 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_OPENBSD */
2209
2210 #elif HAVE_PROCINFO_H
2211   /* AIX */
2212   int running = 0;
2213   int sleeping = 0;
2214   int zombies = 0;
2215   int stopped = 0;
2216   int paging = 0;
2217   int blocked = 0;
2218
2219   pid_t pindex = 0;
2220   int nprocs;
2221
2222   process_entry_t pse;
2223
2224   ps_list_reset();
2225   while ((nprocs = getprocs64(procentry, sizeof(struct procentry64),
2226                               /* fdsinfo = */ NULL, sizeof(struct fdsinfo64),
2227                               &pindex, MAXPROCENTRY)) > 0) {
2228     for (int i = 0; i < nprocs; i++) {
2229       tid64_t thindex;
2230       int nthreads;
2231       char arglist[MAXARGLN + 1];
2232       char *cargs;
2233       char *cmdline;
2234
2235       if (procentry[i].pi_state == SNONE)
2236         continue;
2237       /* if (procentry[i].pi_state == SZOMB)  FIXME */
2238
2239       cmdline = procentry[i].pi_comm;
2240       cargs = procentry[i].pi_comm;
2241       if (procentry[i].pi_flags & SKPROC) {
2242         if (procentry[i].pi_pid == 0)
2243           cmdline = "swapper";
2244         cargs = cmdline;
2245       } else {
2246         if (getargs(&procentry[i], sizeof(struct procentry64), arglist,
2247                     MAXARGLN) >= 0) {
2248           int n;
2249
2250           n = -1;
2251           while (++n < MAXARGLN) {
2252             if (arglist[n] == '\0') {
2253               if (arglist[n + 1] == '\0')
2254                 break;
2255               arglist[n] = ' ';
2256             }
2257           }
2258           cargs = arglist;
2259         }
2260       }
2261
2262       memset(&pse, 0, sizeof(pse));
2263
2264       pse.id = procentry[i].pi_pid;
2265       pse.num_lwp = procentry[i].pi_thcount;
2266       pse.num_proc = 1;
2267
2268       thindex = 0;
2269       while ((nthreads = getthrds64(procentry[i].pi_pid, thrdentry,
2270                                     sizeof(struct thrdentry64), &thindex,
2271                                     MAXTHRDENTRY)) > 0) {
2272         int j;
2273
2274         for (j = 0; j < nthreads; j++) {
2275           switch (thrdentry[j].ti_state) {
2276           /* case TSNONE: break; */
2277           case TSIDL:
2278             blocked++;
2279             break; /* FIXME is really blocked */
2280           case TSRUN:
2281             running++;
2282             break;
2283           case TSSLEEP:
2284             sleeping++;
2285             break;
2286           case TSSWAP:
2287             paging++;
2288             break;
2289           case TSSTOP:
2290             stopped++;
2291             break;
2292           case TSZOMB:
2293             zombies++;
2294             break;
2295           }
2296         }
2297         if (nthreads < MAXTHRDENTRY)
2298           break;
2299       }
2300
2301       /* tv_usec is nanosec ??? */
2302       pse.cpu_user_counter = procentry[i].pi_ru.ru_utime.tv_sec * 1000000 +
2303                              procentry[i].pi_ru.ru_utime.tv_usec / 1000;
2304
2305       /* tv_usec is nanosec ??? */
2306       pse.cpu_system_counter = procentry[i].pi_ru.ru_stime.tv_sec * 1000000 +
2307                                procentry[i].pi_ru.ru_stime.tv_usec / 1000;
2308
2309       pse.vmem_minflt_counter = procentry[i].pi_minflt;
2310       pse.vmem_majflt_counter = procentry[i].pi_majflt;
2311
2312       pse.vmem_size = procentry[i].pi_tsize + procentry[i].pi_dvm * pagesize;
2313       pse.vmem_rss = (procentry[i].pi_drss + procentry[i].pi_trss) * pagesize;
2314       /* Not supported/implemented */
2315       pse.vmem_data = 0;
2316       pse.vmem_code = 0;
2317       pse.stack_size = 0;
2318
2319       pse.io_rchar = -1;
2320       pse.io_wchar = -1;
2321       pse.io_syscr = -1;
2322       pse.io_syscw = -1;
2323       pse.io_diskr = -1;
2324       pse.io_diskw = -1;
2325
2326       pse.num_fd = 0;
2327       pse.num_maps = 0;
2328
2329       pse.cswitch_vol = -1;
2330       pse.cswitch_invol = -1;
2331
2332       ps_list_add(cmdline, cargs, &pse);
2333     } /* for (i = 0 .. nprocs) */
2334
2335     if (nprocs < MAXPROCENTRY)
2336       break;
2337   } /* while (getprocs64() > 0) */
2338   ps_submit_state("running", running);
2339   ps_submit_state("sleeping", sleeping);
2340   ps_submit_state("zombies", zombies);
2341   ps_submit_state("stopped", stopped);
2342   ps_submit_state("paging", paging);
2343   ps_submit_state("blocked", blocked);
2344
2345   for (procstat_t *ps = list_head_g; ps != NULL; ps = ps->next)
2346     ps_submit_proc_list(ps);
2347 /* #endif HAVE_PROCINFO_H */
2348
2349 #elif KERNEL_SOLARIS
2350   /*
2351    * The Solaris section adds a few more process states and removes some
2352    * process states compared to linux. Most notably there is no "PAGING"
2353    * and "BLOCKED" state for a process.  The rest is similar to the linux
2354    * code.
2355    */
2356   int running = 0;
2357   int sleeping = 0;
2358   int zombies = 0;
2359   int stopped = 0;
2360   int detached = 0;
2361   int daemon = 0;
2362   int system = 0;
2363   int orphan = 0;
2364
2365   struct dirent *ent;
2366   DIR *proc;
2367
2368   int status;
2369   char state;
2370
2371   char cmdline[PRARGSZ];
2372
2373   ps_list_reset();
2374
2375   proc = opendir("/proc");
2376   if (proc == NULL)
2377     return -1;
2378
2379   while ((ent = readdir(proc)) != NULL) {
2380     long pid;
2381     process_entry_t pse;
2382     char *endptr;
2383
2384     if (!isdigit((int)ent->d_name[0]))
2385       continue;
2386
2387     pid = strtol(ent->d_name, &endptr, 10);
2388     if (*endptr != 0) /* value didn't completely parse as a number */
2389       continue;
2390
2391     memset(&pse, 0, sizeof(pse));
2392     pse.id = pid;
2393
2394     status = ps_read_process(pid, &pse, &state);
2395     if (status != 0) {
2396       DEBUG("ps_read_process failed: %i", status);
2397       continue;
2398     }
2399
2400     switch (state) {
2401     case 'R':
2402       running++;
2403       break;
2404     case 'S':
2405       sleeping++;
2406       break;
2407     case 'E':
2408       detached++;
2409       break;
2410     case 'Z':
2411       zombies++;
2412       break;
2413     case 'T':
2414       stopped++;
2415       break;
2416     case 'A':
2417       daemon++;
2418       break;
2419     case 'Y':
2420       system++;
2421       break;
2422     case 'O':
2423       orphan++;
2424       break;
2425     }
2426
2427     ps_list_add(pse.name,
2428                 ps_get_cmdline(pid, pse.name, cmdline, sizeof(cmdline)), &pse);
2429   } /* while(readdir) */
2430   closedir(proc);
2431
2432   ps_submit_state("running", running);
2433   ps_submit_state("sleeping", sleeping);
2434   ps_submit_state("zombies", zombies);
2435   ps_submit_state("stopped", stopped);
2436   ps_submit_state("detached", detached);
2437   ps_submit_state("daemon", daemon);
2438   ps_submit_state("system", system);
2439   ps_submit_state("orphan", orphan);
2440
2441   for (procstat_t *ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2442     ps_submit_proc_list(ps_ptr);
2443
2444   read_fork_rate();
2445 #endif /* KERNEL_SOLARIS */
2446
2447   want_init = 0;
2448
2449   return 0;
2450 } /* int ps_read */
2451
2452 void module_register(void) {
2453   plugin_register_complex_config("processes", ps_config);
2454   plugin_register_init("processes", ps_init);
2455   plugin_register_read("processes", ps_read);
2456 } /* void module_register */