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