Code

liboconfig/oconfig.c: remove unneeded assigment
[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 (name_start_pos < buffer_len && buffer[name_start_pos] != '(')
1042                 name_start_pos++;
1044         name_end_pos = buffer_len;
1045         while (name_end_pos > 0 && buffer[name_end_pos] != ')')
1046                 name_end_pos--;
1048         /* Either '(' or ')' is not found or they are in the wrong order.
1049          * Anyway, something weird that shouldn't happen ever. */
1050         if (name_start_pos >= name_end_pos)
1051         {
1052                 ERROR ("processes plugin: name_start_pos = %zu >= name_end_pos = %zu",
1053                                 name_start_pos, name_end_pos);
1054                 return (-1);
1055         }
1057         name_len = (name_end_pos - name_start_pos) - 1;
1058         if (name_len >= sizeof (ps->name))
1059                 name_len = sizeof (ps->name) - 1;
1061         sstrncpy (ps->name, &buffer[name_start_pos + 1], name_len + 1);
1063         if ((buffer_len - name_end_pos) < 2)
1064                 return (-1);
1065         buffer_ptr = &buffer[name_end_pos + 2];
1067         fields_len = strsplit (buffer_ptr, fields, STATIC_ARRAY_SIZE (fields));
1068         if (fields_len < 22)
1069         {
1070                 DEBUG ("processes plugin: ps_read_process (pid = %li):"
1071                                 " `%s' has only %i fields..",
1072                                 pid, filename, fields_len);
1073                 return (-1);
1074         }
1076         *state = fields[0][0];
1078         if (*state == 'Z')
1079         {
1080                 ps->num_lwp  = 0;
1081                 ps->num_proc = 0;
1082         }
1083         else
1084         {
1085                 ps->num_lwp = strtoul (fields[17], /* endptr = */ NULL, /* base = */ 10);
1086                 if ((ps_read_status(pid, ps)) == NULL)
1087                 {
1088                         /* No VMem data */
1089                         ps->vmem_data = -1;
1090                         ps->vmem_code = -1;
1091                         DEBUG("ps_read_process: did not get vmem data for pid %li", pid);
1092                 }
1093                 if (ps->num_lwp == 0)
1094                         ps->num_lwp = 1;
1095                 ps->num_proc = 1;
1096         }
1098         /* Leave the rest at zero if this is only a zombi */
1099         if (ps->num_proc == 0)
1100         {
1101                 DEBUG ("processes plugin: This is only a zombie: pid = %li; "
1102                                 "name = %s;", pid, ps->name);
1103                 return (0);
1104         }
1106         cpu_user_counter   = atoll (fields[11]);
1107         cpu_system_counter = atoll (fields[12]);
1108         vmem_size          = atoll (fields[20]);
1109         vmem_rss           = atoll (fields[21]);
1110         ps->vmem_minflt_counter = atol (fields[7]);
1111         ps->vmem_majflt_counter = atol (fields[9]);
1113         {
1114                 unsigned long long stack_start = atoll (fields[25]);
1115                 unsigned long long stack_ptr   = atoll (fields[26]);
1117                 stack_size = (stack_start > stack_ptr)
1118                         ? stack_start - stack_ptr
1119                         : stack_ptr - stack_start;
1120         }
1122         /* Convert jiffies to useconds */
1123         cpu_user_counter   = cpu_user_counter   * 1000000 / CONFIG_HZ;
1124         cpu_system_counter = cpu_system_counter * 1000000 / CONFIG_HZ;
1125         vmem_rss = vmem_rss * pagesize_g;
1127         ps->cpu_user_counter = cpu_user_counter;
1128         ps->cpu_system_counter = cpu_system_counter;
1129         ps->vmem_size = (unsigned long) vmem_size;
1130         ps->vmem_rss = (unsigned long) vmem_rss;
1131         ps->stack_size = (unsigned long) stack_size;
1133         if ( (ps_read_io (pid, ps)) == NULL)
1134         {
1135                 /* no io data */
1136                 ps->io_rchar = -1;
1137                 ps->io_wchar = -1;
1138                 ps->io_syscr = -1;
1139                 ps->io_syscw = -1;
1141                 DEBUG("ps_read_process: not get io data for pid %li", pid);
1142         }
1144         if ( report_ctx_switch )
1145         {
1146                 if ( (ps_read_tasks_status(pid, ps)) == NULL)
1147                 {
1148                         ps->cswitch_vol = -1;
1149                         ps->cswitch_invol = -1;
1151                         DEBUG("ps_read_tasks_status: not get context "
1152                                         "switch data for pid %li", pid);
1153                 }
1154         }
1156         /* success */
1157         return (0);
1158 } /* int ps_read_process (...) */
1160 static char *ps_get_cmdline (long pid, char *name, char *buf, size_t buf_len)
1162         char  *buf_ptr;
1163         size_t len;
1165         char file[PATH_MAX];
1166         int  fd;
1168         size_t n;
1170         if ((pid < 1) || (NULL == buf) || (buf_len < 2))
1171                 return NULL;
1173         ssnprintf (file, sizeof (file), "/proc/%li/cmdline", pid);
1175         errno = 0;
1176         fd = open (file, O_RDONLY);
1177         if (fd < 0) {
1178                 char errbuf[4096];
1179                 /* ENOENT means the process exited while we were handling it.
1180                  * Don't complain about this, it only fills the logs. */
1181                 if (errno != ENOENT)
1182                         WARNING ("processes plugin: Failed to open `%s': %s.", file,
1183                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1184                 return NULL;
1185         }
1187         buf_ptr = buf;
1188         len     = buf_len;
1190         n = 0;
1192         while (42) {
1193                 ssize_t status;
1195                 status = read (fd, (void *)buf_ptr, len);
1197                 if (status < 0) {
1198                         char errbuf[1024];
1200                         if ((EAGAIN == errno) || (EINTR == errno))
1201                                 continue;
1203                         WARNING ("processes plugin: Failed to read from `%s': %s.", file,
1204                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1205                         close (fd);
1206                         return NULL;
1207                 }
1209                 n += status;
1211                 if (status == 0)
1212                         break;
1214                 buf_ptr += status;
1215                 len     -= status;
1217                 if (len == 0)
1218                         break;
1219         }
1221         close (fd);
1223         if (0 == n) {
1224                 /* cmdline not available; e.g. kernel thread, zombie */
1225                 if (NULL == name)
1226                         return NULL;
1228                 ssnprintf (buf, buf_len, "[%s]", name);
1229                 return buf;
1230         }
1232         assert (n <= buf_len);
1234         if (n == buf_len)
1235                 --n;
1236         buf[n] = '\0';
1238         --n;
1239         /* remove trailing whitespace */
1240         while ((n > 0) && (isspace (buf[n]) || ('\0' == buf[n]))) {
1241                 buf[n] = '\0';
1242                 --n;
1243         }
1245         /* arguments are separated by '\0' in /proc/<pid>/cmdline */
1246         while (n > 0) {
1247                 if ('\0' == buf[n])
1248                         buf[n] = ' ';
1249                 --n;
1250         }
1251         return buf;
1252 } /* char *ps_get_cmdline (...) */
1254 static int read_fork_rate (void)
1256         FILE *proc_stat;
1257         char buffer[1024];
1258         value_t value;
1259         _Bool value_valid = 0;
1261         proc_stat = fopen ("/proc/stat", "r");
1262         if (proc_stat == NULL)
1263         {
1264                 char errbuf[1024];
1265                 ERROR ("processes plugin: fopen (/proc/stat) failed: %s",
1266                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1267                 return (-1);
1268         }
1270         while (fgets (buffer, sizeof (buffer), proc_stat) != NULL)
1271         {
1272                 int status;
1273                 char *fields[3];
1274                 int fields_num;
1276                 fields_num = strsplit (buffer, fields,
1277                                 STATIC_ARRAY_SIZE (fields));
1278                 if (fields_num != 2)
1279                         continue;
1281                 if (strcmp ("processes", fields[0]) != 0)
1282                         continue;
1284                 status = parse_value (fields[1], &value, DS_TYPE_DERIVE);
1285                 if (status == 0)
1286                         value_valid = 1;
1288                 break;
1289         }
1290         fclose(proc_stat);
1292         if (!value_valid)
1293                 return (-1);
1295         ps_submit_fork_rate (value.derive);
1296         return (0);
1298 #endif /*KERNEL_LINUX */
1300 #if KERNEL_SOLARIS
1301 static char *ps_get_cmdline (long pid, char *name __attribute__((unused)), /* {{{ */
1302     char *buffer, size_t buffer_size)
1304         char path[PATH_MAX];
1305         psinfo_t info;
1306         ssize_t status;
1308         snprintf(path, sizeof (path), "/proc/%li/psinfo", pid);
1310         status = read_file_contents (path, (void *) &info, sizeof (info));
1311         if ((status < 0) || (((size_t) status) != sizeof (info)))
1312         {
1313                 ERROR ("processes plugin: Unexpected return value "
1314                                 "while reading \"%s\": "
1315                                 "Returned %zd but expected %zu.",
1316                                 path, status, buffer_size);
1317                 return (NULL);
1318         }
1320         info.pr_psargs[sizeof (info.pr_psargs) - 1] = 0;
1321         sstrncpy (buffer, info.pr_psargs, buffer_size);
1323         return (buffer);
1324 } /* }}} int ps_get_cmdline */
1326 /*
1327  * Reads process information on the Solaris OS. The information comes mainly from
1328  * /proc/PID/status, /proc/PID/psinfo and /proc/PID/usage
1329  * The values for input and ouput chars are calculated "by hand"
1330  * Added a few "solaris" specific process states as well
1331  */
1332 static int ps_read_process(long pid, procstat_t *ps, char *state)
1334         char filename[64];
1335         char f_psinfo[64], f_usage[64];
1336         char *buffer;
1338         pstatus_t *myStatus;
1339         psinfo_t *myInfo;
1340         prusage_t *myUsage;
1342         snprintf(filename, sizeof (filename), "/proc/%li/status", pid);
1343         snprintf(f_psinfo, sizeof (f_psinfo), "/proc/%li/psinfo", pid);
1344         snprintf(f_usage, sizeof (f_usage), "/proc/%li/usage", pid);
1347         buffer = calloc(1, sizeof (pstatus_t));
1348         read_file_contents(filename, buffer, sizeof (pstatus_t));
1349         myStatus = (pstatus_t *) buffer;
1351         buffer = calloc(1, sizeof (psinfo_t));
1352         read_file_contents(f_psinfo, buffer, sizeof (psinfo_t));
1353         myInfo = (psinfo_t *) buffer;
1355         buffer = calloc(1, sizeof (prusage_t));
1356         read_file_contents(f_usage, buffer, sizeof (prusage_t));
1357         myUsage = (prusage_t *) buffer;
1359         sstrncpy(ps->name, myInfo->pr_fname, sizeof (myInfo->pr_fname));
1360         ps->num_lwp = myStatus->pr_nlwp;
1361         if (myInfo->pr_wstat != 0) {
1362                 ps->num_proc = 0;
1363                 ps->num_lwp = 0;
1364                 *state = (char) 'Z';
1366                 sfree(myStatus);
1367                 sfree(myInfo);
1368                 sfree(myUsage);
1369                 return (0);
1370         } else {
1371                 ps->num_proc = 1;
1372                 ps->num_lwp = myInfo->pr_nlwp;
1373         }
1375         /*
1376          * Convert system time and user time from nanoseconds to microseconds
1377          * for compatibility with the linux module
1378          */
1379         ps->cpu_system_counter = myStatus -> pr_stime.tv_nsec / 1000;
1380         ps->cpu_user_counter = myStatus -> pr_utime.tv_nsec / 1000;
1382         /*
1383          * Convert rssize from KB to bytes to be consistent w/ the linux module
1384          */
1385         ps->vmem_rss = myInfo->pr_rssize * 1024;
1386         ps->vmem_size = myInfo->pr_size * 1024;
1387         ps->vmem_minflt_counter = myUsage->pr_minf;
1388         ps->vmem_majflt_counter = myUsage->pr_majf;
1390         /*
1391          * TODO: Data and code segment calculations for Solaris
1392          */
1394         ps->vmem_data = -1;
1395         ps->vmem_code = -1;
1396         ps->stack_size = myStatus->pr_stksize;
1398         /*
1399          * Calculating input/ouput chars
1400          * Formula used is total chars / total blocks => chars/block
1401          * then convert input/output blocks to chars
1402          */
1403         ulong_t tot_chars = myUsage->pr_ioch;
1404         ulong_t tot_blocks = myUsage->pr_inblk + myUsage->pr_oublk;
1405         ulong_t chars_per_block = 1;
1406         if (tot_blocks != 0)
1407                 chars_per_block = tot_chars / tot_blocks;
1408         ps->io_rchar = myUsage->pr_inblk * chars_per_block;
1409         ps->io_wchar = myUsage->pr_oublk * chars_per_block;
1410         ps->io_syscr = myUsage->pr_sysc;
1411         ps->io_syscw = myUsage->pr_sysc;
1413         /*
1414          * TODO: context switch counters for Solaris
1415    */
1416         ps->cswitch_vol   = -1;
1417         ps->cswitch_invol = -1;
1420         /*
1421          * TODO: Find way of setting BLOCKED and PAGING status
1422          */
1424         *state = (char) 'R';
1425         if (myStatus->pr_flags & PR_ASLEEP)
1426                 *state = (char) 'S';
1427         else if (myStatus->pr_flags & PR_STOPPED)
1428                 *state = (char) 'T';
1429         else if (myStatus->pr_flags & PR_DETACH)
1430                 *state = (char) 'E';
1431         else if (myStatus->pr_flags & PR_DAEMON)
1432                 *state = (char) 'A';
1433         else if (myStatus->pr_flags & PR_ISSYS)
1434                 *state = (char) 'Y';
1435         else if (myStatus->pr_flags & PR_ORPHAN)
1436                 *state = (char) 'O';
1438         sfree(myStatus);
1439         sfree(myInfo);
1440         sfree(myUsage);
1442         return (0);
1445 /*
1446  * Reads the number of threads created since the last reboot. On Solaris these
1447  * are retrieved from kstat (module cpu, name sys, class misc, stat nthreads).
1448  * The result is the sum for all the threads created on each cpu
1449  */
1450 static int read_fork_rate (void)
1452         extern kstat_ctl_t *kc;
1453         kstat_t *ksp_chain = NULL;
1454         derive_t result = 0;
1456         if (kc == NULL)
1457                 return (-1);
1459         for (ksp_chain = kc->kc_chain;
1460                         ksp_chain != NULL;
1461                         ksp_chain = ksp_chain->ks_next)
1462         {
1463                 if ((strcmp (ksp_chain->ks_module, "cpu") == 0)
1464                                 && (strcmp (ksp_chain->ks_name, "sys") == 0)
1465                                 && (strcmp (ksp_chain->ks_class, "misc") == 0))
1466                 {
1467                         long long tmp;
1469                         kstat_read (kc, ksp_chain, NULL);
1471                         tmp = get_kstat_value(ksp_chain, "nthreads");
1472                         if (tmp != -1LL)
1473                                 result += tmp;
1474                 }
1475         }
1477         ps_submit_fork_rate (result);
1478         return (0);
1480 #endif /* KERNEL_SOLARIS */
1482 #if HAVE_THREAD_INFO
1483 static int mach_get_task_name (task_t t, int *pid, char *name, size_t name_max_len)
1485         int mib[4];
1487         struct kinfo_proc kp;
1488         size_t            kp_size;
1490         mib[0] = CTL_KERN;
1491         mib[1] = KERN_PROC;
1492         mib[2] = KERN_PROC_PID;
1494         if (pid_for_task (t, pid) != KERN_SUCCESS)
1495                 return (-1);
1496         mib[3] = *pid;
1498         kp_size = sizeof (kp);
1499         if (sysctl (mib, 4, &kp, &kp_size, NULL, 0) != 0)
1500                 return (-1);
1502         if (name_max_len > (MAXCOMLEN + 1))
1503                 name_max_len = MAXCOMLEN + 1;
1505         strncpy (name, kp.kp_proc.p_comm, name_max_len - 1);
1506         name[name_max_len - 1] = '\0';
1508         DEBUG ("pid = %i; name = %s;", *pid, name);
1510         /* We don't do the special handling for `p_comm == "LaunchCFMApp"' as
1511          * `top' does it, because it is a lot of work and only used when
1512          * debugging. -octo */
1514         return (0);
1516 #endif /* HAVE_THREAD_INFO */
1517 /* ------- end of additional functions for KERNEL_LINUX/HAVE_THREAD_INFO ------- */
1519 /* do actual readings from kernel */
1520 static int ps_read (void)
1522 #if HAVE_THREAD_INFO
1523         kern_return_t            status;
1525         int                      pset;
1526         processor_set_t          port_pset_priv;
1528         int                      task;
1529         task_array_t             task_list;
1530         mach_msg_type_number_t   task_list_len;
1532         int                      task_pid;
1533         char                     task_name[MAXCOMLEN + 1];
1535         int                      thread;
1536         thread_act_array_t       thread_list;
1537         mach_msg_type_number_t   thread_list_len;
1538         thread_basic_info_data_t thread_data;
1539         mach_msg_type_number_t   thread_data_len;
1541         int running  = 0;
1542         int sleeping = 0;
1543         int zombies  = 0;
1544         int stopped  = 0;
1545         int blocked  = 0;
1547         procstat_t *ps;
1548         procstat_entry_t pse;
1550         ps_list_reset ();
1552         /*
1553          * The Mach-concept is a little different from the traditional UNIX
1554          * concept: All the work is done in threads. Threads are contained in
1555          * `tasks'. Therefore, `task status' doesn't make much sense, since
1556          * it's actually a `thread status'.
1557          * Tasks are assigned to sets of processors, so that's where you go to
1558          * get a list.
1559          */
1560         for (pset = 0; pset < pset_list_len; pset++)
1561         {
1562                 if ((status = host_processor_set_priv (port_host_self,
1563                                                 pset_list[pset],
1564                                                 &port_pset_priv)) != KERN_SUCCESS)
1565                 {
1566                         ERROR ("host_processor_set_priv failed: %s\n",
1567                                         mach_error_string (status));
1568                         continue;
1569                 }
1571                 if ((status = processor_set_tasks (port_pset_priv,
1572                                                 &task_list,
1573                                                 &task_list_len)) != KERN_SUCCESS)
1574                 {
1575                         ERROR ("processor_set_tasks failed: %s\n",
1576                                         mach_error_string (status));
1577                         mach_port_deallocate (port_task_self, port_pset_priv);
1578                         continue;
1579                 }
1581                 for (task = 0; task < task_list_len; task++)
1582                 {
1583                         ps = NULL;
1584                         if (mach_get_task_name (task_list[task],
1585                                                 &task_pid,
1586                                                 task_name, PROCSTAT_NAME_LEN) == 0)
1587                         {
1588                                 /* search for at least one match */
1589                                 for (ps = list_head_g; ps != NULL; ps = ps->next)
1590                                         /* FIXME: cmdline should be here instead of NULL */
1591                                         if (ps_list_match (task_name, NULL, ps) == 1)
1592                                                 break;
1593                         }
1595                         /* Collect more detailed statistics for this process */
1596                         if (ps != NULL)
1597                         {
1598                                 task_basic_info_data_t        task_basic_info;
1599                                 mach_msg_type_number_t        task_basic_info_len;
1600                                 task_events_info_data_t       task_events_info;
1601                                 mach_msg_type_number_t        task_events_info_len;
1602                                 task_absolutetime_info_data_t task_absolutetime_info;
1603                                 mach_msg_type_number_t        task_absolutetime_info_len;
1605                                 memset (&pse, '\0', sizeof (pse));
1606                                 pse.id = task_pid;
1608                                 task_basic_info_len = TASK_BASIC_INFO_COUNT;
1609                                 status = task_info (task_list[task],
1610                                                 TASK_BASIC_INFO,
1611                                                 (task_info_t) &task_basic_info,
1612                                                 &task_basic_info_len);
1613                                 if (status != KERN_SUCCESS)
1614                                 {
1615                                         ERROR ("task_info failed: %s",
1616                                                         mach_error_string (status));
1617                                         continue; /* with next thread_list */
1618                                 }
1620                                 task_events_info_len = TASK_EVENTS_INFO_COUNT;
1621                                 status = task_info (task_list[task],
1622                                                 TASK_EVENTS_INFO,
1623                                                 (task_info_t) &task_events_info,
1624                                                 &task_events_info_len);
1625                                 if (status != KERN_SUCCESS)
1626                                 {
1627                                         ERROR ("task_info failed: %s",
1628                                                         mach_error_string (status));
1629                                         continue; /* with next thread_list */
1630                                 }
1632                                 task_absolutetime_info_len = TASK_ABSOLUTETIME_INFO_COUNT;
1633                                 status = task_info (task_list[task],
1634                                                 TASK_ABSOLUTETIME_INFO,
1635                                                 (task_info_t) &task_absolutetime_info,
1636                                                 &task_absolutetime_info_len);
1637                                 if (status != KERN_SUCCESS)
1638                                 {
1639                                         ERROR ("task_info failed: %s",
1640                                                         mach_error_string (status));
1641                                         continue; /* with next thread_list */
1642                                 }
1644                                 pse.num_proc++;
1645                                 pse.vmem_size = task_basic_info.virtual_size;
1646                                 pse.vmem_rss = task_basic_info.resident_size;
1647                                 /* Does not seem to be easily exposed */
1648                                 pse.vmem_data = 0;
1649                                 pse.vmem_code = 0;
1651                                 pse.vmem_minflt_counter = task_events_info.cow_faults;
1652                                 pse.vmem_majflt_counter = task_events_info.faults;
1654                                 pse.cpu_user_counter = task_absolutetime_info.total_user;
1655                                 pse.cpu_system_counter = task_absolutetime_info.total_system;
1657                                 /* context switch counters not implemented */
1658                                 pse.cswitch_vol   = -1;
1659                                 pse.cswitch_invol = -1;
1660                         }
1662                         status = task_threads (task_list[task], &thread_list,
1663                                         &thread_list_len);
1664                         if (status != KERN_SUCCESS)
1665                         {
1666                                 /* Apple's `top' treats this case a zombie. It
1667                                  * makes sense to some extend: A `zombie'
1668                                  * thread is nonsense, since the task/process
1669                                  * is dead. */
1670                                 zombies++;
1671                                 DEBUG ("task_threads failed: %s",
1672                                                 mach_error_string (status));
1673                                 if (task_list[task] != port_task_self)
1674                                         mach_port_deallocate (port_task_self,
1675                                                         task_list[task]);
1676                                 continue; /* with next task_list */
1677                         }
1679                         for (thread = 0; thread < thread_list_len; thread++)
1680                         {
1681                                 thread_data_len = THREAD_BASIC_INFO_COUNT;
1682                                 status = thread_info (thread_list[thread],
1683                                                 THREAD_BASIC_INFO,
1684                                                 (thread_info_t) &thread_data,
1685                                                 &thread_data_len);
1686                                 if (status != KERN_SUCCESS)
1687                                 {
1688                                         ERROR ("thread_info failed: %s",
1689                                                         mach_error_string (status));
1690                                         if (task_list[task] != port_task_self)
1691                                                 mach_port_deallocate (port_task_self,
1692                                                                 thread_list[thread]);
1693                                         continue; /* with next thread_list */
1694                                 }
1696                                 if (ps != NULL)
1697                                         pse.num_lwp++;
1699                                 switch (thread_data.run_state)
1700                                 {
1701                                         case TH_STATE_RUNNING:
1702                                                 running++;
1703                                                 break;
1704                                         case TH_STATE_STOPPED:
1705                                         /* What exactly is `halted'? */
1706                                         case TH_STATE_HALTED:
1707                                                 stopped++;
1708                                                 break;
1709                                         case TH_STATE_WAITING:
1710                                                 sleeping++;
1711                                                 break;
1712                                         case TH_STATE_UNINTERRUPTIBLE:
1713                                                 blocked++;
1714                                                 break;
1715                                         /* There is no `zombie' case here,
1716                                          * since there are no zombie-threads.
1717                                          * There's only zombie tasks, which are
1718                                          * handled above. */
1719                                         default:
1720                                                 WARNING ("Unknown thread status: %i",
1721                                                                 thread_data.run_state);
1722                                                 break;
1723                                 } /* switch (thread_data.run_state) */
1725                                 if (task_list[task] != port_task_self)
1726                                 {
1727                                         status = mach_port_deallocate (port_task_self,
1728                                                         thread_list[thread]);
1729                                         if (status != KERN_SUCCESS)
1730                                                 ERROR ("mach_port_deallocate failed: %s",
1731                                                                 mach_error_string (status));
1732                                 }
1733                         } /* for (thread_list) */
1735                         if ((status = vm_deallocate (port_task_self,
1736                                                         (vm_address_t) thread_list,
1737                                                         thread_list_len * sizeof (thread_act_t)))
1738                                         != KERN_SUCCESS)
1739                         {
1740                                 ERROR ("vm_deallocate failed: %s",
1741                                                 mach_error_string (status));
1742                         }
1743                         thread_list = NULL;
1744                         thread_list_len = 0;
1746                         /* Only deallocate the task port, if it isn't our own.
1747                          * Don't know what would happen in that case, but this
1748                          * is what Apple's top does.. ;) */
1749                         if (task_list[task] != port_task_self)
1750                         {
1751                                 status = mach_port_deallocate (port_task_self,
1752                                                 task_list[task]);
1753                                 if (status != KERN_SUCCESS)
1754                                         ERROR ("mach_port_deallocate failed: %s",
1755                                                         mach_error_string (status));
1756                         }
1758                         if (ps != NULL)
1759                                 /* FIXME: cmdline should be here instead of NULL */
1760                                 ps_list_add (task_name, NULL, &pse);
1761                 } /* for (task_list) */
1763                 if ((status = vm_deallocate (port_task_self,
1764                                 (vm_address_t) task_list,
1765                                 task_list_len * sizeof (task_t))) != KERN_SUCCESS)
1766                 {
1767                         ERROR ("vm_deallocate failed: %s",
1768                                         mach_error_string (status));
1769                 }
1770                 task_list = NULL;
1771                 task_list_len = 0;
1773                 if ((status = mach_port_deallocate (port_task_self, port_pset_priv))
1774                                 != KERN_SUCCESS)
1775                 {
1776                         ERROR ("mach_port_deallocate failed: %s",
1777                                         mach_error_string (status));
1778                 }
1779         } /* for (pset_list) */
1781         ps_submit_state ("running", running);
1782         ps_submit_state ("sleeping", sleeping);
1783         ps_submit_state ("zombies", zombies);
1784         ps_submit_state ("stopped", stopped);
1785         ps_submit_state ("blocked", blocked);
1787         for (ps = list_head_g; ps != NULL; ps = ps->next)
1788                 ps_submit_proc_list (ps);
1789 /* #endif HAVE_THREAD_INFO */
1791 #elif KERNEL_LINUX
1792         int running  = 0;
1793         int sleeping = 0;
1794         int zombies  = 0;
1795         int stopped  = 0;
1796         int paging   = 0;
1797         int blocked  = 0;
1799         struct dirent *ent;
1800         DIR           *proc;
1801         long           pid;
1803         char cmdline[CMDLINE_BUFFER_SIZE];
1805         int        status;
1806         procstat_t ps;
1807         procstat_entry_t pse;
1808         char       state;
1810         procstat_t *ps_ptr;
1812         running = sleeping = zombies = stopped = paging = blocked = 0;
1813         ps_list_reset ();
1815         if ((proc = opendir ("/proc")) == NULL)
1816         {
1817                 char errbuf[1024];
1818                 ERROR ("Cannot open `/proc': %s",
1819                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1820                 return (-1);
1821         }
1823         while ((ent = readdir (proc)) != NULL)
1824         {
1825                 if (!isdigit (ent->d_name[0]))
1826                         continue;
1828                 if ((pid = atol (ent->d_name)) < 1)
1829                         continue;
1831                 status = ps_read_process (pid, &ps, &state);
1832                 if (status != 0)
1833                 {
1834                         DEBUG ("ps_read_process failed: %i", status);
1835                         continue;
1836                 }
1838                 memset (&pse, 0, sizeof (pse));
1839                 pse.id       = pid;
1840                 pse.age      = 0;
1842                 pse.num_proc   = ps.num_proc;
1843                 pse.num_lwp    = ps.num_lwp;
1844                 pse.vmem_size  = ps.vmem_size;
1845                 pse.vmem_rss   = ps.vmem_rss;
1846                 pse.vmem_data  = ps.vmem_data;
1847                 pse.vmem_code  = ps.vmem_code;
1848                 pse.stack_size = ps.stack_size;
1850                 pse.vmem_minflt = 0;
1851                 pse.vmem_minflt_counter = ps.vmem_minflt_counter;
1852                 pse.vmem_majflt = 0;
1853                 pse.vmem_majflt_counter = ps.vmem_majflt_counter;
1855                 pse.cpu_user = 0;
1856                 pse.cpu_user_counter = ps.cpu_user_counter;
1857                 pse.cpu_system = 0;
1858                 pse.cpu_system_counter = ps.cpu_system_counter;
1860                 pse.io_rchar = ps.io_rchar;
1861                 pse.io_wchar = ps.io_wchar;
1862                 pse.io_syscr = ps.io_syscr;
1863                 pse.io_syscw = ps.io_syscw;
1865                 pse.cswitch_vol = ps.cswitch_vol;
1866                 pse.cswitch_invol = ps.cswitch_invol;
1868                 switch (state)
1869                 {
1870                         case 'R': running++;  break;
1871                         case 'S': sleeping++; break;
1872                         case 'D': blocked++;  break;
1873                         case 'Z': zombies++;  break;
1874                         case 'T': stopped++;  break;
1875                         case 'W': paging++;   break;
1876                 }
1878                 ps_list_add (ps.name,
1879                                 ps_get_cmdline (pid, ps.name, cmdline, sizeof (cmdline)),
1880                                 &pse);
1881         }
1883         closedir (proc);
1885         ps_submit_state ("running",  running);
1886         ps_submit_state ("sleeping", sleeping);
1887         ps_submit_state ("zombies",  zombies);
1888         ps_submit_state ("stopped",  stopped);
1889         ps_submit_state ("paging",   paging);
1890         ps_submit_state ("blocked",  blocked);
1892         for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
1893                 ps_submit_proc_list (ps_ptr);
1895         read_fork_rate();
1896 /* #endif KERNEL_LINUX */
1898 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
1899         int running  = 0;
1900         int sleeping = 0;
1901         int zombies  = 0;
1902         int stopped  = 0;
1903         int blocked  = 0;
1904         int idle     = 0;
1905         int wait     = 0;
1907         kvm_t *kd;
1908         char errbuf[_POSIX2_LINE_MAX];
1909         struct kinfo_proc *procs;          /* array of processes */
1910         struct kinfo_proc *proc_ptr = NULL;
1911         int count;                         /* returns number of processes */
1912         int i;
1914         procstat_t *ps_ptr;
1915         procstat_entry_t pse;
1917         ps_list_reset ();
1919         /* Open the kvm interface, get a descriptor */
1920         kd = kvm_openfiles (NULL, "/dev/null", NULL, 0, errbuf);
1921         if (kd == NULL)
1922         {
1923                 ERROR ("processes plugin: Cannot open kvm interface: %s",
1924                                 errbuf);
1925                 return (0);
1926         }
1928         /* Get the list of processes. */
1929         procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, &count);
1930         if (procs == NULL)
1931         {
1932                 ERROR ("processes plugin: Cannot get kvm processes list: %s",
1933                                 kvm_geterr(kd));
1934                 kvm_close (kd);
1935                 return (0);
1936         }
1938         /* Iterate through the processes in kinfo_proc */
1939         for (i = 0; i < count; i++)
1940         {
1941                 /* Create only one process list entry per _process_, i.e.
1942                  * filter out threads (duplicate PID entries). */
1943                 if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid))
1944                 {
1945                         char cmdline[CMDLINE_BUFFER_SIZE] = "";
1946                         _Bool have_cmdline = 0;
1948                         proc_ptr = &(procs[i]);
1949                         /* Don't probe system processes and processes without arguments */
1950                         if (((procs[i].ki_flag & P_SYSTEM) == 0)
1951                                         && (procs[i].ki_args != NULL))
1952                         {
1953                                 char **argv;
1954                                 int argc;
1955                                 int status;
1957                                 /* retrieve the arguments */
1958                                 argv = kvm_getargv (kd, proc_ptr, /* nchr = */ 0);
1959                                 argc = 0;
1960                                 if ((argv != NULL) && (argv[0] != NULL))
1961                                 {
1962                                         while (argv[argc] != NULL)
1963                                                 argc++;
1965                                         status = strjoin (cmdline, sizeof (cmdline), argv, argc, " ");
1966                                         if (status < 0)
1967                                                 WARNING ("processes plugin: Command line did not fit into buffer.");
1968                                         else
1969                                                 have_cmdline = 1;
1970                                 }
1971                         } /* if (process has argument list) */
1973                         pse.id       = procs[i].ki_pid;
1974                         pse.age      = 0;
1976                         pse.num_proc = 1;
1977                         pse.num_lwp  = procs[i].ki_numthreads;
1979                         pse.vmem_size = procs[i].ki_size;
1980                         pse.vmem_rss = procs[i].ki_rssize * pagesize;
1981                         pse.vmem_data = procs[i].ki_dsize * pagesize;
1982                         pse.vmem_code = procs[i].ki_tsize * pagesize;
1983                         pse.stack_size = procs[i].ki_ssize * pagesize;
1984                         pse.vmem_minflt = 0;
1985                         pse.vmem_minflt_counter = procs[i].ki_rusage.ru_minflt;
1986                         pse.vmem_majflt = 0;
1987                         pse.vmem_majflt_counter = procs[i].ki_rusage.ru_majflt;
1989                         pse.cpu_user = 0;
1990                         pse.cpu_system = 0;
1991                         pse.cpu_user_counter = 0;
1992                         pse.cpu_system_counter = 0;
1993                         /*
1994                          * The u-area might be swapped out, and we can't get
1995                          * at it because we have a crashdump and no swap.
1996                          * If it's here fill in these fields, otherwise, just
1997                          * leave them 0.
1998                          */
1999                         if (procs[i].ki_flag & P_INMEM)
2000                         {
2001                                 pse.cpu_user_counter = procs[i].ki_rusage.ru_utime.tv_usec
2002                                         + (1000000lu * procs[i].ki_rusage.ru_utime.tv_sec);
2003                                 pse.cpu_system_counter = procs[i].ki_rusage.ru_stime.tv_usec
2004                                         + (1000000lu * procs[i].ki_rusage.ru_stime.tv_sec);
2005                         }
2007                         /* no I/O data */
2008                         pse.io_rchar = -1;
2009                         pse.io_wchar = -1;
2010                         pse.io_syscr = -1;
2011                         pse.io_syscw = -1;
2013                         /* context switch counters not implemented */
2014                         pse.cswitch_vol   = -1;
2015                         pse.cswitch_invol = -1;
2017                         ps_list_add (procs[i].ki_comm, have_cmdline ? cmdline : NULL, &pse);
2019                         switch (procs[i].ki_stat)
2020                         {
2021                                 case SSTOP:     stopped++;      break;
2022                                 case SSLEEP:    sleeping++;     break;
2023                                 case SRUN:      running++;      break;
2024                                 case SIDL:      idle++;         break;
2025                                 case SWAIT:     wait++;         break;
2026                                 case SLOCK:     blocked++;      break;
2027                                 case SZOMB:     zombies++;      break;
2028                         }
2029                 } /* if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid)) */
2030         }
2032         kvm_close(kd);
2034         ps_submit_state ("running",  running);
2035         ps_submit_state ("sleeping", sleeping);
2036         ps_submit_state ("zombies",  zombies);
2037         ps_submit_state ("stopped",  stopped);
2038         ps_submit_state ("blocked",  blocked);
2039         ps_submit_state ("idle",     idle);
2040         ps_submit_state ("wait",     wait);
2042         for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2043                 ps_submit_proc_list (ps_ptr);
2044 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
2046 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_OPENBSD
2047         int running  = 0;
2048         int sleeping = 0;
2049         int zombies  = 0;
2050         int stopped  = 0;
2051         int onproc   = 0;
2052         int idle     = 0;
2053         int dead     = 0;
2055         kvm_t *kd;
2056         char errbuf[1024];
2057         struct kinfo_proc *procs;          /* array of processes */
2058         struct kinfo_proc *proc_ptr = NULL;
2059         int count;                         /* returns number of processes */
2060         int i;
2062         procstat_t *ps_ptr;
2063         procstat_entry_t pse;
2065         ps_list_reset ();
2067         /* Open the kvm interface, get a descriptor */
2068         kd = kvm_open (NULL, NULL, NULL, 0, errbuf);
2069         if (kd == NULL)
2070         {
2071                 ERROR ("processes plugin: Cannot open kvm interface: %s",
2072                                 errbuf);
2073                 return (0);
2074         }
2076         /* Get the list of processes. */
2077         procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc), &count);
2078         if (procs == NULL)
2079         {
2080                 ERROR ("processes plugin: Cannot get kvm processes list: %s",
2081                                 kvm_geterr(kd));
2082                 kvm_close (kd);
2083                 return (0);
2084         }
2086         /* Iterate through the processes in kinfo_proc */
2087         for (i = 0; i < count; i++)
2088         {
2089                 /* Create only one process list entry per _process_, i.e.
2090                  * filter out threads (duplicate PID entries). */
2091                 if ((proc_ptr == NULL) || (proc_ptr->p_pid != procs[i].p_pid))
2092                 {
2093                         char cmdline[CMDLINE_BUFFER_SIZE] = "";
2094                         _Bool have_cmdline = 0;
2096                         proc_ptr = &(procs[i]);
2097                         /* Don't probe zombie processes  */
2098                         if (!P_ZOMBIE(proc_ptr))
2099                         {
2100                                 char **argv;
2101                                 int argc;
2102                                 int status;
2104                                 /* retrieve the arguments */
2105                                 argv = kvm_getargv (kd, proc_ptr, /* nchr = */ 0);
2106                                 argc = 0;
2107                                 if ((argv != NULL) && (argv[0] != NULL))
2108                                 {
2109                                         while (argv[argc] != NULL)
2110                                                 argc++;
2112                                         status = strjoin (cmdline, sizeof (cmdline), argv, argc, " ");
2113                                         if (status < 0)
2114                                                 WARNING ("processes plugin: Command line did not fit into buffer.");
2115                                         else
2116                                                 have_cmdline = 1;
2117                                 }
2118                         } /* if (process has argument list) */
2120                         memset (&pse, 0, sizeof (pse));
2121                         pse.id       = procs[i].p_pid;
2122                         pse.age      = 0;
2124                         pse.num_proc = 1;
2125                         pse.num_lwp  = 1; /* XXX: accumulate p_tid values for a single p_pid ? */
2127                         pse.vmem_rss = procs[i].p_vm_rssize * pagesize;
2128                         pse.vmem_data = procs[i].p_vm_dsize * pagesize;
2129                         pse.vmem_code = procs[i].p_vm_tsize * pagesize;
2130                         pse.stack_size = procs[i].p_vm_ssize * pagesize;
2131                         pse.vmem_size = pse.stack_size + pse.vmem_code + pse.vmem_data;
2132                         pse.vmem_minflt = 0;
2133                         pse.vmem_minflt_counter = procs[i].p_uru_minflt;
2134                         pse.vmem_majflt = 0;
2135                         pse.vmem_majflt_counter = procs[i].p_uru_majflt;
2137                         pse.cpu_user = 0;
2138                         pse.cpu_system = 0;
2139                         pse.cpu_user_counter = procs[i].p_uutime_usec +
2140                                                 (1000000lu * procs[i].p_uutime_sec);
2141                         pse.cpu_system_counter = procs[i].p_ustime_usec +
2142                                                 (1000000lu * procs[i].p_ustime_sec);
2144                         /* no I/O data */
2145                         pse.io_rchar = -1;
2146                         pse.io_wchar = -1;
2147                         pse.io_syscr = -1;
2148                         pse.io_syscw = -1;
2150                         /* context switch counters not implemented */
2151                         pse.cswitch_vol   = -1;
2152                         pse.cswitch_invol = -1;
2154                         ps_list_add (procs[i].p_comm, have_cmdline ? cmdline : NULL, &pse);
2156                         switch (procs[i].p_stat)
2157                         {
2158                                 case SSTOP:     stopped++;      break;
2159                                 case SSLEEP:    sleeping++;     break;
2160                                 case SRUN:      running++;      break;
2161                                 case SIDL:      idle++;         break;
2162                                 case SONPROC:   onproc++;       break;
2163                                 case SDEAD:     dead++;         break;
2164                                 case SZOMB:     zombies++;      break;
2165                         }
2166                 } /* if ((proc_ptr == NULL) || (proc_ptr->p_pid != procs[i].p_pid)) */
2167         }
2169         kvm_close(kd);
2171         ps_submit_state ("running",  running);
2172         ps_submit_state ("sleeping", sleeping);
2173         ps_submit_state ("zombies",  zombies);
2174         ps_submit_state ("stopped",  stopped);
2175         ps_submit_state ("onproc",   onproc);
2176         ps_submit_state ("idle",     idle);
2177         ps_submit_state ("dead",     dead);
2179         for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2180                 ps_submit_proc_list (ps_ptr);
2181 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_OPENBSD */
2183 #elif HAVE_PROCINFO_H
2184         /* AIX */
2185         int running  = 0;
2186         int sleeping = 0;
2187         int zombies  = 0;
2188         int stopped  = 0;
2189         int paging   = 0;
2190         int blocked  = 0;
2192         pid_t pindex = 0;
2193         int nprocs;
2195         procstat_t *ps;
2196         procstat_entry_t pse;
2198         ps_list_reset ();
2199         while ((nprocs = getprocs64 (procentry, sizeof(struct procentry64),
2200                                         /* fdsinfo = */ NULL, sizeof(struct fdsinfo64),
2201                                         &pindex, MAXPROCENTRY)) > 0)
2202         {
2203                 int i;
2205                 for (i = 0; i < nprocs; i++)
2206                 {
2207                         tid64_t thindex;
2208                         int nthreads;
2209                         char arglist[MAXARGLN+1];
2210                         char *cargs;
2211                         char *cmdline;
2213                         if (procentry[i].pi_state == SNONE) continue;
2214                         /* if (procentry[i].pi_state == SZOMB)  FIXME */
2216                         cmdline = procentry[i].pi_comm;
2217                         cargs = procentry[i].pi_comm;
2218                         if ( procentry[i].pi_flags & SKPROC )
2219                         {
2220                                 if (procentry[i].pi_pid == 0)
2221                                         cmdline = "swapper";
2222                                 cargs = cmdline;
2223                         }
2224                         else
2225                         {
2226                                 if (getargs(&procentry[i], sizeof(struct procentry64), arglist, MAXARGLN) >= 0)
2227                                 {
2228                                         int n;
2230                                         n = -1;
2231                                         while (++n < MAXARGLN)
2232                                         {
2233                                                 if (arglist[n] == '\0')
2234                                                 {
2235                                                         if (arglist[n+1] == '\0')
2236                                                                 break;
2237                                                         arglist[n] = ' ';
2238                                                 }
2239                                         }
2240                                         cargs = arglist;
2241                                 }
2242                         }
2244                         pse.id       = procentry[i].pi_pid;
2245                         pse.age      = 0;
2246                         pse.num_lwp  = procentry[i].pi_thcount;
2247                         pse.num_proc = 1;
2249                         thindex=0;
2250                         while ((nthreads = getthrds64(procentry[i].pi_pid,
2251                                                         thrdentry, sizeof(struct thrdentry64),
2252                                                         &thindex, MAXTHRDENTRY)) > 0)
2253                         {
2254                                 int j;
2256                                 for (j=0; j< nthreads; j++)
2257                                 {
2258                                         switch (thrdentry[j].ti_state)
2259                                         {
2260                                                 /* case TSNONE: break; */
2261                                                 case TSIDL:     blocked++;      break; /* FIXME is really blocked */
2262                                                 case TSRUN:     running++;      break;
2263                                                 case TSSLEEP:   sleeping++;     break;
2264                                                 case TSSWAP:    paging++;       break;
2265                                                 case TSSTOP:    stopped++;      break;
2266                                                 case TSZOMB:    zombies++;      break;
2267                                         }
2268                                 }
2269                                 if (nthreads < MAXTHRDENTRY)
2270                                         break;
2271                         }
2273                         pse.cpu_user = 0;
2274                         /* tv_usec is nanosec ??? */
2275                         pse.cpu_user_counter = procentry[i].pi_ru.ru_utime.tv_sec * 1000000 +
2276                                 procentry[i].pi_ru.ru_utime.tv_usec / 1000;
2278                         pse.cpu_system = 0;
2279                         /* tv_usec is nanosec ??? */
2280                         pse.cpu_system_counter = procentry[i].pi_ru.ru_stime.tv_sec * 1000000 +
2281                                 procentry[i].pi_ru.ru_stime.tv_usec / 1000;
2283                         pse.vmem_minflt = 0;
2284                         pse.vmem_minflt_counter = procentry[i].pi_minflt;
2285                         pse.vmem_majflt = 0;
2286                         pse.vmem_majflt_counter = procentry[i].pi_majflt;
2288                         pse.vmem_size = procentry[i].pi_tsize + procentry[i].pi_dvm * pagesize;
2289                         pse.vmem_rss = (procentry[i].pi_drss + procentry[i].pi_trss) * pagesize;
2290                         /* Not supported */
2291                         pse.vmem_data = 0;
2292                         pse.vmem_code = 0;
2293                         pse.stack_size =  0;
2295                         pse.io_rchar = -1;
2296                         pse.io_wchar = -1;
2297                         pse.io_syscr = -1;
2298                         pse.io_syscw = -1;
2300                         pse.cswitch_vol   = -1;
2301                         pse.cswitch_invol = -1;
2303                         ps_list_add (cmdline, cargs, &pse);
2304                 } /* for (i = 0 .. nprocs) */
2306                 if (nprocs < MAXPROCENTRY)
2307                         break;
2308         } /* while (getprocs64() > 0) */
2309         ps_submit_state ("running",  running);
2310         ps_submit_state ("sleeping", sleeping);
2311         ps_submit_state ("zombies",  zombies);
2312         ps_submit_state ("stopped",  stopped);
2313         ps_submit_state ("paging",   paging);
2314         ps_submit_state ("blocked",  blocked);
2316         for (ps = list_head_g; ps != NULL; ps = ps->next)
2317                 ps_submit_proc_list (ps);
2318 /* #endif HAVE_PROCINFO_H */
2320 #elif KERNEL_SOLARIS
2321         /*
2322          * The Solaris section adds a few more process states and removes some
2323          * process states compared to linux. Most notably there is no "PAGING"
2324          * and "BLOCKED" state for a process.  The rest is similar to the linux
2325          * code.
2326          */
2327         int running = 0;
2328         int sleeping = 0;
2329         int zombies = 0;
2330         int stopped = 0;
2331         int detached = 0;
2332         int daemon = 0;
2333         int system = 0;
2334         int orphan = 0;
2336         struct dirent *ent;
2337         DIR *proc;
2339         int status;
2340         procstat_t *ps_ptr;
2341         char state;
2343         char cmdline[PRARGSZ];
2345         ps_list_reset ();
2347         proc = opendir ("/proc");
2348         if (proc == NULL)
2349                 return (-1);
2351         while ((ent = readdir(proc)) != NULL)
2352         {
2353                 long pid;
2354                 struct procstat ps;
2355                 procstat_entry_t pse;
2356                 char *endptr;
2358                 if (!isdigit ((int) ent->d_name[0]))
2359                         continue;
2361                 pid = strtol (ent->d_name, &endptr, 10);
2362                 if (*endptr != 0) /* value didn't completely parse as a number */
2363                         continue;
2365                 status = ps_read_process (pid, &ps, &state);
2366                 if (status != 0)
2367                 {
2368                         DEBUG("ps_read_process failed: %i", status);
2369                         continue;
2370                 }
2372                 memset (&pse, 0, sizeof (pse));
2373                 pse.id = pid;
2374                 pse.age = 0;
2376                 pse.num_proc   = ps.num_proc;
2377                 pse.num_lwp    = ps.num_lwp;
2378                 pse.vmem_size  = ps.vmem_size;
2379                 pse.vmem_rss   = ps.vmem_rss;
2380                 pse.vmem_data  = ps.vmem_data;
2381                 pse.vmem_code  = ps.vmem_code;
2382                 pse.stack_size = ps.stack_size;
2384                 pse.vmem_minflt = 0;
2385                 pse.vmem_minflt_counter = ps.vmem_minflt_counter;
2386                 pse.vmem_majflt = 0;
2387                 pse.vmem_majflt_counter = ps.vmem_majflt_counter;
2389                 pse.cpu_user = 0;
2390                 pse.cpu_user_counter = ps.cpu_user_counter;
2391                 pse.cpu_system = 0;
2392                 pse.cpu_system_counter = ps.cpu_system_counter;
2394                 pse.io_rchar = ps.io_rchar;
2395                 pse.io_wchar = ps.io_wchar;
2396                 pse.io_syscr = ps.io_syscr;
2397                 pse.io_syscw = ps.io_syscw;
2399                 pse.cswitch_vol = -1;
2400                 pse.cswitch_invol = -1;
2402                 switch (state)
2403                 {
2404                         case 'R': running++;  break;
2405                         case 'S': sleeping++; break;
2406                         case 'E': detached++; break;
2407                         case 'Z': zombies++;  break;
2408                         case 'T': stopped++;  break;
2409                         case 'A': daemon++;   break;
2410                         case 'Y': system++;   break;
2411                         case 'O': orphan++;   break;
2412                 }
2415                 ps_list_add (ps.name,
2416                                 ps_get_cmdline (pid, ps.name, cmdline, sizeof (cmdline)),
2417                                 &pse);
2418         } /* while(readdir) */
2419         closedir (proc);
2421         ps_submit_state ("running",  running);
2422         ps_submit_state ("sleeping", sleeping);
2423         ps_submit_state ("zombies",  zombies);
2424         ps_submit_state ("stopped",  stopped);
2425         ps_submit_state ("detached", detached);
2426         ps_submit_state ("daemon",   daemon);
2427         ps_submit_state ("system",   system);
2428         ps_submit_state ("orphan",   orphan);
2430         for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2431                 ps_submit_proc_list (ps_ptr);
2433         read_fork_rate();
2434 #endif /* KERNEL_SOLARIS */
2436         return (0);
2437 } /* int ps_read */
2439 void module_register (void)
2441         plugin_register_complex_config ("processes", ps_config);
2442         plugin_register_init ("processes", ps_init);
2443         plugin_register_read ("processes", ps_read);
2444 } /* void module_register */