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