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