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