Merge branch 'collectd-4.8'
[collectd.git] / src / processes.c
1 /**
2  * collectd - src/processes.c
3  * Copyright (C) 2005       Lyonel Vincent
4  * Copyright (C) 2006-2008  Florian octo Forster
5  * Copyright (C) 2008       Oleg King
6  * Copyright (C) 2009       Sebastian Harl
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of the GNU General Public License as published by the
10  * Free Software Foundation; either version 2 of the License, or (at your
11  * option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
21  *
22  * Authors:
23  *   Lyonel Vincent <lyonel at ezix.org>
24  *   Florian octo Forster <octo at verplant.org>
25  *   Oleg King <king2 at kaluga.ru>
26  *   Sebastian Harl <sh at tokkee.org>
27  **/
28
29 #include "collectd.h"
30 #include "common.h"
31 #include "plugin.h"
32 #include "configfile.h"
33
34 /* Include header files for the mach system, if they exist.. */
35 #if HAVE_THREAD_INFO
36 #  if HAVE_MACH_MACH_INIT_H
37 #    include <mach/mach_init.h>
38 #  endif
39 #  if HAVE_MACH_HOST_PRIV_H
40 #    include <mach/host_priv.h>
41 #  endif
42 #  if HAVE_MACH_MACH_ERROR_H
43 #    include <mach/mach_error.h>
44 #  endif
45 #  if HAVE_MACH_MACH_HOST_H
46 #    include <mach/mach_host.h>
47 #  endif
48 #  if HAVE_MACH_MACH_PORT_H
49 #    include <mach/mach_port.h>
50 #  endif
51 #  if HAVE_MACH_MACH_TYPES_H
52 #    include <mach/mach_types.h>
53 #  endif
54 #  if HAVE_MACH_MESSAGE_H
55 #    include <mach/message.h>
56 #  endif
57 #  if HAVE_MACH_PROCESSOR_SET_H
58 #    include <mach/processor_set.h>
59 #  endif
60 #  if HAVE_MACH_TASK_H
61 #    include <mach/task.h>
62 #  endif
63 #  if HAVE_MACH_THREAD_ACT_H
64 #    include <mach/thread_act.h>
65 #  endif
66 #  if HAVE_MACH_VM_REGION_H
67 #    include <mach/vm_region.h>
68 #  endif
69 #  if HAVE_MACH_VM_MAP_H
70 #    include <mach/vm_map.h>
71 #  endif
72 #  if HAVE_MACH_VM_PROT_H
73 #    include <mach/vm_prot.h>
74 #  endif
75 #  if HAVE_SYS_SYSCTL_H
76 #    include <sys/sysctl.h>
77 #  endif
78 /* #endif HAVE_THREAD_INFO */
79
80 #elif KERNEL_LINUX
81 #  if HAVE_LINUX_CONFIG_H
82 #    include <linux/config.h>
83 #  endif
84 #  ifndef CONFIG_HZ
85 #    define CONFIG_HZ 100
86 #  endif
87 /* #endif KERNEL_LINUX */
88
89 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
90 #  include <kvm.h>
91 #  include <sys/param.h>
92 #  include <sys/sysctl.h>
93 #  include <sys/user.h>
94 #  include <sys/proc.h>
95 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
96
97 #else
98 # error "No applicable input method."
99 #endif
100
101 #if HAVE_REGEX_H
102 # include <regex.h>
103 #endif
104
105 #ifndef ARG_MAX
106 #  define ARG_MAX 4096
107 #endif
108
109 #define BUFSIZE 256
110
111 static const char *config_keys[] =
112 {
113         "Process",
114         "ProcessMatch"
115 };
116 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
117
118 typedef struct procstat_entry_s
119 {
120         unsigned long id;
121         unsigned long age;
122
123         unsigned long num_proc;
124         unsigned long num_lwp;
125         unsigned long vmem_size;
126         unsigned long vmem_rss;
127         unsigned long stack_size;
128
129         unsigned long vmem_minflt;
130         unsigned long vmem_majflt;
131         unsigned long vmem_minflt_counter;
132         unsigned long vmem_majflt_counter;
133
134         unsigned long cpu_user;
135         unsigned long cpu_system;
136         unsigned long cpu_user_counter;
137         unsigned long cpu_system_counter;
138
139         /* io data */
140         long io_rchar;
141         long io_wchar;
142         long io_syscr;
143         long io_syscw;
144
145         struct procstat_entry_s *next;
146 } procstat_entry_t;
147
148 #define PROCSTAT_NAME_LEN 256
149 typedef struct procstat
150 {
151         char          name[PROCSTAT_NAME_LEN];
152 #if HAVE_REGEX_H
153         regex_t *re;
154 #endif
155
156         unsigned long num_proc;
157         unsigned long num_lwp;
158         unsigned long vmem_size;
159         unsigned long vmem_rss;
160         unsigned long stack_size;
161
162         unsigned long vmem_minflt_counter;
163         unsigned long vmem_majflt_counter;
164
165         unsigned long cpu_user_counter;
166         unsigned long cpu_system_counter;
167
168         /* io data */
169         long io_rchar;
170         long io_wchar;
171         long io_syscr;
172         long io_syscw;
173
174         struct procstat   *next;
175         struct procstat_entry_s *instances;
176 } procstat_t;
177
178 static procstat_t *list_head_g = NULL;
179
180 #if HAVE_THREAD_INFO
181 static mach_port_t port_host_self;
182 static mach_port_t port_task_self;
183
184 static processor_set_name_array_t pset_list;
185 static mach_msg_type_number_t     pset_list_len;
186 /* #endif HAVE_THREAD_INFO */
187
188 #elif KERNEL_LINUX
189 static long pagesize_g;
190 /* #endif KERNEL_LINUX */
191
192 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
193 /* no global variables */
194 #endif /* HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
195
196 /* put name of process from config to list_head_g tree
197    list_head_g is a list of 'procstat_t' structs with
198    processes names we want to watch */
199 static void ps_list_register (const char *name, const char *regexp)
200 {
201         procstat_t *new;
202         procstat_t *ptr;
203         int status;
204
205         new = (procstat_t *) malloc (sizeof (procstat_t));
206         if (new == NULL)
207         {
208                 ERROR ("processes plugin: ps_list_register: malloc failed.");
209                 return;
210         }
211         memset (new, 0, sizeof (procstat_t));
212         sstrncpy (new->name, name, sizeof (new->name));
213
214 #if HAVE_REGEX_H
215         if (regexp != NULL)
216         {
217                 DEBUG ("ProcessMatch: adding \"%s\" as criteria to process %s.", regexp, name);
218                 new->re = (regex_t *) malloc (sizeof (regex_t));
219                 if (new->re == NULL)
220                 {
221                         ERROR ("processes plugin: ps_list_register: malloc failed.");
222                         sfree (new);
223                         return;
224                 }
225
226                 status = regcomp (new->re, regexp, REG_EXTENDED | REG_NOSUB);
227                 if (status != 0)
228                 {
229                         DEBUG ("ProcessMatch: compiling the regular expression \"%s\" failed.", regexp);
230                         sfree(new->re);
231                         return;
232                 }
233         }
234 #else
235         if (regexp != NULL)
236         {
237                 ERROR ("processes plugin: ps_list_register: "
238                                 "Regular expression \"%s\" found in config "
239                                 "file, but support for regular expressions "
240                                 "has been dispabled at compile time.",
241                                 regexp);
242                 sfree (new);
243                 return;
244         }
245 #endif
246         
247         for (ptr = list_head_g; ptr != NULL; ptr = ptr->next)
248         {
249                 if (strcmp (ptr->name, name) == 0)
250                 {
251                         WARNING ("processes plugin: You have configured more "
252                                         "than one `Process' or "
253                                         "`ProcessMatch' with the same name. "
254                                         "All but the first setting will be "
255                                         "ignored.");
256                         sfree (new->re);
257                         sfree (new);
258                         return;
259                 }
260
261                 if (ptr->next == NULL)
262                         break;
263         }
264
265         if (ptr == NULL)
266                 list_head_g = new;
267         else
268                 ptr->next = new;
269 } /* void ps_list_register */
270
271 /* try to match name against entry, returns 1 if success */
272 static int ps_list_match (const char *name, const char *cmdline, procstat_t *ps)
273 {
274 #if HAVE_REGEX_H
275         if (ps->re != NULL)
276         {
277                 int status;
278                 const char *str;
279
280                 str = cmdline;
281                 if ((str == NULL) || (str[0] == 0))
282                         str = name;
283
284                 assert (str != NULL);
285
286                 status = regexec (ps->re, str,
287                                 /* nmatch = */ 0,
288                                 /* pmatch = */ NULL,
289                                 /* eflags = */ 0);
290                 if (status == 0)
291                         return (1);
292         }
293         else
294 #endif
295         if (strcmp (ps->name, name) == 0)
296                 return (1);
297
298         return (0);
299 } /* int ps_list_match */
300
301 /* add process entry to 'instances' of process 'name' (or refresh it) */
302 static void ps_list_add (const char *name, const char *cmdline, procstat_entry_t *entry)
303 {
304         procstat_t *ps;
305         procstat_entry_t *pse;
306
307         if (entry->id == 0)
308                 return;
309
310         for (ps = list_head_g; ps != NULL; ps = ps->next)
311         {
312                 if ((ps_list_match (name, cmdline, ps)) == 0)
313                         continue;
314
315                 for (pse = ps->instances; pse != NULL; pse = pse->next)
316                         if ((pse->id == entry->id) || (pse->next == NULL))
317                                 break;
318
319                 if ((pse == NULL) || (pse->id != entry->id))
320                 {
321                         procstat_entry_t *new;
322                         
323                         new = (procstat_entry_t *) malloc (sizeof (procstat_entry_t));
324                         if (new == NULL)
325                                 return;
326                         memset (new, 0, sizeof (procstat_entry_t));
327                         new->id = entry->id;
328                         
329                         if (pse == NULL)
330                                 ps->instances = new;
331                         else
332                                 pse->next = new;
333
334                         pse = new;
335                 }
336
337                 pse->age = 0;
338                 pse->num_proc   = entry->num_proc;
339                 pse->num_lwp    = entry->num_lwp;
340                 pse->vmem_size  = entry->vmem_size;
341                 pse->vmem_rss   = entry->vmem_rss;
342                 pse->stack_size = entry->stack_size;
343                 pse->io_rchar   = entry->io_rchar;
344                 pse->io_wchar   = entry->io_wchar;
345                 pse->io_syscr   = entry->io_syscr;
346                 pse->io_syscw   = entry->io_syscw;
347
348                 ps->num_proc   += pse->num_proc;
349                 ps->num_lwp    += pse->num_lwp;
350                 ps->vmem_size  += pse->vmem_size;
351                 ps->vmem_rss   += pse->vmem_rss;
352                 ps->stack_size += pse->stack_size;
353
354                 ps->io_rchar   += ((pse->io_rchar == -1)?0:pse->io_rchar);
355                 ps->io_wchar   += ((pse->io_wchar == -1)?0:pse->io_wchar);
356                 ps->io_syscr   += ((pse->io_syscr == -1)?0:pse->io_syscr);
357                 ps->io_syscw   += ((pse->io_syscw == -1)?0:pse->io_syscw);
358
359                 if ((entry->vmem_minflt_counter == 0)
360                                 && (entry->vmem_majflt_counter == 0))
361                 {
362                         pse->vmem_minflt_counter += entry->vmem_minflt;
363                         pse->vmem_minflt = entry->vmem_minflt;
364
365                         pse->vmem_majflt_counter += entry->vmem_majflt;
366                         pse->vmem_majflt = entry->vmem_majflt;
367                 }
368                 else
369                 {
370                         if (entry->vmem_minflt_counter < pse->vmem_minflt_counter)
371                         {
372                                 pse->vmem_minflt = entry->vmem_minflt_counter
373                                         + (ULONG_MAX - pse->vmem_minflt_counter);
374                         }
375                         else
376                         {
377                                 pse->vmem_minflt = entry->vmem_minflt_counter - pse->vmem_minflt_counter;
378                         }
379                         pse->vmem_minflt_counter = entry->vmem_minflt_counter;
380                         
381                         if (entry->vmem_majflt_counter < pse->vmem_majflt_counter)
382                         {
383                                 pse->vmem_majflt = entry->vmem_majflt_counter
384                                         + (ULONG_MAX - pse->vmem_majflt_counter);
385                         }
386                         else
387                         {
388                                 pse->vmem_majflt = entry->vmem_majflt_counter - pse->vmem_majflt_counter;
389                         }
390                         pse->vmem_majflt_counter = entry->vmem_majflt_counter;
391                 }
392
393                 ps->vmem_minflt_counter += pse->vmem_minflt;
394                 ps->vmem_majflt_counter += pse->vmem_majflt;
395
396                 if ((entry->cpu_user_counter == 0)
397                                 && (entry->cpu_system_counter == 0))
398                 {
399                         pse->cpu_user_counter += entry->cpu_user;
400                         pse->cpu_user = entry->cpu_user;
401
402                         pse->cpu_system_counter += entry->cpu_system;
403                         pse->cpu_system = entry->cpu_system;
404                 }
405                 else
406                 {
407                         if (entry->cpu_user_counter < pse->cpu_user_counter)
408                         {
409                                 pse->cpu_user = entry->cpu_user_counter
410                                         + (ULONG_MAX - pse->cpu_user_counter);
411                         }
412                         else
413                         {
414                                 pse->cpu_user = entry->cpu_user_counter - pse->cpu_user_counter;
415                         }
416                         pse->cpu_user_counter = entry->cpu_user_counter;
417                         
418                         if (entry->cpu_system_counter < pse->cpu_system_counter)
419                         {
420                                 pse->cpu_system = entry->cpu_system_counter
421                                         + (ULONG_MAX - pse->cpu_system_counter);
422                         }
423                         else
424                         {
425                                 pse->cpu_system = entry->cpu_system_counter - pse->cpu_system_counter;
426                         }
427                         pse->cpu_system_counter = entry->cpu_system_counter;
428                 }
429
430                 ps->cpu_user_counter   += pse->cpu_user;
431                 ps->cpu_system_counter += pse->cpu_system;
432         }
433 }
434
435 /* remove old entries from instances of processes in list_head_g */
436 static void ps_list_reset (void)
437 {
438         procstat_t *ps;
439         procstat_entry_t *pse;
440         procstat_entry_t *pse_prev;
441
442         for (ps = list_head_g; ps != NULL; ps = ps->next)
443         {
444                 ps->num_proc    = 0;
445                 ps->num_lwp     = 0;
446                 ps->vmem_size   = 0;
447                 ps->vmem_rss    = 0;
448                 ps->stack_size  = 0;
449                 ps->io_rchar = -1;
450                 ps->io_wchar = -1;
451                 ps->io_syscr = -1;
452                 ps->io_syscw = -1;
453
454                 pse_prev = NULL;
455                 pse = ps->instances;
456                 while (pse != NULL)
457                 {
458                         if (pse->age > 10)
459                         {
460                                 DEBUG ("Removing this procstat entry cause it's too old: "
461                                                 "id = %lu; name = %s;",
462                                                 pse->id, ps->name);
463
464                                 if (pse_prev == NULL)
465                                 {
466                                         ps->instances = pse->next;
467                                         free (pse);
468                                         pse = ps->instances;
469                                 }
470                                 else
471                                 {
472                                         pse_prev->next = pse->next;
473                                         free (pse);
474                                         pse = pse_prev->next;
475                                 }
476                         }
477                         else
478                         {
479                                 pse->age++;
480                                 pse_prev = pse;
481                                 pse = pse->next;
482                         }
483                 } /* while (pse != NULL) */
484         } /* for (ps = list_head_g; ps != NULL; ps = ps->next) */
485 }
486
487 /* put all pre-defined 'Process' names from config to list_head_g tree */
488 static int ps_config (const char *key, const char *value)
489 {
490         if (strcasecmp (key, "Process") == 0)
491         {
492                 ps_list_register (value, NULL);
493         }
494         else if (strcasecmp (key, "ProcessMatch") == 0)
495         {
496                 char *new_val;
497                 char *fields[3];
498                 int fields_num;
499
500                 new_val = strdup (value);
501                 if (new_val == NULL) {
502                         ERROR ("processes plugin: strdup failed when processing "
503                                         "`ProcessMatch %s'.", value);
504                         return (1);
505                 }
506
507                 fields_num = strsplit (new_val, fields,
508                                 STATIC_ARRAY_SIZE (fields));
509                 if (fields_num != 2)
510                 {
511                         ERROR ("processes plugin: `ProcessMatch' needs exactly "
512                                         "two string arguments.");
513                         sfree (new_val);
514                         return (1);
515                 }
516                 ps_list_register (fields[0], fields[1]);
517                 sfree (new_val);
518         }
519         else
520         {
521                 ERROR ("processes plugin: The `%s' configuration option is not "
522                                 "understood and will be ignored.", key);
523                 return (-1);
524         }
525
526         return (0);
527 }
528
529 static int ps_init (void)
530 {
531 #if HAVE_THREAD_INFO
532         kern_return_t status;
533
534         port_host_self = mach_host_self ();
535         port_task_self = mach_task_self ();
536
537         if (pset_list != NULL)
538         {
539                 vm_deallocate (port_task_self,
540                                 (vm_address_t) pset_list,
541                                 pset_list_len * sizeof (processor_set_t));
542                 pset_list = NULL;
543                 pset_list_len = 0;
544         }
545
546         if ((status = host_processor_sets (port_host_self,
547                                         &pset_list,
548                                         &pset_list_len)) != KERN_SUCCESS)
549         {
550                 ERROR ("host_processor_sets failed: %s\n",
551                                 mach_error_string (status));
552                 pset_list = NULL;
553                 pset_list_len = 0;
554                 return (-1);
555         }
556 /* #endif HAVE_THREAD_INFO */
557
558 #elif KERNEL_LINUX
559         pagesize_g = sysconf(_SC_PAGESIZE);
560         DEBUG ("pagesize_g = %li; CONFIG_HZ = %i;",
561                         pagesize_g, CONFIG_HZ);
562 /* #endif KERNEL_LINUX */
563
564 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
565 /* no initialization */
566 #endif /* HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
567
568         return (0);
569 } /* int ps_init */
570
571 /* submit global state (e.g.: qty of zombies, running, etc..) */
572 static void ps_submit_state (const char *state, double value)
573 {
574         value_t values[1];
575         value_list_t vl = VALUE_LIST_INIT;
576
577         values[0].gauge = value;
578
579         vl.values = values;
580         vl.values_len = 1;
581         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
582         sstrncpy (vl.plugin, "processes", sizeof (vl.plugin));
583         sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
584         sstrncpy (vl.type, "ps_state", sizeof (vl.type));
585         sstrncpy (vl.type_instance, state, sizeof (vl.type_instance));
586
587         plugin_dispatch_values (&vl);
588 }
589
590 /* submit info about specific process (e.g.: memory taken, cpu usage, etc..) */
591 static void ps_submit_proc_list (procstat_t *ps)
592 {
593         value_t values[2];
594         value_list_t vl = VALUE_LIST_INIT;
595
596         vl.values = values;
597         vl.values_len = 2;
598         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
599         sstrncpy (vl.plugin, "processes", sizeof (vl.plugin));
600         sstrncpy (vl.plugin_instance, ps->name, sizeof (vl.plugin_instance));
601
602         sstrncpy (vl.type, "ps_vm", sizeof (vl.type));
603         vl.values[0].gauge = ps->vmem_size;
604         vl.values_len = 1;
605         plugin_dispatch_values (&vl);
606
607         sstrncpy (vl.type, "ps_rss", sizeof (vl.type));
608         vl.values[0].gauge = ps->vmem_rss;
609         vl.values_len = 1;
610         plugin_dispatch_values (&vl);
611
612         sstrncpy (vl.type, "ps_stacksize", sizeof (vl.type));
613         vl.values[0].gauge = ps->stack_size;
614         vl.values_len = 1;
615         plugin_dispatch_values (&vl);
616
617         sstrncpy (vl.type, "ps_cputime", sizeof (vl.type));
618         vl.values[0].counter = ps->cpu_user_counter;
619         vl.values[1].counter = ps->cpu_system_counter;
620         vl.values_len = 2;
621         plugin_dispatch_values (&vl);
622
623         sstrncpy (vl.type, "ps_count", sizeof (vl.type));
624         vl.values[0].gauge = ps->num_proc;
625         vl.values[1].gauge = ps->num_lwp;
626         vl.values_len = 2;
627         plugin_dispatch_values (&vl);
628
629         sstrncpy (vl.type, "ps_pagefaults", sizeof (vl.type));
630         vl.values[0].counter = ps->vmem_minflt_counter;
631         vl.values[1].counter = ps->vmem_majflt_counter;
632         vl.values_len = 2;
633         plugin_dispatch_values (&vl);
634
635         if ( (ps->io_rchar != -1) && (ps->io_wchar != -1) )
636         {
637                 sstrncpy (vl.type, "ps_disk_octets", sizeof (vl.type));
638                 vl.values[0].counter = ps->io_rchar;
639                 vl.values[1].counter = ps->io_wchar;
640                 vl.values_len = 2;
641                 plugin_dispatch_values (&vl);
642         }
643
644         if ( (ps->io_syscr != -1) && (ps->io_syscw != -1) )
645         {
646                 sstrncpy (vl.type, "ps_disk_ops", sizeof (vl.type));
647                 vl.values[0].counter = ps->io_syscr;
648                 vl.values[1].counter = ps->io_syscw;
649                 vl.values_len = 2;
650                 plugin_dispatch_values (&vl);
651         }
652
653         DEBUG ("name = %s; num_proc = %lu; num_lwp = %lu; vmem_rss = %lu; "
654                         "vmem_minflt_counter = %lu; vmem_majflt_counter = %lu; "
655                         "cpu_user_counter = %lu; cpu_system_counter = %lu; "
656                         "io_rchar = %ld; io_wchar = %ld; "
657                         "io_syscr = %ld; io_syscw = %ld;",
658                         ps->name, ps->num_proc, ps->num_lwp, ps->vmem_rss,
659                         ps->vmem_minflt_counter, ps->vmem_majflt_counter,
660                         ps->cpu_user_counter, ps->cpu_system_counter,
661                         ps->io_rchar, ps->io_wchar, ps->io_syscr, ps->io_syscw);
662 } /* void ps_submit_proc_list */
663
664 /* ------- additional functions for KERNEL_LINUX/HAVE_THREAD_INFO ------- */
665 #if KERNEL_LINUX
666 static int ps_read_tasks (int pid)
667 {
668         char           dirname[64];
669         DIR           *dh;
670         struct dirent *ent;
671         int count = 0;
672
673         ssnprintf (dirname, sizeof (dirname), "/proc/%i/task", pid);
674
675         if ((dh = opendir (dirname)) == NULL)
676         {
677                 DEBUG ("Failed to open directory `%s'", dirname);
678                 return (-1);
679         }
680
681         while ((ent = readdir (dh)) != NULL)
682         {
683                 if (!isdigit ((int) ent->d_name[0]))
684                         continue;
685                 else
686                         count++;
687         }
688         closedir (dh);
689
690         return ((count >= 1) ? count : 1);
691 } /* int *ps_read_tasks */
692
693 static procstat_t *ps_read_io (int pid, procstat_t *ps)
694 {
695         FILE *fh;
696         char buffer[1024];
697         char filename[64];
698
699         char *fields[8];
700         int numfields;
701
702         ssnprintf (filename, sizeof (filename), "/proc/%i/io", pid);
703         if ((fh = fopen (filename, "r")) == NULL)
704                 return (NULL);
705
706         while (fgets (buffer, 1024, fh) != NULL)
707         {
708                 long *val = NULL;
709
710                 if (strncasecmp (buffer, "rchar:", 6) == 0)
711                         val = &(ps->io_rchar);
712                 else if (strncasecmp (buffer, "wchar:", 6) == 0)
713                         val = &(ps->io_wchar);
714                 else if (strncasecmp (buffer, "syscr:", 6) == 0)
715                         val = &(ps->io_syscr);
716                 else if (strncasecmp (buffer, "syscw:", 6) == 0)
717                         val = &(ps->io_syscw);
718                 else
719                         continue;
720
721                 numfields = strsplit (buffer, fields, 8);
722
723                 if (numfields < 2)
724                         continue;
725
726                 *val = atol (fields[1]);
727         }
728
729         if (fclose (fh))
730         {
731                 char errbuf[1024];
732                 WARNING ("processes: fclose: %s",
733                                 sstrerror (errno, errbuf, sizeof (errbuf)));
734         }
735
736         return (ps);
737 } /* procstat_t *ps_read_io */
738
739 int ps_read_process (int pid, procstat_t *ps, char *state)
740 {
741         char  filename[64];
742         char  buffer[1024];
743
744         char *fields[64];
745         char  fields_len;
746
747         int   i;
748
749         int   ppid;
750         int   name_len;
751
752         long long unsigned cpu_user_counter;
753         long long unsigned cpu_system_counter;
754         long long unsigned vmem_size;
755         long long unsigned vmem_rss;
756         long long unsigned stack_size;
757
758         memset (ps, 0, sizeof (procstat_t));
759
760         ssnprintf (filename, sizeof (filename), "/proc/%i/stat", pid);
761
762         i = read_file_contents (filename, buffer, sizeof(buffer) - 1);
763         if (i <= 0)
764                 return (-1);
765         buffer[i] = 0;
766
767         fields_len = strsplit (buffer, fields, 64);
768         if (fields_len < 24)
769         {
770                 DEBUG ("processes plugin: ps_read_process (pid = %i):"
771                                 " `%s' has only %i fields..",
772                                 (int) pid, filename, fields_len);
773                 return (-1);
774         }
775
776         /* copy the name, strip brackets in the process */
777         name_len = strlen (fields[1]) - 2;
778         if ((fields[1][0] != '(') || (fields[1][name_len + 1] != ')'))
779         {
780                 DEBUG ("No brackets found in process name: `%s'", fields[1]);
781                 return (-1);
782         }
783         fields[1] = fields[1] + 1;
784         fields[1][name_len] = '\0';
785         strncpy (ps->name, fields[1], PROCSTAT_NAME_LEN);
786
787         ppid = atoi (fields[3]);
788
789         *state = fields[2][0];
790
791         if (*state == 'Z')
792         {
793                 ps->num_lwp  = 0;
794                 ps->num_proc = 0;
795         }
796         else
797         {
798                 if ( (ps->num_lwp = ps_read_tasks (pid)) == -1 )
799                 {
800                         /* returns -1 => kernel 2.4 */
801                         ps->num_lwp = 1;
802                 }
803                 ps->num_proc = 1;
804         }
805
806         /* Leave the rest at zero if this is only a zombi */
807         if (ps->num_proc == 0)
808         {
809                 DEBUG ("processes plugin: This is only a zombi: pid = %i; "
810                                 "name = %s;", pid, ps->name);
811                 return (0);
812         }
813
814         cpu_user_counter   = atoll (fields[13]);
815         cpu_system_counter = atoll (fields[14]);
816         vmem_size          = atoll (fields[22]);
817         vmem_rss           = atoll (fields[23]);
818         ps->vmem_minflt_counter = atol (fields[9]);
819         ps->vmem_majflt_counter = atol (fields[11]);
820
821         {
822                 unsigned long long stack_start = atoll (fields[27]);
823                 unsigned long long stack_ptr   = atoll (fields[28]);
824
825                 stack_size = (stack_start > stack_ptr)
826                         ? stack_start - stack_ptr
827                         : stack_ptr - stack_start;
828         }
829
830         /* Convert jiffies to useconds */
831         cpu_user_counter   = cpu_user_counter   * 1000000 / CONFIG_HZ;
832         cpu_system_counter = cpu_system_counter * 1000000 / CONFIG_HZ;
833         vmem_rss = vmem_rss * pagesize_g;
834
835         ps->cpu_user_counter = (unsigned long) cpu_user_counter;
836         ps->cpu_system_counter = (unsigned long) cpu_system_counter;
837         ps->vmem_size = (unsigned long) vmem_size;
838         ps->vmem_rss = (unsigned long) vmem_rss;
839         ps->stack_size = (unsigned long) stack_size;
840
841         if ( (ps_read_io (pid, ps)) == NULL)
842         {
843                 /* no io data */
844                 ps->io_rchar = -1;
845                 ps->io_wchar = -1;
846                 ps->io_syscr = -1;
847                 ps->io_syscw = -1;
848
849                 DEBUG("ps_read_process: not get io data for pid %i",pid);
850         }
851
852         /* success */
853         return (0);
854 } /* int ps_read_process (...) */
855
856 static char *ps_get_cmdline (pid_t pid, char *name, char *buf, size_t buf_len)
857 {
858         char  *buf_ptr;
859         size_t len;
860
861         char file[PATH_MAX];
862         int  fd;
863
864         size_t n;
865
866         if ((pid < 1) || (NULL == buf) || (buf_len < 2))
867                 return NULL;
868
869         ssnprintf (file, sizeof (file), "/proc/%u/cmdline", pid);
870
871         fd = open (file, O_RDONLY);
872         if (fd < 0) {
873                 char errbuf[4096];
874                 WARNING ("processes plugin: Failed to open `%s': %s.", file,
875                                 sstrerror (errno, errbuf, sizeof (errbuf)));
876                 return NULL;
877         }
878
879         buf_ptr = buf;
880         len     = buf_len;
881
882         n = 0;
883
884         while (42) {
885                 ssize_t status;
886
887                 status = read (fd, (void *)buf_ptr, len);
888
889                 if (status < 0) {
890                         char errbuf[4096];
891
892                         if ((EAGAIN == errno) || (EINTR == errno))
893                                 continue;
894
895                         WARNING ("processes plugin: Failed to read from `%s': %s.", file,
896                                         sstrerror (errno, errbuf, sizeof (errbuf)));
897                         close (fd);
898                         return NULL;
899                 }
900
901                 n += status;
902
903                 if (status == 0)
904                         break;
905
906                 buf_ptr += status;
907                 len     -= status;
908
909                 if (len <= 0)
910                         break;
911         }
912
913         close (fd);
914
915         if (0 == n) {
916                 /* cmdline not available; e.g. kernel thread, zombie */
917                 if (NULL == name)
918                         return NULL;
919
920                 ssnprintf (buf, buf_len, "[%s]", name);
921                 return buf;
922         }
923
924         assert (n <= buf_len);
925
926         if (n == buf_len)
927                 --n;
928         buf[n] = '\0';
929
930         --n;
931         /* remove trailing whitespace */
932         while ((n > 0) && (isspace (buf[n]) || ('\0' == buf[n]))) {
933                 buf[n] = '\0';
934                 --n;
935         }
936
937         /* arguments are separated by '\0' in /proc/<pid>/cmdline */
938         while (n > 0) {
939                 if ('\0' == buf[n])
940                         buf[n] = ' ';
941                 --n;
942         }
943         return buf;
944 } /* char *ps_get_cmdline (...) */
945
946 static unsigned long read_fork_rate ()
947 {
948         FILE *proc_stat;
949         char buf[1024];
950         unsigned long result = 0;
951         int numfields;
952         char *fields[3];
953
954         proc_stat = fopen("/proc/stat", "r");
955         if (proc_stat == NULL) {
956                 char errbuf[1024];
957                 ERROR ("processes plugin: fopen (/proc/stat) failed: %s",
958                                 sstrerror (errno, errbuf, sizeof (errbuf)));
959                 return ULONG_MAX;
960         }
961
962         while (fgets (buf, sizeof(buf), proc_stat) != NULL)
963         {
964                 char *endptr;
965
966                 numfields = strsplit(buf, fields, STATIC_ARRAY_SIZE (fields));
967                 if (numfields != 2)
968                         continue;
969
970                 if (strcmp ("processes", fields[0]) != 0)
971                         continue;
972
973                 errno = 0;
974                 endptr = NULL;
975                 result = strtoul(fields[1], &endptr, 10);
976                 if ((endptr == fields[1]) || (errno != 0)) {
977                         ERROR ("processes plugin: Cannot parse fork rate: %s",
978                                         fields[1]);
979                         result = ULONG_MAX;
980                         break;
981                 }
982
983                 break;
984         }
985
986         fclose(proc_stat);
987
988         return result;
989 }
990
991 static void ps_submit_fork_rate (unsigned long value)
992 {
993         value_t values[1];
994         value_list_t vl = VALUE_LIST_INIT;
995
996         values[0].derive = (derive_t) value;
997
998         vl.values = values;
999         vl.values_len = 1;
1000         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
1001         sstrncpy (vl.plugin, "processes", sizeof (vl.plugin));
1002         sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
1003         sstrncpy (vl.type, "fork_rate", sizeof (vl.type));
1004         sstrncpy (vl.type_instance, "", sizeof (vl.type_instance));
1005
1006         plugin_dispatch_values (&vl);
1007 }
1008
1009 #endif /* KERNEL_LINUX */
1010
1011 #if HAVE_THREAD_INFO
1012 static int mach_get_task_name (task_t t, int *pid, char *name, size_t name_max_len)
1013 {
1014         int mib[4];
1015
1016         struct kinfo_proc kp;
1017         size_t            kp_size;
1018
1019         mib[0] = CTL_KERN;
1020         mib[1] = KERN_PROC;
1021         mib[2] = KERN_PROC_PID;
1022
1023         if (pid_for_task (t, pid) != KERN_SUCCESS)
1024                 return (-1);
1025         mib[3] = *pid;
1026
1027         kp_size = sizeof (kp);
1028         if (sysctl (mib, 4, &kp, &kp_size, NULL, 0) != 0)
1029                 return (-1);
1030
1031         if (name_max_len > (MAXCOMLEN + 1))
1032                 name_max_len = MAXCOMLEN + 1;
1033
1034         strncpy (name, kp.kp_proc.p_comm, name_max_len - 1);
1035         name[name_max_len - 1] = '\0';
1036
1037         DEBUG ("pid = %i; name = %s;", *pid, name);
1038
1039         /* We don't do the special handling for `p_comm == "LaunchCFMApp"' as
1040          * `top' does it, because it is a lot of work and only used when
1041          * debugging. -octo */
1042
1043         return (0);
1044 }
1045 #endif /* HAVE_THREAD_INFO */
1046 /* ------- end of additional functions for KERNEL_LINUX/HAVE_THREAD_INFO ------- */
1047
1048 /* do actual readings from kernel */
1049 static int ps_read (void)
1050 {
1051 #if HAVE_THREAD_INFO
1052         kern_return_t            status;
1053
1054         int                      pset;
1055         processor_set_t          port_pset_priv;
1056
1057         int                      task;
1058         task_array_t             task_list;
1059         mach_msg_type_number_t   task_list_len;
1060
1061         int                      task_pid;
1062         char                     task_name[MAXCOMLEN + 1];
1063
1064         int                      thread;
1065         thread_act_array_t       thread_list;
1066         mach_msg_type_number_t   thread_list_len;
1067         thread_basic_info_data_t thread_data;
1068         mach_msg_type_number_t   thread_data_len;
1069
1070         int running  = 0;
1071         int sleeping = 0;
1072         int zombies  = 0;
1073         int stopped  = 0;
1074         int blocked  = 0;
1075
1076         procstat_t *ps;
1077         procstat_entry_t pse;
1078
1079         ps_list_reset ();
1080
1081         /*
1082          * The Mach-concept is a little different from the traditional UNIX
1083          * concept: All the work is done in threads. Threads are contained in
1084          * `tasks'. Therefore, `task status' doesn't make much sense, since
1085          * it's actually a `thread status'.
1086          * Tasks are assigned to sets of processors, so that's where you go to
1087          * get a list.
1088          */
1089         for (pset = 0; pset < pset_list_len; pset++)
1090         {
1091                 if ((status = host_processor_set_priv (port_host_self,
1092                                                 pset_list[pset],
1093                                                 &port_pset_priv)) != KERN_SUCCESS)
1094                 {
1095                         ERROR ("host_processor_set_priv failed: %s\n",
1096                                         mach_error_string (status));
1097                         continue;
1098                 }
1099
1100                 if ((status = processor_set_tasks (port_pset_priv,
1101                                                 &task_list,
1102                                                 &task_list_len)) != KERN_SUCCESS)
1103                 {
1104                         ERROR ("processor_set_tasks failed: %s\n",
1105                                         mach_error_string (status));
1106                         mach_port_deallocate (port_task_self, port_pset_priv);
1107                         continue;
1108                 }
1109
1110                 for (task = 0; task < task_list_len; task++)
1111                 {
1112                         ps = NULL;
1113                         if (mach_get_task_name (task_list[task],
1114                                                 &task_pid,
1115                                                 task_name, PROCSTAT_NAME_LEN) == 0)
1116                         {
1117                                 /* search for at least one match */
1118                                 for (ps = list_head_g; ps != NULL; ps = ps->next)
1119                                         /* FIXME: cmdline should be here instead of NULL */
1120                                         if (ps_list_match (task_name, NULL, ps) == 1)
1121                                                 break;
1122                         }
1123
1124                         /* Collect more detailed statistics for this process */
1125                         if (ps != NULL)
1126                         {
1127                                 task_basic_info_data_t        task_basic_info;
1128                                 mach_msg_type_number_t        task_basic_info_len;
1129                                 task_events_info_data_t       task_events_info;
1130                                 mach_msg_type_number_t        task_events_info_len;
1131                                 task_absolutetime_info_data_t task_absolutetime_info;
1132                                 mach_msg_type_number_t        task_absolutetime_info_len;
1133
1134                                 memset (&pse, '\0', sizeof (pse));
1135                                 pse.id = task_pid;
1136
1137                                 task_basic_info_len = TASK_BASIC_INFO_COUNT;
1138                                 status = task_info (task_list[task],
1139                                                 TASK_BASIC_INFO,
1140                                                 (task_info_t) &task_basic_info,
1141                                                 &task_basic_info_len);
1142                                 if (status != KERN_SUCCESS)
1143                                 {
1144                                         ERROR ("task_info failed: %s",
1145                                                         mach_error_string (status));
1146                                         continue; /* with next thread_list */
1147                                 }
1148
1149                                 task_events_info_len = TASK_EVENTS_INFO_COUNT;
1150                                 status = task_info (task_list[task],
1151                                                 TASK_EVENTS_INFO,
1152                                                 (task_info_t) &task_events_info,
1153                                                 &task_events_info_len);
1154                                 if (status != KERN_SUCCESS)
1155                                 {
1156                                         ERROR ("task_info failed: %s",
1157                                                         mach_error_string (status));
1158                                         continue; /* with next thread_list */
1159                                 }
1160
1161                                 task_absolutetime_info_len = TASK_ABSOLUTETIME_INFO_COUNT;
1162                                 status = task_info (task_list[task],
1163                                                 TASK_ABSOLUTETIME_INFO,
1164                                                 (task_info_t) &task_absolutetime_info,
1165                                                 &task_absolutetime_info_len);
1166                                 if (status != KERN_SUCCESS)
1167                                 {
1168                                         ERROR ("task_info failed: %s",
1169                                                         mach_error_string (status));
1170                                         continue; /* with next thread_list */
1171                                 }
1172
1173                                 pse.num_proc++;
1174                                 pse.vmem_rss = task_basic_info.resident_size;
1175
1176                                 pse.vmem_minflt_counter = task_events_info.cow_faults;
1177                                 pse.vmem_majflt_counter = task_events_info.faults;
1178
1179                                 pse.cpu_user_counter = task_absolutetime_info.total_user;
1180                                 pse.cpu_system_counter = task_absolutetime_info.total_system;
1181                         }
1182
1183                         status = task_threads (task_list[task], &thread_list,
1184                                         &thread_list_len);
1185                         if (status != KERN_SUCCESS)
1186                         {
1187                                 /* Apple's `top' treats this case a zombie. It
1188                                  * makes sense to some extend: A `zombie'
1189                                  * thread is nonsense, since the task/process
1190                                  * is dead. */
1191                                 zombies++;
1192                                 DEBUG ("task_threads failed: %s",
1193                                                 mach_error_string (status));
1194                                 if (task_list[task] != port_task_self)
1195                                         mach_port_deallocate (port_task_self,
1196                                                         task_list[task]);
1197                                 continue; /* with next task_list */
1198                         }
1199
1200                         for (thread = 0; thread < thread_list_len; thread++)
1201                         {
1202                                 thread_data_len = THREAD_BASIC_INFO_COUNT;
1203                                 status = thread_info (thread_list[thread],
1204                                                 THREAD_BASIC_INFO,
1205                                                 (thread_info_t) &thread_data,
1206                                                 &thread_data_len);
1207                                 if (status != KERN_SUCCESS)
1208                                 {
1209                                         ERROR ("thread_info failed: %s",
1210                                                         mach_error_string (status));
1211                                         if (task_list[task] != port_task_self)
1212                                                 mach_port_deallocate (port_task_self,
1213                                                                 thread_list[thread]);
1214                                         continue; /* with next thread_list */
1215                                 }
1216
1217                                 if (ps != NULL)
1218                                         pse.num_lwp++;
1219
1220                                 switch (thread_data.run_state)
1221                                 {
1222                                         case TH_STATE_RUNNING:
1223                                                 running++;
1224                                                 break;
1225                                         case TH_STATE_STOPPED:
1226                                         /* What exactly is `halted'? */
1227                                         case TH_STATE_HALTED:
1228                                                 stopped++;
1229                                                 break;
1230                                         case TH_STATE_WAITING:
1231                                                 sleeping++;
1232                                                 break;
1233                                         case TH_STATE_UNINTERRUPTIBLE:
1234                                                 blocked++;
1235                                                 break;
1236                                         /* There is no `zombie' case here,
1237                                          * since there are no zombie-threads.
1238                                          * There's only zombie tasks, which are
1239                                          * handled above. */
1240                                         default:
1241                                                 WARNING ("Unknown thread status: %i",
1242                                                                 thread_data.run_state);
1243                                                 break;
1244                                 } /* switch (thread_data.run_state) */
1245
1246                                 if (task_list[task] != port_task_self)
1247                                 {
1248                                         status = mach_port_deallocate (port_task_self,
1249                                                         thread_list[thread]);
1250                                         if (status != KERN_SUCCESS)
1251                                                 ERROR ("mach_port_deallocate failed: %s",
1252                                                                 mach_error_string (status));
1253                                 }
1254                         } /* for (thread_list) */
1255
1256                         if ((status = vm_deallocate (port_task_self,
1257                                                         (vm_address_t) thread_list,
1258                                                         thread_list_len * sizeof (thread_act_t)))
1259                                         != KERN_SUCCESS)
1260                         {
1261                                 ERROR ("vm_deallocate failed: %s",
1262                                                 mach_error_string (status));
1263                         }
1264                         thread_list = NULL;
1265                         thread_list_len = 0;
1266
1267                         /* Only deallocate the task port, if it isn't our own.
1268                          * Don't know what would happen in that case, but this
1269                          * is what Apple's top does.. ;) */
1270                         if (task_list[task] != port_task_self)
1271                         {
1272                                 status = mach_port_deallocate (port_task_self,
1273                                                 task_list[task]);
1274                                 if (status != KERN_SUCCESS)
1275                                         ERROR ("mach_port_deallocate failed: %s",
1276                                                         mach_error_string (status));
1277                         }
1278
1279                         if (ps != NULL)
1280                                 /* FIXME: cmdline should be here instead of NULL */
1281                                 ps_list_add (task_name, NULL, &pse);
1282                 } /* for (task_list) */
1283
1284                 if ((status = vm_deallocate (port_task_self,
1285                                 (vm_address_t) task_list,
1286                                 task_list_len * sizeof (task_t))) != KERN_SUCCESS)
1287                 {
1288                         ERROR ("vm_deallocate failed: %s",
1289                                         mach_error_string (status));
1290                 }
1291                 task_list = NULL;
1292                 task_list_len = 0;
1293
1294                 if ((status = mach_port_deallocate (port_task_self, port_pset_priv))
1295                                 != KERN_SUCCESS)
1296                 {
1297                         ERROR ("mach_port_deallocate failed: %s",
1298                                         mach_error_string (status));
1299                 }
1300         } /* for (pset_list) */
1301
1302         ps_submit_state ("running", running);
1303         ps_submit_state ("sleeping", sleeping);
1304         ps_submit_state ("zombies", zombies);
1305         ps_submit_state ("stopped", stopped);
1306         ps_submit_state ("blocked", blocked);
1307
1308         for (ps = list_head_g; ps != NULL; ps = ps->next)
1309                 ps_submit_proc_list (ps);
1310 /* #endif HAVE_THREAD_INFO */
1311
1312 #elif KERNEL_LINUX
1313         int running  = 0;
1314         int sleeping = 0;
1315         int zombies  = 0;
1316         int stopped  = 0;
1317         int paging   = 0;
1318         int blocked  = 0;
1319
1320         struct dirent *ent;
1321         DIR           *proc;
1322         int            pid;
1323
1324         char cmdline[ARG_MAX];
1325
1326         int        status;
1327         procstat_t ps;
1328         procstat_entry_t pse;
1329         char       state;
1330
1331         unsigned long fork_rate;
1332
1333         procstat_t *ps_ptr;
1334
1335         running = sleeping = zombies = stopped = paging = blocked = 0;
1336         ps_list_reset ();
1337
1338         if ((proc = opendir ("/proc")) == NULL)
1339         {
1340                 char errbuf[1024];
1341                 ERROR ("Cannot open `/proc': %s",
1342                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1343                 return (-1);
1344         }
1345
1346         while ((ent = readdir (proc)) != NULL)
1347         {
1348                 if (!isdigit (ent->d_name[0]))
1349                         continue;
1350
1351                 if ((pid = atoi (ent->d_name)) < 1)
1352                         continue;
1353
1354                 status = ps_read_process (pid, &ps, &state);
1355                 if (status != 0)
1356                 {
1357                         DEBUG ("ps_read_process failed: %i", status);
1358                         continue;
1359                 }
1360
1361                 pse.id       = pid;
1362                 pse.age      = 0;
1363
1364                 pse.num_proc   = ps.num_proc;
1365                 pse.num_lwp    = ps.num_lwp;
1366                 pse.vmem_size  = ps.vmem_size;
1367                 pse.vmem_rss   = ps.vmem_rss;
1368                 pse.stack_size = ps.stack_size;
1369
1370                 pse.vmem_minflt = 0;
1371                 pse.vmem_minflt_counter = ps.vmem_minflt_counter;
1372                 pse.vmem_majflt = 0;
1373                 pse.vmem_majflt_counter = ps.vmem_majflt_counter;
1374
1375                 pse.cpu_user = 0;
1376                 pse.cpu_user_counter = ps.cpu_user_counter;
1377                 pse.cpu_system = 0;
1378                 pse.cpu_system_counter = ps.cpu_system_counter;
1379
1380                 pse.io_rchar = ps.io_rchar;
1381                 pse.io_wchar = ps.io_wchar;
1382                 pse.io_syscr = ps.io_syscr;
1383                 pse.io_syscw = ps.io_syscw;
1384
1385                 switch (state)
1386                 {
1387                         case 'R': running++;  break;
1388                         case 'S': sleeping++; break;
1389                         case 'D': blocked++;  break;
1390                         case 'Z': zombies++;  break;
1391                         case 'T': stopped++;  break;
1392                         case 'W': paging++;   break;
1393                 }
1394
1395                 ps_list_add (ps.name,
1396                                 ps_get_cmdline (pid, ps.name, cmdline, sizeof (cmdline)),
1397                                 &pse);
1398         }
1399
1400         closedir (proc);
1401
1402         ps_submit_state ("running",  running);
1403         ps_submit_state ("sleeping", sleeping);
1404         ps_submit_state ("zombies",  zombies);
1405         ps_submit_state ("stopped",  stopped);
1406         ps_submit_state ("paging",   paging);
1407         ps_submit_state ("blocked",  blocked);
1408
1409         for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
1410                 ps_submit_proc_list (ps_ptr);
1411
1412         fork_rate = read_fork_rate();
1413         if (fork_rate != ULONG_MAX)
1414                 ps_submit_fork_rate(fork_rate);
1415 /* #endif KERNEL_LINUX */
1416
1417 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
1418         int running  = 0;
1419         int sleeping = 0;
1420         int zombies  = 0;
1421         int stopped  = 0;
1422         int blocked  = 0;
1423         int idle     = 0;
1424         int wait     = 0;
1425
1426         kvm_t *kd;
1427         char errbuf[1024];
1428         char cmdline[ARG_MAX];
1429         char *cmdline_ptr;
1430         struct kinfo_proc *procs;          /* array of processes */
1431         char **argv;
1432         int count;                         /* returns number of processes */
1433         int i;
1434
1435         procstat_t *ps_ptr;
1436         procstat_entry_t pse;
1437
1438         ps_list_reset ();
1439
1440         /* Open the kvm interface, get a descriptor */
1441         kd = kvm_open (NULL, NULL, NULL, 0, errbuf);
1442         if (kd == NULL)
1443         {
1444                 ERROR ("processes plugin: Cannot open kvm interface: %s",
1445                                 errbuf);
1446                 return (0);
1447         }
1448
1449         /* Get the list of processes. */
1450         procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, &count);
1451         if (procs == NULL)
1452         {
1453                 kvm_close (kd);
1454                 ERROR ("processes plugin: Cannot get kvm processes list: %s",
1455                                 kvm_geterr(kd));
1456                 return (0);
1457         }
1458
1459         /* Iterate through the processes in kinfo_proc */
1460         for (i = 0; i < count; i++)
1461         {
1462                 /* retrieve the arguments */
1463                 cmdline[0] = 0;
1464                 cmdline_ptr = NULL;
1465
1466                 argv = kvm_getargv (kd, (const struct kinfo_proc *) &(procs[i]), 0);
1467                 if (argv != NULL)
1468                 {
1469                         int status;
1470                         int argc;
1471
1472                         argc = 0;
1473                         while (argv[argc] != NULL)
1474                                 argc++;
1475
1476                         status = strjoin (cmdline, sizeof (cmdline),
1477                                         argv, argc, " ");
1478
1479                         if (status < 0)
1480                         {
1481                                 WARNING ("processes plugin: Command line did "
1482                                                 "not fit into buffer.");
1483                         }
1484                         else
1485                         {
1486                                 cmdline_ptr = &cmdline[0];
1487                         }
1488                 }
1489
1490                 pse.id       = procs[i].ki_pid;
1491                 pse.age      = 0;
1492
1493                 pse.num_proc = 1;
1494                 pse.num_lwp  = procs[i].ki_numthreads;
1495
1496                 pse.vmem_size = procs[i].ki_size;
1497                 pse.vmem_rss = procs[i].ki_rssize * getpagesize();
1498                 pse.stack_size = procs[i].ki_ssize * getpagesize();
1499                 pse.vmem_minflt = 0;
1500                 pse.vmem_minflt_counter = procs[i].ki_rusage.ru_minflt;
1501                 pse.vmem_majflt = 0;
1502                 pse.vmem_majflt_counter = procs[i].ki_rusage.ru_majflt;
1503
1504                 pse.cpu_user = 0;
1505                 pse.cpu_user_counter = procs[i].ki_rusage.ru_utime.tv_sec
1506                         * 1000
1507                         + procs[i].ki_rusage.ru_utime.tv_usec;
1508                 pse.cpu_system = 0;
1509                 pse.cpu_system_counter = procs[i].ki_rusage.ru_stime.tv_sec
1510                         * 1000
1511                         + procs[i].ki_rusage.ru_stime.tv_usec;
1512
1513                 switch (procs[i].ki_stat)
1514                 {
1515                         case SSTOP:     stopped++;      break;
1516                         case SSLEEP:    sleeping++;     break;
1517                         case SRUN:      running++;      break;
1518                         case SIDL:      idle++;         break;
1519                         case SWAIT:     wait++;         break;
1520                         case SLOCK:     blocked++;      break;
1521                         case SZOMB:     zombies++;      break;
1522                 }
1523
1524                 ps_list_add (procs[i].ki_comm, cmdline_ptr, &pse);
1525         }
1526
1527         kvm_close(kd);
1528
1529         ps_submit_state ("running",  running);
1530         ps_submit_state ("sleeping", sleeping);
1531         ps_submit_state ("zombies",  zombies);
1532         ps_submit_state ("stopped",  stopped);
1533         ps_submit_state ("blocked",  blocked);
1534         ps_submit_state ("idle",     idle);
1535         ps_submit_state ("wait",     wait);
1536
1537         for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
1538                 ps_submit_proc_list (ps_ptr);
1539 #endif /* HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
1540
1541         return (0);
1542 } /* int ps_read */
1543
1544 void module_register (void)
1545 {
1546         plugin_register_config ("processes", ps_config,
1547                         config_keys, config_keys_num);
1548         plugin_register_init ("processes", ps_init);
1549         plugin_register_read ("processes", ps_read);
1550 } /* void module_register */