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