Code

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