fix indention, revert merge failures
[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_vol != -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, "memory_maps", sizeof(vl.type));
787     vl.values[0].gauge = ps->num_maps;
788     vl.values_len = 1;
789     plugin_dispatch_values(&vl);
790   }
791
792   if ((ps->cswitch_vol != -1) && (ps->cswitch_invol != -1)) {
793     sstrncpy(vl.type, "contextswitch", sizeof(vl.type));
794     sstrncpy(vl.type_instance, "voluntary", sizeof(vl.type_instance));
795     vl.values[0].derive = ps->cswitch_vol;
796     vl.values_len = 1;
797     plugin_dispatch_values(&vl);
798
799     sstrncpy(vl.type, "contextswitch", sizeof(vl.type));
800     sstrncpy(vl.type_instance, "involuntary", sizeof(vl.type_instance));
801     vl.values[0].derive = ps->cswitch_invol;
802     vl.values_len = 1;
803     plugin_dispatch_values(&vl);
804   }
805
806   DEBUG("name = %s; num_proc = %lu; num_lwp = %lu; num_fd = %lu; num_maps = %lu; "
807         "vmem_size = %lu; vmem_rss = %lu; vmem_data = %lu; "
808         "vmem_code = %lu; "
809         "vmem_minflt_counter = %" PRIi64 "; vmem_majflt_counter = %" PRIi64 "; "
810         "cpu_user_counter = %" PRIi64 "; cpu_system_counter = %" PRIi64 "; "
811         "io_rchar = %" PRIi64 "; io_wchar = %" PRIi64 "; "
812         "io_syscr = %" PRIi64 "; io_syscw = %" PRIi64 "; "
813         "io_diskr = %" PRIi64 "; io_diskw = %" PRIi64 "; "
814         "cswitch_vol = %" PRIi64 "; cswitch_invol = %" PRIi64 ";",
815         ps->name, ps->num_proc, ps->num_lwp, ps->num_fd, ps->num_maps, ps->vmem_size,
816         ps->vmem_rss, ps->vmem_data, ps->vmem_code, ps->vmem_minflt_counter,
817         ps->vmem_majflt_counter, ps->cpu_user_counter, ps->cpu_system_counter,
818         ps->io_rchar, ps->io_wchar, ps->io_syscr, ps->io_syscw, ps->io_diskr,
819         ps->io_diskw, ps->cswitch_vol, ps->cswitch_invol);
820
821 } /* void ps_submit_proc_list */
822
823 #if KERNEL_LINUX || KERNEL_SOLARIS
824 static void ps_submit_fork_rate(derive_t value) {
825   value_list_t vl = VALUE_LIST_INIT;
826
827   vl.values = &(value_t){.derive = value};
828   vl.values_len = 1;
829   sstrncpy(vl.plugin, "processes", sizeof(vl.plugin));
830   sstrncpy(vl.plugin_instance, "", sizeof(vl.plugin_instance));
831   sstrncpy(vl.type, "fork_rate", sizeof(vl.type));
832   sstrncpy(vl.type_instance, "", sizeof(vl.type_instance));
833
834   plugin_dispatch_values(&vl);
835 }
836 #endif /* KERNEL_LINUX || KERNEL_SOLARIS*/
837
838 /* ------- additional functions for KERNEL_LINUX/HAVE_THREAD_INFO ------- */
839 #if KERNEL_LINUX
840 static int ps_read_tasks_status(process_entry_t *ps) {
841   char dirname[64];
842   DIR *dh;
843   char filename[64];
844   FILE *fh;
845   struct dirent *ent;
846   derive_t cswitch_vol = 0;
847   derive_t cswitch_invol = 0;
848   char buffer[1024];
849   char *fields[8];
850   int numfields;
851
852   snprintf(dirname, sizeof(dirname), "/proc/%li/task", ps->id);
853
854   if ((dh = opendir(dirname)) == NULL) {
855     DEBUG("Failed to open directory `%s'", dirname);
856     return -1;
857   }
858
859   while ((ent = readdir(dh)) != NULL) {
860     char *tpid;
861
862     if (!isdigit((int)ent->d_name[0]))
863       continue;
864
865     tpid = ent->d_name;
866
867     if (snprintf(filename, sizeof(filename), "/proc/%li/task/%s/status", ps->id,
868                  tpid) >= sizeof(filename)) {
869       DEBUG("Filename too long: `%s'", filename);
870       continue;
871     }
872
873     if ((fh = fopen(filename, "r")) == NULL) {
874       DEBUG("Failed to open file `%s'", filename);
875       continue;
876     }
877
878     while (fgets(buffer, sizeof(buffer), fh) != NULL) {
879       derive_t tmp;
880       char *endptr;
881
882       if (strncmp(buffer, "voluntary_ctxt_switches", 23) != 0 &&
883           strncmp(buffer, "nonvoluntary_ctxt_switches", 26) != 0)
884         continue;
885
886       numfields = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
887
888       if (numfields < 2)
889         continue;
890
891       errno = 0;
892       endptr = NULL;
893       tmp = (derive_t)strtoll(fields[1], &endptr, /* base = */ 10);
894       if ((errno == 0) && (endptr != fields[1])) {
895         if (strncmp(buffer, "voluntary_ctxt_switches", 23) == 0) {
896           cswitch_vol += tmp;
897         } else if (strncmp(buffer, "nonvoluntary_ctxt_switches", 26) == 0) {
898           cswitch_invol += tmp;
899         }
900       }
901     } /* while (fgets) */
902
903     if (fclose(fh)) {
904       char errbuf[1024];
905       WARNING("processes: fclose: %s",
906               sstrerror(errno, errbuf, sizeof(errbuf)));
907     }
908   }
909   closedir(dh);
910
911   ps->cswitch_vol = cswitch_vol;
912   ps->cswitch_invol = cswitch_invol;
913
914   return 0;
915 } /* int *ps_read_tasks_status */
916
917 /* Read data from /proc/pid/status */
918 static int ps_read_status(long pid, process_entry_t *ps) {
919   FILE *fh;
920   char buffer[1024];
921   char filename[64];
922   unsigned long lib = 0;
923   unsigned long exe = 0;
924   unsigned long data = 0;
925   unsigned long threads = 0;
926   char *fields[8];
927   int numfields;
928
929   snprintf(filename, sizeof(filename), "/proc/%li/status", pid);
930   if ((fh = fopen(filename, "r")) == NULL)
931     return -1;
932
933   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
934     unsigned long tmp;
935     char *endptr;
936
937     if (strncmp(buffer, "Vm", 2) != 0 && strncmp(buffer, "Threads", 7) != 0)
938       continue;
939
940     numfields = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
941
942     if (numfields < 2)
943       continue;
944
945     errno = 0;
946     endptr = NULL;
947     tmp = strtoul(fields[1], &endptr, /* base = */ 10);
948     if ((errno == 0) && (endptr != fields[1])) {
949       if (strncmp(buffer, "VmData", 6) == 0) {
950         data = tmp;
951       } else if (strncmp(buffer, "VmLib", 5) == 0) {
952         lib = tmp;
953       } else if (strncmp(buffer, "VmExe", 5) == 0) {
954         exe = tmp;
955       } else if (strncmp(buffer, "Threads", 7) == 0) {
956         threads = tmp;
957       }
958     }
959   } /* while (fgets) */
960
961   if (fclose(fh)) {
962     char errbuf[1024];
963     WARNING("processes: fclose: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
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     char errbuf[1024];
1024     WARNING("processes: fclose: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
1025   }
1026   return 0;
1027 } /* int ps_read_io (...) */
1028
1029 static int ps_count_maps(pid_t pid) {
1030   FILE *fh;
1031   char buffer[1024];
1032   char filename[64];
1033   int count = 0;
1034
1035   snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
1036   if ((fh = fopen(filename, "r")) == NULL) {
1037     DEBUG("ps_count_maps: Failed to open file `%s'", filename);
1038     return -1;
1039   }
1040
1041   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
1042     if (strchr(buffer, '\n')) {
1043       count ++;
1044     }
1045   } /* while (fgets) */
1046
1047   if (fclose(fh)) {
1048     char errbuf[1024];
1049     WARNING("processes: fclose: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
1050   }
1051   return count;
1052 } /* int ps_count_maps (...) */
1053
1054 static int ps_count_fd(int pid) {
1055   char dirname[64];
1056   DIR *dh;
1057   struct dirent *ent;
1058   int count = 0;
1059
1060   snprintf(dirname, sizeof(dirname), "/proc/%i/fd", pid);
1061
1062   if ((dh = opendir(dirname)) == NULL) {
1063     DEBUG("Failed to open directory `%s'", dirname);
1064     return -1;
1065   }
1066   while ((ent = readdir(dh)) != NULL) {
1067     if (!isdigit((int)ent->d_name[0]))
1068       continue;
1069     else
1070       count++;
1071   }
1072   closedir(dh);
1073
1074   return (count >= 1) ? count : 1;
1075 } /* int ps_count_fd (pid) */
1076
1077 static void ps_fill_details(const procstat_t *ps, process_entry_t *entry) {
1078   if (entry->has_io == 0) {
1079     ps_read_io(entry);
1080     entry->has_io = 1;
1081   }
1082
1083   if (ps->report_ctx_switch) {
1084     if (entry->has_cswitch == 0) {
1085       ps_read_tasks_status(entry);
1086       entry->has_cswitch = 1;
1087     }
1088   }
1089
1090   if (ps->report_maps_num) {
1091     int num_maps;
1092     if (entry->has_maps == 0 && (num_maps = ps_count_maps(entry->id)) > 0) {
1093       entry->num_maps = num_maps;
1094     }
1095     entry->has_maps = 1;
1096   }
1097
1098   if (ps->report_fd_num) {
1099     int num_fd;
1100     if (entry->has_fd == 0 && (num_fd = ps_count_fd(entry->id)) > 0) {
1101       entry->num_fd = num_fd;
1102     }
1103     entry->has_fd = 1;
1104   }
1105 } /* void ps_fill_details (...) */
1106
1107 static int ps_read_process(long pid, process_entry_t *ps, char *state) {
1108   char filename[64];
1109   char buffer[1024];
1110
1111   char *fields[64];
1112   char fields_len;
1113
1114   size_t buffer_len;
1115
1116   char *buffer_ptr;
1117   size_t name_start_pos;
1118   size_t name_end_pos;
1119   size_t name_len;
1120
1121   derive_t cpu_user_counter;
1122   derive_t cpu_system_counter;
1123   long long unsigned vmem_size;
1124   long long unsigned vmem_rss;
1125   long long unsigned stack_size;
1126
1127   ssize_t status;
1128
1129   snprintf(filename, sizeof(filename), "/proc/%li/stat", pid);
1130
1131   status = read_file_contents(filename, buffer, sizeof(buffer) - 1);
1132   if (status <= 0)
1133     return -1;
1134   buffer_len = (size_t)status;
1135   buffer[buffer_len] = 0;
1136
1137   /* The name of the process is enclosed in parens. Since the name can
1138    * contain parens itself, spaces, numbers and pretty much everything
1139    * else, use these to determine the process name. We don't use
1140    * strchr(3) and strrchr(3) to avoid pointer arithmetic which would
1141    * otherwise be required to determine name_len. */
1142   name_start_pos = 0;
1143   while (name_start_pos < buffer_len && buffer[name_start_pos] != '(')
1144     name_start_pos++;
1145
1146   name_end_pos = buffer_len;
1147   while (name_end_pos > 0 && buffer[name_end_pos] != ')')
1148     name_end_pos--;
1149
1150   /* Either '(' or ')' is not found or they are in the wrong order.
1151    * Anyway, something weird that shouldn't happen ever. */
1152   if (name_start_pos >= name_end_pos) {
1153     ERROR("processes plugin: name_start_pos = %zu >= name_end_pos = %zu",
1154           name_start_pos, name_end_pos);
1155     return -1;
1156   }
1157
1158   name_len = (name_end_pos - name_start_pos) - 1;
1159   if (name_len >= sizeof(ps->name))
1160     name_len = sizeof(ps->name) - 1;
1161
1162   sstrncpy(ps->name, &buffer[name_start_pos + 1], name_len + 1);
1163
1164   if ((buffer_len - name_end_pos) < 2)
1165     return -1;
1166   buffer_ptr = &buffer[name_end_pos + 2];
1167
1168   fields_len = strsplit(buffer_ptr, fields, STATIC_ARRAY_SIZE(fields));
1169   if (fields_len < 22) {
1170     DEBUG("processes plugin: ps_read_process (pid = %li):"
1171           " `%s' has only %i fields..",
1172           pid, filename, fields_len);
1173     return -1;
1174   }
1175
1176   *state = fields[0][0];
1177
1178   if (*state == 'Z') {
1179     ps->num_lwp = 0;
1180     ps->num_proc = 0;
1181   } else {
1182     ps->num_lwp = strtoul(fields[17], /* endptr = */ NULL, /* base = */ 10);
1183     if ((ps_read_status(pid, ps)) != 0) {
1184       /* No VMem data */
1185       ps->vmem_data = -1;
1186       ps->vmem_code = -1;
1187       DEBUG("ps_read_process: did not get vmem data for pid %li", pid);
1188     }
1189     if (ps->num_lwp == 0)
1190       ps->num_lwp = 1;
1191     ps->num_proc = 1;
1192   }
1193
1194   /* Leave the rest at zero if this is only a zombi */
1195   if (ps->num_proc == 0) {
1196     DEBUG("processes plugin: This is only a zombie: pid = %li; "
1197           "name = %s;",
1198           pid, ps->name);
1199     return 0;
1200   }
1201
1202   cpu_user_counter = atoll(fields[11]);
1203   cpu_system_counter = atoll(fields[12]);
1204   vmem_size = atoll(fields[20]);
1205   vmem_rss = atoll(fields[21]);
1206   ps->vmem_minflt_counter = atol(fields[7]);
1207   ps->vmem_majflt_counter = atol(fields[9]);
1208
1209   {
1210     unsigned long long stack_start = atoll(fields[25]);
1211     unsigned long long stack_ptr = atoll(fields[26]);
1212
1213     stack_size = (stack_start > stack_ptr) ? stack_start - stack_ptr
1214                                            : stack_ptr - stack_start;
1215   }
1216
1217   /* Convert jiffies to useconds */
1218   cpu_user_counter = cpu_user_counter * 1000000 / CONFIG_HZ;
1219   cpu_system_counter = cpu_system_counter * 1000000 / CONFIG_HZ;
1220   vmem_rss = vmem_rss * pagesize_g;
1221
1222   ps->cpu_user_counter = cpu_user_counter;
1223   ps->cpu_system_counter = cpu_system_counter;
1224   ps->vmem_size = (unsigned long)vmem_size;
1225   ps->vmem_rss = (unsigned long)vmem_rss;
1226   ps->stack_size = (unsigned long)stack_size;
1227
1228   /* no data by default. May be filled by ps_fill_details () */
1229   ps->io_rchar = -1;
1230   ps->io_wchar = -1;
1231   ps->io_syscr = -1;
1232   ps->io_syscw = -1;
1233   ps->io_diskr = -1;
1234   ps->io_diskw = -1;
1235
1236   ps->cswitch_vol = -1;
1237   ps->cswitch_invol = -1;
1238
1239   /* success */
1240   return 0;
1241 } /* int ps_read_process (...) */
1242
1243 static char *ps_get_cmdline(long pid, char *name, char *buf, size_t buf_len) {
1244   char *buf_ptr;
1245   size_t len;
1246
1247   char file[PATH_MAX];
1248   int fd;
1249
1250   size_t n;
1251
1252   if ((pid < 1) || (NULL == buf) || (buf_len < 2))
1253     return NULL;
1254
1255   snprintf(file, sizeof(file), "/proc/%li/cmdline", pid);
1256
1257   errno = 0;
1258   fd = open(file, O_RDONLY);
1259   if (fd < 0) {
1260     char errbuf[4096];
1261     /* ENOENT means the process exited while we were handling it.
1262      * Don't complain about this, it only fills the logs. */
1263     if (errno != ENOENT)
1264       WARNING("processes plugin: Failed to open `%s': %s.", file,
1265               sstrerror(errno, errbuf, sizeof(errbuf)));
1266     return NULL;
1267   }
1268
1269   buf_ptr = buf;
1270   len = buf_len;
1271
1272   n = 0;
1273
1274   while (42) {
1275     ssize_t status;
1276
1277     status = read(fd, (void *)buf_ptr, len);
1278
1279     if (status < 0) {
1280       char errbuf[1024];
1281
1282       if ((EAGAIN == errno) || (EINTR == errno))
1283         continue;
1284
1285       WARNING("processes plugin: Failed to read from `%s': %s.", file,
1286               sstrerror(errno, errbuf, sizeof(errbuf)));
1287       close(fd);
1288       return NULL;
1289     }
1290
1291     n += status;
1292
1293     if (status == 0)
1294       break;
1295
1296     buf_ptr += status;
1297     len -= status;
1298
1299     if (len == 0)
1300       break;
1301   }
1302
1303   close(fd);
1304
1305   if (0 == n) {
1306     /* cmdline not available; e.g. kernel thread, zombie */
1307     if (NULL == name)
1308       return NULL;
1309
1310     snprintf(buf, buf_len, "[%s]", name);
1311     return buf;
1312   }
1313
1314   assert(n <= buf_len);
1315
1316   if (n == buf_len)
1317     --n;
1318   buf[n] = '\0';
1319
1320   --n;
1321   /* remove trailing whitespace */
1322   while ((n > 0) && (isspace(buf[n]) || ('\0' == buf[n]))) {
1323     buf[n] = '\0';
1324     --n;
1325   }
1326
1327   /* arguments are separated by '\0' in /proc/<pid>/cmdline */
1328   while (n > 0) {
1329     if ('\0' == buf[n])
1330       buf[n] = ' ';
1331     --n;
1332   }
1333   return buf;
1334 } /* char *ps_get_cmdline (...) */
1335
1336 static int read_fork_rate(void) {
1337   FILE *proc_stat;
1338   char buffer[1024];
1339   value_t value;
1340   _Bool value_valid = 0;
1341
1342   proc_stat = fopen("/proc/stat", "r");
1343   if (proc_stat == NULL) {
1344     char errbuf[1024];
1345     ERROR("processes plugin: fopen (/proc/stat) failed: %s",
1346           sstrerror(errno, errbuf, sizeof(errbuf)));
1347     return -1;
1348   }
1349
1350   while (fgets(buffer, sizeof(buffer), proc_stat) != NULL) {
1351     int status;
1352     char *fields[3];
1353     int fields_num;
1354
1355     fields_num = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
1356     if (fields_num != 2)
1357       continue;
1358
1359     if (strcmp("processes", fields[0]) != 0)
1360       continue;
1361
1362     status = parse_value(fields[1], &value, DS_TYPE_DERIVE);
1363     if (status == 0)
1364       value_valid = 1;
1365
1366     break;
1367   }
1368   fclose(proc_stat);
1369
1370   if (!value_valid)
1371     return -1;
1372
1373   ps_submit_fork_rate(value.derive);
1374   return 0;
1375 }
1376 #endif /*KERNEL_LINUX */
1377
1378 #if KERNEL_SOLARIS
1379 static char *ps_get_cmdline(long pid,
1380                             char *name __attribute__((unused)), /* {{{ */
1381                             char *buffer, size_t buffer_size) {
1382   char path[PATH_MAX];
1383   psinfo_t info;
1384   ssize_t status;
1385
1386   snprintf(path, sizeof(path), "/proc/%li/psinfo", pid);
1387
1388   status = read_file_contents(path, (void *)&info, sizeof(info));
1389   if ((status < 0) || (((size_t)status) != sizeof(info))) {
1390     ERROR("processes plugin: Unexpected return value "
1391           "while reading \"%s\": "
1392           "Returned %zd but expected %zu.",
1393           path, status, buffer_size);
1394     return NULL;
1395   }
1396
1397   info.pr_psargs[sizeof(info.pr_psargs) - 1] = 0;
1398   sstrncpy(buffer, info.pr_psargs, buffer_size);
1399
1400   return buffer;
1401 } /* }}} int ps_get_cmdline */
1402
1403 /*
1404  * Reads process information on the Solaris OS. The information comes mainly
1405  * from
1406  * /proc/PID/status, /proc/PID/psinfo and /proc/PID/usage
1407  * The values for input and ouput chars are calculated "by hand"
1408  * Added a few "solaris" specific process states as well
1409  */
1410 static int ps_read_process(long pid, process_entry_t *ps, char *state) {
1411   char filename[64];
1412   char f_psinfo[64], f_usage[64];
1413   char *buffer;
1414
1415   pstatus_t *myStatus;
1416   psinfo_t *myInfo;
1417   prusage_t *myUsage;
1418
1419   snprintf(filename, sizeof(filename), "/proc/%li/status", pid);
1420   snprintf(f_psinfo, sizeof(f_psinfo), "/proc/%li/psinfo", pid);
1421   snprintf(f_usage, sizeof(f_usage), "/proc/%li/usage", pid);
1422
1423   buffer = calloc(1, sizeof(pstatus_t));
1424   read_file_contents(filename, buffer, sizeof(pstatus_t));
1425   myStatus = (pstatus_t *)buffer;
1426
1427   buffer = calloc(1, sizeof(psinfo_t));
1428   read_file_contents(f_psinfo, buffer, sizeof(psinfo_t));
1429   myInfo = (psinfo_t *)buffer;
1430
1431   buffer = calloc(1, sizeof(prusage_t));
1432   read_file_contents(f_usage, buffer, sizeof(prusage_t));
1433   myUsage = (prusage_t *)buffer;
1434
1435   sstrncpy(ps->name, myInfo->pr_fname, sizeof(myInfo->pr_fname));
1436   ps->num_lwp = myStatus->pr_nlwp;
1437   if (myInfo->pr_wstat != 0) {
1438     ps->num_proc = 0;
1439     ps->num_lwp = 0;
1440     *state = (char)'Z';
1441
1442     sfree(myStatus);
1443     sfree(myInfo);
1444     sfree(myUsage);
1445     return 0;
1446   } else {
1447     ps->num_proc = 1;
1448     ps->num_lwp = myInfo->pr_nlwp;
1449   }
1450
1451   /*
1452    * Convert system time and user time from nanoseconds to microseconds
1453    * for compatibility with the linux module
1454    */
1455   ps->cpu_system_counter = myStatus->pr_stime.tv_nsec / 1000;
1456   ps->cpu_user_counter = myStatus->pr_utime.tv_nsec / 1000;
1457
1458   /*
1459    * Convert rssize from KB to bytes to be consistent w/ the linux module
1460    */
1461   ps->vmem_rss = myInfo->pr_rssize * 1024;
1462   ps->vmem_size = myInfo->pr_size * 1024;
1463   ps->vmem_minflt_counter = myUsage->pr_minf;
1464   ps->vmem_majflt_counter = myUsage->pr_majf;
1465
1466   /*
1467    * TODO: Data and code segment calculations for Solaris
1468    */
1469
1470   ps->vmem_data = -1;
1471   ps->vmem_code = -1;
1472   ps->stack_size = myStatus->pr_stksize;
1473
1474   /*
1475    * TODO: File descriptor count for Solaris
1476    */
1477   ps->num_fd = 0;
1478
1479   /* Number of memory mappings */
1480   ps->num_maps = 0;
1481
1482   /*
1483    * Calculating input/ouput chars
1484    * Formula used is total chars / total blocks => chars/block
1485    * then convert input/output blocks to chars
1486    */
1487   ulong_t tot_chars = myUsage->pr_ioch;
1488   ulong_t tot_blocks = myUsage->pr_inblk + myUsage->pr_oublk;
1489   ulong_t chars_per_block = 1;
1490   if (tot_blocks != 0)
1491     chars_per_block = tot_chars / tot_blocks;
1492   ps->io_rchar = myUsage->pr_inblk * chars_per_block;
1493   ps->io_wchar = myUsage->pr_oublk * chars_per_block;
1494   ps->io_syscr = myUsage->pr_sysc;
1495   ps->io_syscw = myUsage->pr_sysc;
1496   ps->io_diskr = -1;
1497   ps->io_diskw = -1;
1498
1499   /*
1500    * TODO: context switch counters for Solaris
1501 */
1502   ps->cswitch_vol = -1;
1503   ps->cswitch_invol = -1;
1504
1505   /*
1506    * TODO: Find way of setting BLOCKED and PAGING status
1507    */
1508
1509   *state = (char)'R';
1510   if (myStatus->pr_flags & PR_ASLEEP)
1511     *state = (char)'S';
1512   else if (myStatus->pr_flags & PR_STOPPED)
1513     *state = (char)'T';
1514   else if (myStatus->pr_flags & PR_DETACH)
1515     *state = (char)'E';
1516   else if (myStatus->pr_flags & PR_DAEMON)
1517     *state = (char)'A';
1518   else if (myStatus->pr_flags & PR_ISSYS)
1519     *state = (char)'Y';
1520   else if (myStatus->pr_flags & PR_ORPHAN)
1521     *state = (char)'O';
1522
1523   sfree(myStatus);
1524   sfree(myInfo);
1525   sfree(myUsage);
1526
1527   return 0;
1528 }
1529
1530 /*
1531  * Reads the number of threads created since the last reboot. On Solaris these
1532  * are retrieved from kstat (module cpu, name sys, class misc, stat nthreads).
1533  * The result is the sum for all the threads created on each cpu
1534  */
1535 static int read_fork_rate(void) {
1536   extern kstat_ctl_t *kc;
1537   derive_t result = 0;
1538
1539   if (kc == NULL)
1540     return -1;
1541
1542   for (kstat_t *ksp_chain = kc->kc_chain; ksp_chain != NULL;
1543        ksp_chain = ksp_chain->ks_next) {
1544     if ((strcmp(ksp_chain->ks_module, "cpu") == 0) &&
1545         (strcmp(ksp_chain->ks_name, "sys") == 0) &&
1546         (strcmp(ksp_chain->ks_class, "misc") == 0)) {
1547       long long tmp;
1548
1549       kstat_read(kc, ksp_chain, NULL);
1550
1551       tmp = get_kstat_value(ksp_chain, "nthreads");
1552       if (tmp != -1LL)
1553         result += tmp;
1554     }
1555   }
1556
1557   ps_submit_fork_rate(result);
1558   return 0;
1559 }
1560 #endif /* KERNEL_SOLARIS */
1561
1562 #if HAVE_THREAD_INFO
1563 static int mach_get_task_name(task_t t, int *pid, char *name,
1564                               size_t name_max_len) {
1565   int mib[4];
1566
1567   struct kinfo_proc kp;
1568   size_t kp_size;
1569
1570   mib[0] = CTL_KERN;
1571   mib[1] = KERN_PROC;
1572   mib[2] = KERN_PROC_PID;
1573
1574   if (pid_for_task(t, pid) != KERN_SUCCESS)
1575     return -1;
1576   mib[3] = *pid;
1577
1578   kp_size = sizeof(kp);
1579   if (sysctl(mib, 4, &kp, &kp_size, NULL, 0) != 0)
1580     return -1;
1581
1582   if (name_max_len > (MAXCOMLEN + 1))
1583     name_max_len = MAXCOMLEN + 1;
1584
1585   strncpy(name, kp.kp_proc.p_comm, name_max_len - 1);
1586   name[name_max_len - 1] = '\0';
1587
1588   DEBUG("pid = %i; name = %s;", *pid, name);
1589
1590   /* We don't do the special handling for `p_comm == "LaunchCFMApp"' as
1591    * `top' does it, because it is a lot of work and only used when
1592    * debugging. -octo */
1593
1594   return 0;
1595 }
1596 #endif /* HAVE_THREAD_INFO */
1597 /* ------- end of additional functions for KERNEL_LINUX/HAVE_THREAD_INFO -------
1598  */
1599
1600 /* do actual readings from kernel */
1601 static int ps_read(void) {
1602 #if HAVE_THREAD_INFO
1603   kern_return_t status;
1604
1605   processor_set_t port_pset_priv;
1606
1607   task_array_t task_list;
1608   mach_msg_type_number_t task_list_len;
1609
1610   int task_pid;
1611   char task_name[MAXCOMLEN + 1];
1612
1613   thread_act_array_t thread_list;
1614   mach_msg_type_number_t thread_list_len;
1615   thread_basic_info_data_t thread_data;
1616   mach_msg_type_number_t thread_data_len;
1617
1618   int running = 0;
1619   int sleeping = 0;
1620   int zombies = 0;
1621   int stopped = 0;
1622   int blocked = 0;
1623
1624   procstat_t *ps;
1625   process_entry_t pse;
1626
1627   ps_list_reset();
1628
1629   /*
1630    * The Mach-concept is a little different from the traditional UNIX
1631    * concept: All the work is done in threads. Threads are contained in
1632    * `tasks'. Therefore, `task status' doesn't make much sense, since
1633    * it's actually a `thread status'.
1634    * Tasks are assigned to sets of processors, so that's where you go to
1635    * get a list.
1636    */
1637   for (mach_msg_type_number_t pset = 0; pset < pset_list_len; pset++) {
1638     if ((status = host_processor_set_priv(port_host_self, pset_list[pset],
1639                                           &port_pset_priv)) != KERN_SUCCESS) {
1640       ERROR("host_processor_set_priv failed: %s\n", mach_error_string(status));
1641       continue;
1642     }
1643
1644     if ((status = processor_set_tasks(port_pset_priv, &task_list,
1645                                       &task_list_len)) != KERN_SUCCESS) {
1646       ERROR("processor_set_tasks failed: %s\n", mach_error_string(status));
1647       mach_port_deallocate(port_task_self, port_pset_priv);
1648       continue;
1649     }
1650
1651     for (mach_msg_type_number_t task = 0; task < task_list_len; task++) {
1652       ps = NULL;
1653       if (mach_get_task_name(task_list[task], &task_pid, task_name,
1654                              PROCSTAT_NAME_LEN) == 0) {
1655         /* search for at least one match */
1656         for (ps = list_head_g; ps != NULL; ps = ps->next)
1657           /* FIXME: cmdline should be here instead of NULL */
1658           if (ps_list_match(task_name, NULL, ps) == 1)
1659             break;
1660       }
1661
1662       /* Collect more detailed statistics for this process */
1663       if (ps != NULL) {
1664         task_basic_info_data_t task_basic_info;
1665         mach_msg_type_number_t task_basic_info_len;
1666         task_events_info_data_t task_events_info;
1667         mach_msg_type_number_t task_events_info_len;
1668         task_absolutetime_info_data_t task_absolutetime_info;
1669         mach_msg_type_number_t task_absolutetime_info_len;
1670
1671         memset(&pse, '\0', sizeof(pse));
1672         pse.id = task_pid;
1673
1674         task_basic_info_len = TASK_BASIC_INFO_COUNT;
1675         status = task_info(task_list[task], TASK_BASIC_INFO,
1676                            (task_info_t)&task_basic_info, &task_basic_info_len);
1677         if (status != KERN_SUCCESS) {
1678           ERROR("task_info failed: %s", mach_error_string(status));
1679           continue; /* with next thread_list */
1680         }
1681
1682         task_events_info_len = TASK_EVENTS_INFO_COUNT;
1683         status =
1684             task_info(task_list[task], TASK_EVENTS_INFO,
1685                       (task_info_t)&task_events_info, &task_events_info_len);
1686         if (status != KERN_SUCCESS) {
1687           ERROR("task_info failed: %s", mach_error_string(status));
1688           continue; /* with next thread_list */
1689         }
1690
1691         task_absolutetime_info_len = TASK_ABSOLUTETIME_INFO_COUNT;
1692         status = task_info(task_list[task], TASK_ABSOLUTETIME_INFO,
1693                            (task_info_t)&task_absolutetime_info,
1694                            &task_absolutetime_info_len);
1695         if (status != KERN_SUCCESS) {
1696           ERROR("task_info failed: %s", mach_error_string(status));
1697           continue; /* with next thread_list */
1698         }
1699
1700         pse.num_proc++;
1701         pse.vmem_size = task_basic_info.virtual_size;
1702         pse.vmem_rss = task_basic_info.resident_size;
1703         /* Does not seem to be easily exposed */
1704         pse.vmem_data = 0;
1705         pse.vmem_code = 0;
1706
1707         pse.io_rchar = -1;
1708         pse.io_wchar = -1;
1709         pse.io_syscr = -1;
1710         pse.io_syscw = -1;
1711         pse.io_diskr = -1;
1712         pse.io_diskw = -1;
1713
1714         /* File descriptor count not implemented */
1715         pse.num_fd = 0;
1716
1717         /* Number of memory mappings */
1718         pse.num_maps = 0;
1719
1720         pse.vmem_minflt_counter = task_events_info.cow_faults;
1721         pse.vmem_majflt_counter = task_events_info.faults;
1722
1723         pse.cpu_user_counter = task_absolutetime_info.total_user;
1724         pse.cpu_system_counter = task_absolutetime_info.total_system;
1725
1726         /* context switch counters not implemented */
1727         pse.cswitch_vol = -1;
1728         pse.cswitch_invol = -1;
1729       }
1730
1731       status = task_threads(task_list[task], &thread_list, &thread_list_len);
1732       if (status != KERN_SUCCESS) {
1733         /* Apple's `top' treats this case a zombie. It
1734          * makes sense to some extend: A `zombie'
1735          * thread is nonsense, since the task/process
1736          * is dead. */
1737         zombies++;
1738         DEBUG("task_threads failed: %s", mach_error_string(status));
1739         if (task_list[task] != port_task_self)
1740           mach_port_deallocate(port_task_self, task_list[task]);
1741         continue; /* with next task_list */
1742       }
1743
1744       for (mach_msg_type_number_t thread = 0; thread < thread_list_len;
1745            thread++) {
1746         thread_data_len = THREAD_BASIC_INFO_COUNT;
1747         status = thread_info(thread_list[thread], THREAD_BASIC_INFO,
1748                              (thread_info_t)&thread_data, &thread_data_len);
1749         if (status != KERN_SUCCESS) {
1750           ERROR("thread_info failed: %s", mach_error_string(status));
1751           if (task_list[task] != port_task_self)
1752             mach_port_deallocate(port_task_self, thread_list[thread]);
1753           continue; /* with next thread_list */
1754         }
1755
1756         if (ps != NULL)
1757           pse.num_lwp++;
1758
1759         switch (thread_data.run_state) {
1760         case TH_STATE_RUNNING:
1761           running++;
1762           break;
1763         case TH_STATE_STOPPED:
1764         /* What exactly is `halted'? */
1765         case TH_STATE_HALTED:
1766           stopped++;
1767           break;
1768         case TH_STATE_WAITING:
1769           sleeping++;
1770           break;
1771         case TH_STATE_UNINTERRUPTIBLE:
1772           blocked++;
1773           break;
1774         /* There is no `zombie' case here,
1775          * since there are no zombie-threads.
1776          * There's only zombie tasks, which are
1777          * handled above. */
1778         default:
1779           WARNING("Unknown thread status: %i", thread_data.run_state);
1780           break;
1781         } /* switch (thread_data.run_state) */
1782
1783         if (task_list[task] != port_task_self) {
1784           status = mach_port_deallocate(port_task_self, thread_list[thread]);
1785           if (status != KERN_SUCCESS)
1786             ERROR("mach_port_deallocate failed: %s", mach_error_string(status));
1787         }
1788       } /* for (thread_list) */
1789
1790       if ((status = vm_deallocate(port_task_self, (vm_address_t)thread_list,
1791                                   thread_list_len * sizeof(thread_act_t))) !=
1792           KERN_SUCCESS) {
1793         ERROR("vm_deallocate failed: %s", mach_error_string(status));
1794       }
1795       thread_list = NULL;
1796       thread_list_len = 0;
1797
1798       /* Only deallocate the task port, if it isn't our own.
1799        * Don't know what would happen in that case, but this
1800        * is what Apple's top does.. ;) */
1801       if (task_list[task] != port_task_self) {
1802         status = mach_port_deallocate(port_task_self, task_list[task]);
1803         if (status != KERN_SUCCESS)
1804           ERROR("mach_port_deallocate failed: %s", mach_error_string(status));
1805       }
1806
1807       if (ps != NULL)
1808         /* FIXME: cmdline should be here instead of NULL */
1809         ps_list_add(task_name, NULL, &pse);
1810     } /* for (task_list) */
1811
1812     if ((status = vm_deallocate(port_task_self, (vm_address_t)task_list,
1813                                 task_list_len * sizeof(task_t))) !=
1814         KERN_SUCCESS) {
1815       ERROR("vm_deallocate failed: %s", mach_error_string(status));
1816     }
1817     task_list = NULL;
1818     task_list_len = 0;
1819
1820     if ((status = mach_port_deallocate(port_task_self, port_pset_priv)) !=
1821         KERN_SUCCESS) {
1822       ERROR("mach_port_deallocate failed: %s", mach_error_string(status));
1823     }
1824   } /* for (pset_list) */
1825
1826   ps_submit_state("running", running);
1827   ps_submit_state("sleeping", sleeping);
1828   ps_submit_state("zombies", zombies);
1829   ps_submit_state("stopped", stopped);
1830   ps_submit_state("blocked", blocked);
1831
1832   for (ps = list_head_g; ps != NULL; ps = ps->next)
1833     ps_submit_proc_list(ps);
1834 /* #endif HAVE_THREAD_INFO */
1835
1836 #elif KERNEL_LINUX
1837   int running = 0;
1838   int sleeping = 0;
1839   int zombies = 0;
1840   int stopped = 0;
1841   int paging = 0;
1842   int blocked = 0;
1843
1844   struct dirent *ent;
1845   DIR *proc;
1846   long pid;
1847
1848   char cmdline[CMDLINE_BUFFER_SIZE];
1849
1850   int status;
1851   process_entry_t pse;
1852   char state;
1853
1854   running = sleeping = zombies = stopped = paging = blocked = 0;
1855   ps_list_reset();
1856
1857   if ((proc = opendir("/proc")) == NULL) {
1858     char errbuf[1024];
1859     ERROR("Cannot open `/proc': %s", sstrerror(errno, errbuf, sizeof(errbuf)));
1860     return -1;
1861   }
1862
1863   while ((ent = readdir(proc)) != NULL) {
1864     if (!isdigit(ent->d_name[0]))
1865       continue;
1866
1867     if ((pid = atol(ent->d_name)) < 1)
1868       continue;
1869
1870     memset(&pse, 0, sizeof(pse));
1871     pse.id = pid;
1872
1873     status = ps_read_process(pid, &pse, &state);
1874     if (status != 0) {
1875       DEBUG("ps_read_process failed: %i", status);
1876       continue;
1877     }
1878
1879     switch (state) {
1880     case 'R':
1881       running++;
1882       break;
1883     case 'S':
1884       sleeping++;
1885       break;
1886     case 'D':
1887       blocked++;
1888       break;
1889     case 'Z':
1890       zombies++;
1891       break;
1892     case 'T':
1893       stopped++;
1894       break;
1895     case 'W':
1896       paging++;
1897       break;
1898     }
1899
1900     ps_list_add(pse.name,
1901                 ps_get_cmdline(pid, pse.name, cmdline, sizeof(cmdline)), &pse);
1902   }
1903
1904   closedir(proc);
1905
1906   ps_submit_state("running", running);
1907   ps_submit_state("sleeping", sleeping);
1908   ps_submit_state("zombies", zombies);
1909   ps_submit_state("stopped", stopped);
1910   ps_submit_state("paging", paging);
1911   ps_submit_state("blocked", blocked);
1912
1913   for (procstat_t *ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
1914     ps_submit_proc_list(ps_ptr);
1915
1916   read_fork_rate();
1917 /* #endif KERNEL_LINUX */
1918
1919 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
1920   int running = 0;
1921   int sleeping = 0;
1922   int zombies = 0;
1923   int stopped = 0;
1924   int blocked = 0;
1925   int idle = 0;
1926   int wait = 0;
1927
1928   kvm_t *kd;
1929   char errbuf[_POSIX2_LINE_MAX];
1930   struct kinfo_proc *procs; /* array of processes */
1931   struct kinfo_proc *proc_ptr = NULL;
1932   int count; /* returns number of processes */
1933
1934   process_entry_t pse;
1935
1936   ps_list_reset();
1937
1938   /* Open the kvm interface, get a descriptor */
1939   kd = kvm_openfiles(NULL, "/dev/null", NULL, 0, errbuf);
1940   if (kd == NULL) {
1941     ERROR("processes plugin: Cannot open kvm interface: %s", errbuf);
1942     return 0;
1943   }
1944
1945   /* Get the list of processes. */
1946   procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, &count);
1947   if (procs == NULL) {
1948     ERROR("processes plugin: Cannot get kvm processes list: %s",
1949           kvm_geterr(kd));
1950     kvm_close(kd);
1951     return 0;
1952   }
1953
1954   /* Iterate through the processes in kinfo_proc */
1955   for (int i = 0; i < count; i++) {
1956     /* Create only one process list entry per _process_, i.e.
1957      * filter out threads (duplicate PID entries). */
1958     if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid)) {
1959       char cmdline[CMDLINE_BUFFER_SIZE] = "";
1960       _Bool have_cmdline = 0;
1961
1962       proc_ptr = &(procs[i]);
1963       /* Don't probe system processes and processes without arguments */
1964       if (((procs[i].ki_flag & P_SYSTEM) == 0) && (procs[i].ki_args != NULL)) {
1965         char **argv;
1966         int argc;
1967         int status;
1968
1969         /* retrieve the arguments */
1970         argv = kvm_getargv(kd, proc_ptr, /* nchr = */ 0);
1971         argc = 0;
1972         if ((argv != NULL) && (argv[0] != NULL)) {
1973           while (argv[argc] != NULL)
1974             argc++;
1975
1976           status = strjoin(cmdline, sizeof(cmdline), argv, argc, " ");
1977           if (status < 0)
1978             WARNING("processes plugin: Command line did not fit into buffer.");
1979           else
1980             have_cmdline = 1;
1981         }
1982       } /* if (process has argument list) */
1983
1984       memset(&pse, 0, sizeof(pse));
1985       pse.id = procs[i].ki_pid;
1986
1987       pse.num_proc = 1;
1988       pse.num_lwp = procs[i].ki_numthreads;
1989
1990       pse.vmem_size = procs[i].ki_size;
1991       pse.vmem_rss = procs[i].ki_rssize * pagesize;
1992       pse.vmem_data = procs[i].ki_dsize * pagesize;
1993       pse.vmem_code = procs[i].ki_tsize * pagesize;
1994       pse.stack_size = procs[i].ki_ssize * pagesize;
1995       pse.vmem_minflt_counter = procs[i].ki_rusage.ru_minflt;
1996       pse.vmem_majflt_counter = procs[i].ki_rusage.ru_majflt;
1997
1998       pse.cpu_user_counter = 0;
1999       pse.cpu_system_counter = 0;
2000       /*
2001        * The u-area might be swapped out, and we can't get
2002        * at it because we have a crashdump and no swap.
2003        * If it's here fill in these fields, otherwise, just
2004        * leave them 0.
2005        */
2006       if (procs[i].ki_flag & P_INMEM) {
2007         pse.cpu_user_counter = procs[i].ki_rusage.ru_utime.tv_usec +
2008                                (1000000lu * procs[i].ki_rusage.ru_utime.tv_sec);
2009         pse.cpu_system_counter =
2010             procs[i].ki_rusage.ru_stime.tv_usec +
2011             (1000000lu * procs[i].ki_rusage.ru_stime.tv_sec);
2012       }
2013
2014       /* no I/O data */
2015       pse.io_rchar = -1;
2016       pse.io_wchar = -1;
2017       pse.io_syscr = -1;
2018       pse.io_syscw = -1;
2019       pse.io_diskr = -1;
2020       pse.io_diskw = -1;
2021
2022       /* file descriptor count not implemented */
2023       pse.num_fd = 0;
2024
2025       /* Number of memory mappings */
2026       pse.num_maps = 0;
2027
2028       /* context switch counters not implemented */
2029       pse.cswitch_vol = -1;
2030       pse.cswitch_invol = -1;
2031
2032       ps_list_add(procs[i].ki_comm, have_cmdline ? cmdline : NULL, &pse);
2033
2034       switch (procs[i].ki_stat) {
2035       case SSTOP:
2036         stopped++;
2037         break;
2038       case SSLEEP:
2039         sleeping++;
2040         break;
2041       case SRUN:
2042         running++;
2043         break;
2044       case SIDL:
2045         idle++;
2046         break;
2047       case SWAIT:
2048         wait++;
2049         break;
2050       case SLOCK:
2051         blocked++;
2052         break;
2053       case SZOMB:
2054         zombies++;
2055         break;
2056       }
2057     } /* if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid)) */
2058   }
2059
2060   kvm_close(kd);
2061
2062   ps_submit_state("running", running);
2063   ps_submit_state("sleeping", sleeping);
2064   ps_submit_state("zombies", zombies);
2065   ps_submit_state("stopped", stopped);
2066   ps_submit_state("blocked", blocked);
2067   ps_submit_state("idle", idle);
2068   ps_submit_state("wait", wait);
2069
2070   for (procstat_t *ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2071     ps_submit_proc_list(ps_ptr);
2072 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
2073
2074 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_OPENBSD
2075   int running = 0;
2076   int sleeping = 0;
2077   int zombies = 0;
2078   int stopped = 0;
2079   int onproc = 0;
2080   int idle = 0;
2081   int dead = 0;
2082
2083   kvm_t *kd;
2084   char errbuf[1024];
2085   struct kinfo_proc *procs; /* array of processes */
2086   struct kinfo_proc *proc_ptr = NULL;
2087   int count; /* returns number of processes */
2088
2089   process_entry_t pse;
2090
2091   ps_list_reset();
2092
2093   /* Open the kvm interface, get a descriptor */
2094   kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
2095   if (kd == NULL) {
2096     ERROR("processes plugin: Cannot open kvm interface: %s", errbuf);
2097     return 0;
2098   }
2099
2100   /* Get the list of processes. */
2101   procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc), &count);
2102   if (procs == NULL) {
2103     ERROR("processes plugin: Cannot get kvm processes list: %s",
2104           kvm_geterr(kd));
2105     kvm_close(kd);
2106     return 0;
2107   }
2108
2109   /* Iterate through the processes in kinfo_proc */
2110   for (int i = 0; i < count; i++) {
2111     /* Create only one process list entry per _process_, i.e.
2112      * filter out threads (duplicate PID entries). */
2113     if ((proc_ptr == NULL) || (proc_ptr->p_pid != procs[i].p_pid)) {
2114       char cmdline[CMDLINE_BUFFER_SIZE] = "";
2115       _Bool have_cmdline = 0;
2116
2117       proc_ptr = &(procs[i]);
2118       /* Don't probe zombie processes  */
2119       if (!P_ZOMBIE(proc_ptr)) {
2120         char **argv;
2121         int argc;
2122         int status;
2123
2124         /* retrieve the arguments */
2125         argv = kvm_getargv(kd, proc_ptr, /* nchr = */ 0);
2126         argc = 0;
2127         if ((argv != NULL) && (argv[0] != NULL)) {
2128           while (argv[argc] != NULL)
2129             argc++;
2130
2131           status = strjoin(cmdline, sizeof(cmdline), argv, argc, " ");
2132           if (status < 0)
2133             WARNING("processes plugin: Command line did not fit into buffer.");
2134           else
2135             have_cmdline = 1;
2136         }
2137       } /* if (process has argument list) */
2138
2139       memset(&pse, 0, sizeof(pse));
2140       pse.id = procs[i].p_pid;
2141
2142       pse.num_proc = 1;
2143       pse.num_lwp = 1; /* XXX: accumulate p_tid values for a single p_pid ? */
2144
2145       pse.vmem_rss = procs[i].p_vm_rssize * pagesize;
2146       pse.vmem_data = procs[i].p_vm_dsize * pagesize;
2147       pse.vmem_code = procs[i].p_vm_tsize * pagesize;
2148       pse.stack_size = procs[i].p_vm_ssize * pagesize;
2149       pse.vmem_size = pse.stack_size + pse.vmem_code + pse.vmem_data;
2150       pse.vmem_minflt_counter = procs[i].p_uru_minflt;
2151       pse.vmem_majflt_counter = procs[i].p_uru_majflt;
2152
2153       pse.cpu_user_counter =
2154           procs[i].p_uutime_usec + (1000000lu * procs[i].p_uutime_sec);
2155       pse.cpu_system_counter =
2156           procs[i].p_ustime_usec + (1000000lu * procs[i].p_ustime_sec);
2157
2158       /* no I/O data */
2159       pse.io_rchar = -1;
2160       pse.io_wchar = -1;
2161       pse.io_syscr = -1;
2162       pse.io_syscw = -1;
2163       pse.io_diskr = -1;
2164       pse.io_diskw = -1;
2165
2166       /* file descriptor count not implemented */
2167       pse.num_fd = 0;
2168
2169       /* Number of memory mappings */
2170       pse.num_maps = 0;
2171
2172       /* context switch counters not implemented */
2173       pse.cswitch_vol = -1;
2174       pse.cswitch_invol = -1;
2175
2176       ps_list_add(procs[i].p_comm, have_cmdline ? cmdline : NULL, &pse);
2177
2178       switch (procs[i].p_stat) {
2179       case SSTOP:
2180         stopped++;
2181         break;
2182       case SSLEEP:
2183         sleeping++;
2184         break;
2185       case SRUN:
2186         running++;
2187         break;
2188       case SIDL:
2189         idle++;
2190         break;
2191       case SONPROC:
2192         onproc++;
2193         break;
2194       case SDEAD:
2195         dead++;
2196         break;
2197       case SZOMB:
2198         zombies++;
2199         break;
2200       }
2201     } /* if ((proc_ptr == NULL) || (proc_ptr->p_pid != procs[i].p_pid)) */
2202   }
2203
2204   kvm_close(kd);
2205
2206   ps_submit_state("running", running);
2207   ps_submit_state("sleeping", sleeping);
2208   ps_submit_state("zombies", zombies);
2209   ps_submit_state("stopped", stopped);
2210   ps_submit_state("onproc", onproc);
2211   ps_submit_state("idle", idle);
2212   ps_submit_state("dead", dead);
2213
2214   for (procstat_t *ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2215     ps_submit_proc_list(ps_ptr);
2216 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_OPENBSD */
2217
2218 #elif HAVE_PROCINFO_H
2219   /* AIX */
2220   int running = 0;
2221   int sleeping = 0;
2222   int zombies = 0;
2223   int stopped = 0;
2224   int paging = 0;
2225   int blocked = 0;
2226
2227   pid_t pindex = 0;
2228   int nprocs;
2229
2230   process_entry_t pse;
2231
2232   ps_list_reset();
2233   while ((nprocs = getprocs64(procentry, sizeof(struct procentry64),
2234                               /* fdsinfo = */ NULL, sizeof(struct fdsinfo64),
2235                               &pindex, MAXPROCENTRY)) > 0) {
2236     for (int i = 0; i < nprocs; i++) {
2237       tid64_t thindex;
2238       int nthreads;
2239       char arglist[MAXARGLN + 1];
2240       char *cargs;
2241       char *cmdline;
2242
2243       if (procentry[i].pi_state == SNONE)
2244         continue;
2245       /* if (procentry[i].pi_state == SZOMB)  FIXME */
2246
2247       cmdline = procentry[i].pi_comm;
2248       cargs = procentry[i].pi_comm;
2249       if (procentry[i].pi_flags & SKPROC) {
2250         if (procentry[i].pi_pid == 0)
2251           cmdline = "swapper";
2252         cargs = cmdline;
2253       } else {
2254         if (getargs(&procentry[i], sizeof(struct procentry64), arglist,
2255                     MAXARGLN) >= 0) {
2256           int n;
2257
2258           n = -1;
2259           while (++n < MAXARGLN) {
2260             if (arglist[n] == '\0') {
2261               if (arglist[n + 1] == '\0')
2262                 break;
2263               arglist[n] = ' ';
2264             }
2265           }
2266           cargs = arglist;
2267         }
2268       }
2269
2270       memset(&pse, 0, sizeof(pse));
2271
2272       pse.id = procentry[i].pi_pid;
2273       pse.num_lwp = procentry[i].pi_thcount;
2274       pse.num_proc = 1;
2275
2276       thindex = 0;
2277       while ((nthreads = getthrds64(procentry[i].pi_pid, thrdentry,
2278                                     sizeof(struct thrdentry64), &thindex,
2279                                     MAXTHRDENTRY)) > 0) {
2280         int j;
2281
2282         for (j = 0; j < nthreads; j++) {
2283           switch (thrdentry[j].ti_state) {
2284           /* case TSNONE: break; */
2285           case TSIDL:
2286             blocked++;
2287             break; /* FIXME is really blocked */
2288           case TSRUN:
2289             running++;
2290             break;
2291           case TSSLEEP:
2292             sleeping++;
2293             break;
2294           case TSSWAP:
2295             paging++;
2296             break;
2297           case TSSTOP:
2298             stopped++;
2299             break;
2300           case TSZOMB:
2301             zombies++;
2302             break;
2303           }
2304         }
2305         if (nthreads < MAXTHRDENTRY)
2306           break;
2307       }
2308
2309       /* tv_usec is nanosec ??? */
2310       pse.cpu_user_counter = procentry[i].pi_ru.ru_utime.tv_sec * 1000000 +
2311                              procentry[i].pi_ru.ru_utime.tv_usec / 1000;
2312
2313       /* tv_usec is nanosec ??? */
2314       pse.cpu_system_counter = procentry[i].pi_ru.ru_stime.tv_sec * 1000000 +
2315                                procentry[i].pi_ru.ru_stime.tv_usec / 1000;
2316
2317       pse.vmem_minflt_counter = procentry[i].pi_minflt;
2318       pse.vmem_majflt_counter = procentry[i].pi_majflt;
2319
2320       pse.vmem_size = procentry[i].pi_tsize + procentry[i].pi_dvm * pagesize;
2321       pse.vmem_rss = (procentry[i].pi_drss + procentry[i].pi_trss) * pagesize;
2322       /* Not supported/implemented */
2323       pse.vmem_data = 0;
2324       pse.vmem_code = 0;
2325       pse.stack_size = 0;
2326
2327       pse.io_rchar = -1;
2328       pse.io_wchar = -1;
2329       pse.io_syscr = -1;
2330       pse.io_syscw = -1;
2331       pse.io_diskr = -1;
2332       pse.io_diskw = -1;
2333
2334       pse.num_fd = 0;
2335       pse.num_maps = 0;
2336
2337       pse.cswitch_vol = -1;
2338       pse.cswitch_invol = -1;
2339
2340       ps_list_add(cmdline, cargs, &pse);
2341     } /* for (i = 0 .. nprocs) */
2342
2343     if (nprocs < MAXPROCENTRY)
2344       break;
2345   } /* while (getprocs64() > 0) */
2346   ps_submit_state("running", running);
2347   ps_submit_state("sleeping", sleeping);
2348   ps_submit_state("zombies", zombies);
2349   ps_submit_state("stopped", stopped);
2350   ps_submit_state("paging", paging);
2351   ps_submit_state("blocked", blocked);
2352
2353   for (procstat_t *ps = list_head_g; ps != NULL; ps = ps->next)
2354     ps_submit_proc_list(ps);
2355 /* #endif HAVE_PROCINFO_H */
2356
2357 #elif KERNEL_SOLARIS
2358   /*
2359    * The Solaris section adds a few more process states and removes some
2360    * process states compared to linux. Most notably there is no "PAGING"
2361    * and "BLOCKED" state for a process.  The rest is similar to the linux
2362    * code.
2363    */
2364   int running = 0;
2365   int sleeping = 0;
2366   int zombies = 0;
2367   int stopped = 0;
2368   int detached = 0;
2369   int daemon = 0;
2370   int system = 0;
2371   int orphan = 0;
2372
2373   struct dirent *ent;
2374   DIR *proc;
2375
2376   int status;
2377   char state;
2378
2379   char cmdline[PRARGSZ];
2380
2381   ps_list_reset();
2382
2383   proc = opendir("/proc");
2384   if (proc == NULL)
2385     return -1;
2386
2387   while ((ent = readdir(proc)) != NULL) {
2388     long pid;
2389     process_entry_t pse;
2390     char *endptr;
2391
2392     if (!isdigit((int)ent->d_name[0]))
2393       continue;
2394
2395     pid = strtol(ent->d_name, &endptr, 10);
2396     if (*endptr != 0) /* value didn't completely parse as a number */
2397       continue;
2398
2399     memset(&pse, 0, sizeof(pse));
2400     pse.id = pid;
2401
2402     status = ps_read_process(pid, &pse, &state);
2403     if (status != 0) {
2404       DEBUG("ps_read_process failed: %i", status);
2405       continue;
2406     }
2407
2408     switch (state) {
2409     case 'R':
2410       running++;
2411       break;
2412     case 'S':
2413       sleeping++;
2414       break;
2415     case 'E':
2416       detached++;
2417       break;
2418     case 'Z':
2419       zombies++;
2420       break;
2421     case 'T':
2422       stopped++;
2423       break;
2424     case 'A':
2425       daemon++;
2426       break;
2427     case 'Y':
2428       system++;
2429       break;
2430     case 'O':
2431       orphan++;
2432       break;
2433     }
2434
2435     ps_list_add(pse.name,
2436                 ps_get_cmdline(pid, pse.name, cmdline, sizeof(cmdline)), &pse);
2437   } /* while(readdir) */
2438   closedir(proc);
2439
2440   ps_submit_state("running", running);
2441   ps_submit_state("sleeping", sleeping);
2442   ps_submit_state("zombies", zombies);
2443   ps_submit_state("stopped", stopped);
2444   ps_submit_state("detached", detached);
2445   ps_submit_state("daemon", daemon);
2446   ps_submit_state("system", system);
2447   ps_submit_state("orphan", orphan);
2448
2449   for (procstat_t *ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2450     ps_submit_proc_list(ps_ptr);
2451
2452   read_fork_rate();
2453 #endif /* KERNEL_SOLARIS */
2454
2455   want_init = 0;
2456
2457   return 0;
2458 } /* int ps_read */
2459
2460 void module_register(void) {
2461   plugin_register_complex_config("processes", ps_config);
2462   plugin_register_init("processes", ps_init);
2463   plugin_register_read("processes", ps_read);
2464 } /* void module_register */