clang formatting
[collectd.git] / src / procevent.c
1 /**
2  * collectd - src/procevent.c
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20  * DEALINGS IN THE SOFTWARE.
21  *
22  * Authors:
23  *   Red Hat NFVPE
24  *     Andrew Bays <abays at redhat.com>
25  **/
26
27 #include "collectd.h"
28
29 #include "common.h"
30 #include "plugin.h"
31 #include "utils_complain.h"
32 #include "utils_ignorelist.h"
33
34 #include <errno.h>
35 #include <pthread.h>
36 #include <stdio.h>
37 #include <string.h>
38 #include <sys/socket.h>
39 #include <unistd.h>
40
41 #include <dirent.h>
42 #include <linux/cn_proc.h>
43 #include <linux/connector.h>
44 #include <linux/netlink.h>
45 #include <linux/rtnetlink.h>
46 #include <signal.h>
47 #include <stdbool.h>
48 #include <stdlib.h>
49 #include <string.h>
50
51 #include <yajl/yajl_common.h>
52 #include <yajl/yajl_gen.h>
53 #if HAVE_YAJL_YAJL_VERSION_H
54 #include <yajl/yajl_version.h>
55 #endif
56 #if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
57 #define HAVE_YAJL_V2 1
58 #endif
59
60 #define PROCEVENT_EXITED 0
61 #define PROCEVENT_STARTED 1
62 #define PROCEVENT_FIELDS 4 // pid, status, extra, timestamp
63 #define BUFSIZE 512
64 #define PROCDIR "/proc"
65
66 #define PROCEVENT_DOMAIN_FIELD "domain"
67 #define PROCEVENT_DOMAIN_VALUE "fault"
68 #define PROCEVENT_EVENT_ID_FIELD "eventId"
69 #define PROCEVENT_EVENT_NAME_FIELD "eventName"
70 #define PROCEVENT_EVENT_NAME_DOWN_VALUE "down"
71 #define PROCEVENT_EVENT_NAME_UP_VALUE "up"
72 #define PROCEVENT_LAST_EPOCH_MICROSEC_FIELD "lastEpochMicrosec"
73 #define PROCEVENT_PRIORITY_FIELD "priority"
74 #define PROCEVENT_PRIORITY_VALUE "high"
75 #define PROCEVENT_REPORTING_ENTITY_NAME_FIELD "reportingEntityName"
76 #define PROCEVENT_REPORTING_ENTITY_NAME_VALUE "collectd procevent plugin"
77 #define PROCEVENT_SEQUENCE_FIELD "sequence"
78 #define PROCEVENT_SEQUENCE_VALUE "0"
79 #define PROCEVENT_SOURCE_NAME_FIELD "sourceName"
80 #define PROCEVENT_START_EPOCH_MICROSEC_FIELD "startEpochMicrosec"
81 #define PROCEVENT_VERSION_FIELD "version"
82 #define PROCEVENT_VERSION_VALUE "1.0"
83
84 #define PROCEVENT_ALARM_CONDITION_FIELD "alarmCondition"
85 #define PROCEVENT_ALARM_INTERFACE_A_FIELD "alarmInterfaceA"
86 #define PROCEVENT_EVENT_SEVERITY_FIELD "eventSeverity"
87 #define PROCEVENT_EVENT_SEVERITY_CRITICAL_VALUE "CRITICAL"
88 #define PROCEVENT_EVENT_SEVERITY_NORMAL_VALUE "NORMAL"
89 #define PROCEVENT_EVENT_SOURCE_TYPE_FIELD "eventSourceType"
90 #define PROCEVENT_EVENT_SOURCE_TYPE_VALUE "process"
91 #define PROCEVENT_FAULT_FIELDS_FIELD "faultFields"
92 #define PROCEVENT_FAULT_FIELDS_VERSION_FIELD "faultFieldsVersion"
93 #define PROCEVENT_FAULT_FIELDS_VERSION_VALUE "1.0"
94 #define PROCEVENT_SPECIFIC_PROBLEM_FIELD "specificProblem"
95 #define PROCEVENT_SPECIFIC_PROBLEM_DOWN_VALUE "down"
96 #define PROCEVENT_SPECIFIC_PROBLEM_UP_VALUE "up"
97 #define PROCEVENT_VF_STATUS_FIELD "vfStatus"
98 #define PROCEVENT_VF_STATUS_CRITICAL_VALUE "Ready to terminate"
99 #define PROCEVENT_VF_STATUS_NORMAL_VALUE "Active"
100
101 /*
102  * Private data types
103  */
104
105 typedef struct {
106   int head;
107   int tail;
108   int maxLen;
109   long long unsigned int **buffer;
110 } circbuf_t;
111
112 struct processlist_s {
113   char *process;
114
115   long pid;
116   int32_t last_status;
117
118   struct processlist_s *next;
119 };
120 typedef struct processlist_s processlist_t;
121
122 /*
123  * Private variables
124  */
125 static ignorelist_t *ignorelist = NULL;
126
127 static int procevent_thread_loop = 0;
128 static int procevent_thread_error = 0;
129 static pthread_t procevent_thread_id;
130 static pthread_mutex_t procevent_lock = PTHREAD_MUTEX_INITIALIZER;
131 static pthread_cond_t procevent_cond = PTHREAD_COND_INITIALIZER;
132 static pthread_mutex_t procevent_list_lock = PTHREAD_MUTEX_INITIALIZER;
133 static int nl_sock = -1;
134 static int buffer_length;
135 static circbuf_t ring;
136 static processlist_t *processlist_head = NULL;
137 static int event_id = 0;
138
139 static const char *config_keys[] = {"BufferLength", "Process", "RegexProcess"};
140 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
141
142 /*
143  * Private functions
144  */
145
146 static int gen_message_payload(int state, int pid, char *process,
147                                long long unsigned int timestamp, char **buf) {
148   const unsigned char *buf2;
149   yajl_gen g;
150   char json_str[DATA_MAX_NAME_LEN];
151
152 #if !defined(HAVE_YAJL_V2)
153   yajl_gen_config conf = {};
154
155   conf.beautify = 0;
156 #endif
157
158 #if HAVE_YAJL_V2
159   size_t len;
160   g = yajl_gen_alloc(NULL);
161   yajl_gen_config(g, yajl_gen_beautify, 0);
162 #else
163   unsigned int len;
164   g = yajl_gen_alloc(&conf, NULL);
165 #endif
166
167   yajl_gen_clear(g);
168
169   // *** BEGIN common event header ***
170
171   if (yajl_gen_map_open(g) != yajl_gen_status_ok)
172     goto err;
173
174   // domain
175   if (yajl_gen_string(g, (u_char *)PROCEVENT_DOMAIN_FIELD,
176                       strlen(PROCEVENT_DOMAIN_FIELD)) != yajl_gen_status_ok)
177     goto err;
178
179   if (yajl_gen_string(g, (u_char *)PROCEVENT_DOMAIN_VALUE,
180                       strlen(PROCEVENT_DOMAIN_VALUE)) != yajl_gen_status_ok)
181     goto err;
182
183   // eventId
184   if (yajl_gen_string(g, (u_char *)PROCEVENT_EVENT_ID_FIELD,
185                       strlen(PROCEVENT_EVENT_ID_FIELD)) != yajl_gen_status_ok)
186     goto err;
187
188   event_id = event_id + 1;
189   int event_id_len = sizeof(char) * sizeof(int) * 4 + 1;
190   memset(json_str, '\0', DATA_MAX_NAME_LEN);
191   snprintf(json_str, event_id_len, "%d", event_id);
192
193   if (yajl_gen_number(g, json_str, strlen(json_str)) != yajl_gen_status_ok) {
194     goto err;
195   }
196
197   // eventName
198   if (yajl_gen_string(g, (u_char *)PROCEVENT_EVENT_NAME_FIELD,
199                       strlen(PROCEVENT_EVENT_NAME_FIELD)) != yajl_gen_status_ok)
200     goto err;
201
202   int event_name_len = 0;
203   event_name_len = event_name_len + (sizeof(char) * sizeof(int) * 4); // pid
204   event_name_len = event_name_len + strlen(process);      // process name
205   event_name_len = event_name_len + (state == 0 ? 4 : 2); // "down" or "up"
206   event_name_len = event_name_len +
207                    13; // "process", 3 spaces, 2 parentheses and null-terminator
208   memset(json_str, '\0', DATA_MAX_NAME_LEN);
209   snprintf(json_str, event_name_len, "process %s (%d) %s", process, pid,
210            (state == 0 ? PROCEVENT_EVENT_NAME_DOWN_VALUE
211                        : PROCEVENT_EVENT_NAME_UP_VALUE));
212
213   if (yajl_gen_string(g, (u_char *)json_str, strlen(json_str)) !=
214       yajl_gen_status_ok) {
215     goto err;
216   }
217
218   // lastEpochMicrosec
219   if (yajl_gen_string(g, (u_char *)PROCEVENT_LAST_EPOCH_MICROSEC_FIELD,
220                       strlen(PROCEVENT_LAST_EPOCH_MICROSEC_FIELD)) !=
221       yajl_gen_status_ok)
222     goto err;
223
224   int last_epoch_microsec_len =
225       sizeof(char) * sizeof(long long unsigned int) * 4 + 1;
226   memset(json_str, '\0', DATA_MAX_NAME_LEN);
227   snprintf(json_str, last_epoch_microsec_len, "%llu",
228            (long long unsigned int)CDTIME_T_TO_US(cdtime()));
229
230   if (yajl_gen_number(g, json_str, strlen(json_str)) != yajl_gen_status_ok) {
231     goto err;
232   }
233
234   // priority
235   if (yajl_gen_string(g, (u_char *)PROCEVENT_PRIORITY_FIELD,
236                       strlen(PROCEVENT_PRIORITY_FIELD)) != yajl_gen_status_ok)
237     goto err;
238
239   if (yajl_gen_string(g, (u_char *)PROCEVENT_PRIORITY_VALUE,
240                       strlen(PROCEVENT_PRIORITY_VALUE)) != yajl_gen_status_ok)
241     goto err;
242
243   // reportingEntityName
244   if (yajl_gen_string(g, (u_char *)PROCEVENT_REPORTING_ENTITY_NAME_FIELD,
245                       strlen(PROCEVENT_REPORTING_ENTITY_NAME_FIELD)) !=
246       yajl_gen_status_ok)
247     goto err;
248
249   if (yajl_gen_string(g, (u_char *)PROCEVENT_REPORTING_ENTITY_NAME_VALUE,
250                       strlen(PROCEVENT_REPORTING_ENTITY_NAME_VALUE)) !=
251       yajl_gen_status_ok)
252     goto err;
253
254   // sequence
255   if (yajl_gen_string(g, (u_char *)PROCEVENT_SEQUENCE_FIELD,
256                       strlen(PROCEVENT_SEQUENCE_FIELD)) != yajl_gen_status_ok)
257     goto err;
258
259   if (yajl_gen_number(g, PROCEVENT_SEQUENCE_VALUE,
260                       strlen(PROCEVENT_SEQUENCE_VALUE)) != yajl_gen_status_ok)
261     goto err;
262
263   // sourceName
264   if (yajl_gen_string(g, (u_char *)PROCEVENT_SOURCE_NAME_FIELD,
265                       strlen(PROCEVENT_SOURCE_NAME_FIELD)) !=
266       yajl_gen_status_ok)
267     goto err;
268
269   if (yajl_gen_string(g, (u_char *)process, strlen(process)) !=
270       yajl_gen_status_ok)
271     goto err;
272
273   // startEpochMicrosec
274   if (yajl_gen_string(g, (u_char *)PROCEVENT_START_EPOCH_MICROSEC_FIELD,
275                       strlen(PROCEVENT_START_EPOCH_MICROSEC_FIELD)) !=
276       yajl_gen_status_ok)
277     goto err;
278
279   int start_epoch_microsec_len =
280       sizeof(char) * sizeof(long long unsigned int) * 4 + 1;
281   memset(json_str, '\0', DATA_MAX_NAME_LEN);
282   snprintf(json_str, start_epoch_microsec_len, "%llu",
283            (long long unsigned int)timestamp);
284
285   if (yajl_gen_number(g, json_str, strlen(json_str)) != yajl_gen_status_ok) {
286     goto err;
287   }
288
289   // version
290   if (yajl_gen_string(g, (u_char *)PROCEVENT_VERSION_FIELD,
291                       strlen(PROCEVENT_VERSION_FIELD)) != yajl_gen_status_ok)
292     goto err;
293
294   if (yajl_gen_number(g, PROCEVENT_VERSION_VALUE,
295                       strlen(PROCEVENT_VERSION_VALUE)) != yajl_gen_status_ok)
296     goto err;
297
298   // *** END common event header ***
299
300   // *** BEGIN fault fields ***
301
302   if (yajl_gen_string(g, (u_char *)PROCEVENT_FAULT_FIELDS_FIELD,
303                       strlen(PROCEVENT_FAULT_FIELDS_FIELD)) !=
304       yajl_gen_status_ok)
305     goto err;
306
307   if (yajl_gen_map_open(g) != yajl_gen_status_ok)
308     goto err;
309
310   // alarmCondition
311   if (yajl_gen_string(g, (u_char *)PROCEVENT_ALARM_CONDITION_FIELD,
312                       strlen(PROCEVENT_ALARM_CONDITION_FIELD)) !=
313       yajl_gen_status_ok)
314     goto err;
315
316   int alarm_condition_len = 0;
317   alarm_condition_len =
318       alarm_condition_len + (sizeof(char) * sizeof(int) * 4);  // pid
319   alarm_condition_len = alarm_condition_len + strlen(process); // process name
320   alarm_condition_len =
321       alarm_condition_len + 25; // "process", "state", "change", 4 spaces, 2
322                                 // parentheses and null-terminator
323   memset(json_str, '\0', DATA_MAX_NAME_LEN);
324   snprintf(json_str, alarm_condition_len, "process %s (%d) state change",
325            process, pid);
326
327   if (yajl_gen_string(g, (u_char *)json_str, strlen(json_str)) !=
328       yajl_gen_status_ok) {
329     goto err;
330   }
331
332   // alarmInterfaceA
333   if (yajl_gen_string(g, (u_char *)PROCEVENT_ALARM_INTERFACE_A_FIELD,
334                       strlen(PROCEVENT_ALARM_INTERFACE_A_FIELD)) !=
335       yajl_gen_status_ok)
336     goto err;
337
338   if (yajl_gen_string(g, (u_char *)process, strlen(process)) !=
339       yajl_gen_status_ok)
340     goto err;
341
342   // eventSeverity
343   if (yajl_gen_string(g, (u_char *)PROCEVENT_EVENT_SEVERITY_FIELD,
344                       strlen(PROCEVENT_EVENT_SEVERITY_FIELD)) !=
345       yajl_gen_status_ok)
346     goto err;
347
348   if (yajl_gen_string(
349           g, (u_char *)(state == 0 ? PROCEVENT_EVENT_SEVERITY_CRITICAL_VALUE
350                                    : PROCEVENT_EVENT_SEVERITY_NORMAL_VALUE),
351           strlen((state == 0 ? PROCEVENT_EVENT_SEVERITY_CRITICAL_VALUE
352                              : PROCEVENT_EVENT_SEVERITY_NORMAL_VALUE))) !=
353       yajl_gen_status_ok)
354     goto err;
355
356   // eventSourceType
357   if (yajl_gen_string(g, (u_char *)PROCEVENT_EVENT_SOURCE_TYPE_FIELD,
358                       strlen(PROCEVENT_EVENT_SOURCE_TYPE_FIELD)) !=
359       yajl_gen_status_ok)
360     goto err;
361
362   if (yajl_gen_string(g, (u_char *)PROCEVENT_EVENT_SOURCE_TYPE_VALUE,
363                       strlen(PROCEVENT_EVENT_SOURCE_TYPE_VALUE)) !=
364       yajl_gen_status_ok)
365     goto err;
366
367   // faultFieldsVersion
368   if (yajl_gen_string(g, (u_char *)PROCEVENT_FAULT_FIELDS_VERSION_FIELD,
369                       strlen(PROCEVENT_FAULT_FIELDS_VERSION_FIELD)) !=
370       yajl_gen_status_ok)
371     goto err;
372
373   if (yajl_gen_number(g, PROCEVENT_FAULT_FIELDS_VERSION_VALUE,
374                       strlen(PROCEVENT_FAULT_FIELDS_VERSION_VALUE)) !=
375       yajl_gen_status_ok)
376     goto err;
377
378   // specificProblem
379   if (yajl_gen_string(g, (u_char *)PROCEVENT_SPECIFIC_PROBLEM_FIELD,
380                       strlen(PROCEVENT_SPECIFIC_PROBLEM_FIELD)) !=
381       yajl_gen_status_ok)
382     goto err;
383
384   int specific_problem_len = 0;
385   specific_problem_len =
386       specific_problem_len + (sizeof(char) * sizeof(int) * 4);   // pid
387   specific_problem_len = specific_problem_len + strlen(process); // process name
388   specific_problem_len =
389       specific_problem_len + (state == 0 ? 4 : 2); // "down" or "up"
390   specific_problem_len =
391       specific_problem_len +
392       13; // "process", 3 spaces, 2 parentheses and null-terminator
393   memset(json_str, '\0', DATA_MAX_NAME_LEN);
394   snprintf(json_str, specific_problem_len, "process %s (%d) %s", process, pid,
395            (state == 0 ? PROCEVENT_SPECIFIC_PROBLEM_DOWN_VALUE
396                        : PROCEVENT_SPECIFIC_PROBLEM_UP_VALUE));
397
398   if (yajl_gen_string(g, (u_char *)json_str, strlen(json_str)) !=
399       yajl_gen_status_ok) {
400     goto err;
401   }
402
403   // vfStatus
404   if (yajl_gen_string(g, (u_char *)PROCEVENT_VF_STATUS_FIELD,
405                       strlen(PROCEVENT_VF_STATUS_FIELD)) != yajl_gen_status_ok)
406     goto err;
407
408   if (yajl_gen_string(
409           g, (u_char *)(state == 0 ? PROCEVENT_VF_STATUS_CRITICAL_VALUE
410                                    : PROCEVENT_VF_STATUS_NORMAL_VALUE),
411           strlen((state == 0 ? PROCEVENT_VF_STATUS_CRITICAL_VALUE
412                              : PROCEVENT_VF_STATUS_NORMAL_VALUE))) !=
413       yajl_gen_status_ok)
414     goto err;
415
416   if (yajl_gen_map_close(g) != yajl_gen_status_ok)
417     goto err;
418
419   // *** END fault fields ***
420
421   if (yajl_gen_map_close(g) != yajl_gen_status_ok)
422     goto err;
423
424   if (yajl_gen_get_buf(g, &buf2, &len) != yajl_gen_status_ok)
425     goto err;
426
427   *buf = malloc(strlen((char *)buf2) + 1);
428
429   if (*buf == NULL) {
430     char errbuf[1024];
431     ERROR("procevent plugin: malloc failed during gen_message_payload: %s",
432           sstrerror(errno, errbuf, sizeof(errbuf)));
433     goto err;
434   }
435
436   sstrncpy(*buf, (char *)buf2, strlen((char *)buf2) + 1);
437
438   yajl_gen_free(g);
439
440   return 0;
441
442 err:
443   yajl_gen_free(g);
444   ERROR("procevent plugin: gen_message_payload failed to generate JSON");
445   return -1;
446 }
447
448 // Does /proc/<pid>/comm contain a process name we are interested in?
449 static processlist_t *process_check(int pid) {
450   int len, is_match, retval;
451   char file[BUFSIZE];
452   FILE *fh;
453   char buffer[BUFSIZE];
454
455   len = snprintf(file, sizeof(file), PROCDIR "/%d/comm", pid);
456
457   if ((len < 0) || (len >= BUFSIZE)) {
458     WARNING("procevent process_check: process name too large");
459     return NULL;
460   }
461
462   if (NULL == (fh = fopen(file, "r"))) {
463     // No /proc/<pid>/comm for this pid, just ignore
464     DEBUG("procevent plugin: no comm file available for pid %d", pid);
465     return NULL;
466   }
467
468   retval = fscanf(fh, "%[^\n]", buffer);
469
470   if (retval < 0) {
471     WARNING("procevent process_check: unable to read comm file for pid %d",
472             pid);
473     fclose(fh);
474     return NULL;
475   }
476
477   // Now that we have the process name in the buffer, check if we are
478   // even interested in it
479   if (ignorelist_match(ignorelist, buffer) != 0) {
480     DEBUG("procevent process_check: ignoring process %s (%d)", buffer, pid);
481     fclose(fh);
482     return NULL;
483   }
484
485   if (fh != NULL) {
486     fclose(fh);
487     fh = NULL;
488   }
489
490   //
491   // Go through the processlist linked list and look for the process name
492   // in /proc/<pid>/comm.  If found:
493   // 1. If pl->pid is -1, then set pl->pid to <pid> (and return that object)
494   // 2. If pl->pid is not -1, then another <process name> process was already
495   //    found.  If <pid> == pl->pid, this is an old match, so do nothing.
496   //    If the <pid> is different, however, make a new processlist_t and
497   //    associate <pid> with it (with the same process name as the existing).
498   //
499
500   pthread_mutex_lock(&procevent_list_lock);
501
502   processlist_t *pl;
503   processlist_t *match = NULL;
504
505   for (pl = processlist_head; pl != NULL; pl = pl->next) {
506
507     is_match = (strcmp(buffer, pl->process) == 0 ? 1 : 0);
508
509     if (is_match == 1) {
510       DEBUG("procevent plugin: process %d name match for %s", pid, buffer);
511
512       if (pl->pid == pid) {
513         // this is a match, and we've already stored the exact pid/name combo
514         DEBUG("procevent plugin: found exact match with name %s, PID %ld for "
515               "incoming PID %d",
516               pl->process, pl->pid, pid);
517         match = pl;
518         break;
519       } else if (pl->pid == -1) {
520         // this is a match, and we've found a candidate processlist_t to store
521         // this new pid/name combo
522         DEBUG("procevent plugin: reusing pl object with PID %ld for incoming "
523               "PID %d",
524               pl->pid, pid);
525         pl->pid = pid;
526         match = pl;
527         break;
528       } else if (pl->pid != -1) {
529         // this is a match, but another instance of this process has already
530         // claimed this pid/name combo,
531         // so keep looking
532         DEBUG("procevent plugin: found pl object with matching name for "
533               "incoming PID %d, but object is in use by PID %ld",
534               pid, pl->pid);
535         match = pl;
536         continue;
537       }
538     }
539   }
540
541   if (match == NULL ||
542       (match != NULL && match->pid != -1 && match->pid != pid)) {
543     // if there wasn't an existing match, OR
544     // if there was a match but the associated processlist_t object already
545     // contained a pid/name combo,
546     // then make a new one and add it to the linked list
547
548     DEBUG(
549         "procevent plugin: allocating new processlist_t object for PID %d (%s)",
550         pid, buffer);
551
552     processlist_t *pl2;
553     char *process;
554
555     pl2 = malloc(sizeof(*pl2));
556     if (pl2 == NULL) {
557       char errbuf[1024];
558       ERROR("procevent plugin: malloc failed during process_check: %s",
559             sstrerror(errno, errbuf, sizeof(errbuf)));
560       pthread_mutex_unlock(&procevent_list_lock);
561       return NULL;
562     }
563
564     process = strdup(buffer);
565     if (process == NULL) {
566       char errbuf[1024];
567       sfree(pl2);
568       ERROR("procevent plugin: strdup failed during process_check: %s",
569             sstrerror(errno, errbuf, sizeof(errbuf)));
570       pthread_mutex_unlock(&procevent_list_lock);
571       return NULL;
572     }
573
574     pl2->process = process;
575     pl2->pid = pid;
576     pl2->next = processlist_head;
577     processlist_head = pl2;
578
579     match = pl2;
580   }
581
582   pthread_mutex_unlock(&procevent_list_lock);
583
584   return match;
585 }
586
587 // Does our map have this PID or name?
588 static processlist_t *process_map_check(int pid, char *process) {
589   processlist_t *pl;
590
591   pthread_mutex_lock(&procevent_list_lock);
592
593   for (pl = processlist_head; pl != NULL; pl = pl->next) {
594     int match_pid = 0;
595     int match_process = 0;
596     int match = 0;
597
598     if (pid > 0) {
599       if (pl->pid == pid)
600         match_pid = 1;
601     }
602
603     if (process != NULL) {
604       if (strcmp(pl->process, process) == 0)
605         match_process = 1;
606     }
607
608     if (pid > 0 && process == NULL && match_pid == 1)
609       match = 1;
610     else if (pid < 0 && process != NULL && match_process == 1)
611       match = 1;
612     else if (pid > 0 && process != NULL && match_pid == 1 && match_process == 1)
613       match = 1;
614
615     if (match == 1) {
616       pthread_mutex_unlock(&procevent_list_lock);
617       return pl;
618     }
619   }
620
621   pthread_mutex_unlock(&procevent_list_lock);
622
623   return NULL;
624 }
625
626 static int process_map_refresh(void) {
627   DIR *proc;
628
629   errno = 0;
630   proc = opendir(PROCDIR);
631   if (proc == NULL) {
632     char errbuf[1024];
633     ERROR("procevent plugin: fopen (%s): %s", PROCDIR,
634           sstrerror(errno, errbuf, sizeof(errbuf)));
635     return -1;
636   }
637
638   while (42) {
639     struct dirent *dent;
640     int len;
641     char file[BUFSIZE];
642
643     struct stat statbuf;
644
645     int status;
646
647     errno = 0;
648     dent = readdir(proc);
649     if (dent == NULL) {
650       char errbuf[4096];
651
652       if (errno == 0) /* end of directory */
653         break;
654
655       ERROR("procevent plugin: failed to read directory %s: %s", PROCDIR,
656             sstrerror(errno, errbuf, sizeof(errbuf)));
657       closedir(proc);
658       return -1;
659     }
660
661     if (dent->d_name[0] == '.')
662       continue;
663
664     len = snprintf(file, sizeof(file), PROCDIR "/%s", dent->d_name);
665     if ((len < 0) || (len >= BUFSIZE))
666       continue;
667
668     status = stat(file, &statbuf);
669     if (status != 0) {
670       char errbuf[4096];
671       WARNING("procevent plugin: stat (%s) failed: %s", file,
672               sstrerror(errno, errbuf, sizeof(errbuf)));
673       continue;
674     }
675
676     if (!S_ISDIR(statbuf.st_mode))
677       continue;
678
679     len = snprintf(file, sizeof(file), PROCDIR "/%s/comm", dent->d_name);
680     if ((len < 0) || (len >= BUFSIZE))
681       continue;
682
683     int not_number = 0;
684
685     for (int i = 0; i < strlen(dent->d_name); i++) {
686       if (!isdigit(dent->d_name[i])) {
687         not_number = 1;
688         break;
689       }
690     }
691
692     if (not_number != 0)
693       continue;
694
695     // Check if we need to store this pid/name combo in our processlist_t linked
696     // list
697     int this_pid = atoi(dent->d_name);
698     processlist_t *pl = process_check(this_pid);
699
700     if (pl != NULL)
701       DEBUG("procevent plugin: process map refreshed for PID %d and name %s",
702             this_pid, pl->process);
703   }
704
705   closedir(proc);
706
707   return 0;
708 }
709
710 static int nl_connect() {
711   int rc;
712   struct sockaddr_nl sa_nl;
713
714   nl_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
715   if (nl_sock == -1) {
716     ERROR("procevent plugin: socket open failed: %d", errno);
717     return -1;
718   }
719
720   sa_nl.nl_family = AF_NETLINK;
721   sa_nl.nl_groups = CN_IDX_PROC;
722   sa_nl.nl_pid = getpid();
723
724   rc = bind(nl_sock, (struct sockaddr *)&sa_nl, sizeof(sa_nl));
725   if (rc == -1) {
726     ERROR("procevent plugin: socket bind failed: %d", errno);
727     close(nl_sock);
728     return -1;
729   }
730
731   return 0;
732 }
733
734 static int set_proc_ev_listen(bool enable) {
735   int rc;
736   struct __attribute__((aligned(NLMSG_ALIGNTO))) {
737     struct nlmsghdr nl_hdr;
738     struct __attribute__((__packed__)) {
739       struct cn_msg cn_msg;
740       enum proc_cn_mcast_op cn_mcast;
741     };
742   } nlcn_msg;
743
744   memset(&nlcn_msg, 0, sizeof(nlcn_msg));
745   nlcn_msg.nl_hdr.nlmsg_len = sizeof(nlcn_msg);
746   nlcn_msg.nl_hdr.nlmsg_pid = getpid();
747   nlcn_msg.nl_hdr.nlmsg_type = NLMSG_DONE;
748
749   nlcn_msg.cn_msg.id.idx = CN_IDX_PROC;
750   nlcn_msg.cn_msg.id.val = CN_VAL_PROC;
751   nlcn_msg.cn_msg.len = sizeof(enum proc_cn_mcast_op);
752
753   nlcn_msg.cn_mcast = enable ? PROC_CN_MCAST_LISTEN : PROC_CN_MCAST_IGNORE;
754
755   rc = send(nl_sock, &nlcn_msg, sizeof(nlcn_msg), 0);
756   if (rc == -1) {
757     ERROR("procevent plugin: subscribing to netlink process events failed: %d",
758           errno);
759     return -1;
760   }
761
762   return 0;
763 }
764
765 static int read_event() {
766   int status;
767   int ret = 0;
768   int proc_id = -1;
769   int proc_status = -1;
770   int proc_extra = -1;
771   struct __attribute__((aligned(NLMSG_ALIGNTO))) {
772     struct nlmsghdr nl_hdr;
773     struct __attribute__((__packed__)) {
774       struct cn_msg cn_msg;
775       struct proc_event proc_ev;
776     };
777   } nlcn_msg;
778
779   if (nl_sock == -1)
780     return ret;
781
782   while (42) {
783
784     pthread_mutex_lock(&procevent_lock);
785
786     if (procevent_thread_loop <= 0)
787       return ret;
788
789     pthread_mutex_unlock(&procevent_lock);
790
791     status = recv(nl_sock, &nlcn_msg, sizeof(nlcn_msg), 0);
792
793     if (status == 0) {
794       return 0;
795     } else if (status == -1) {
796       if (errno != EINTR) {
797         ERROR("procevent plugin: socket receive error: %d", errno);
798         return -1;
799       }
800     }
801
802     switch (nlcn_msg.proc_ev.what) {
803     case PROC_EVENT_NONE:
804     case PROC_EVENT_FORK:
805     case PROC_EVENT_UID:
806     case PROC_EVENT_GID:
807       // Not of interest in current version
808       break;
809     case PROC_EVENT_EXEC:
810       proc_status = PROCEVENT_STARTED;
811       proc_id = nlcn_msg.proc_ev.event_data.exec.process_pid;
812       break;
813     case PROC_EVENT_EXIT:
814       proc_id = nlcn_msg.proc_ev.event_data.exit.process_pid;
815       proc_status = PROCEVENT_EXITED;
816       proc_extra = nlcn_msg.proc_ev.event_data.exit.exit_code;
817       break;
818     default:
819       break;
820     }
821
822     // If we're interested in this process status event, place the event
823     // in the ring buffer for consumption by the main polling thread.
824
825     if (proc_status != -1) {
826       pthread_mutex_lock(&procevent_lock);
827
828       int next = ring.head + 1;
829       if (next >= ring.maxLen)
830         next = 0;
831
832       if (next == ring.tail) {
833         WARNING("procevent plugin: ring buffer full");
834       } else {
835         DEBUG("procevent plugin: Process %d status is now %s at %llu", proc_id,
836               (proc_status == PROCEVENT_EXITED ? "EXITED" : "STARTED"),
837               (long long unsigned int)CDTIME_T_TO_US(cdtime()));
838
839         if (proc_status == PROCEVENT_EXITED) {
840           ring.buffer[ring.head][0] = proc_id;
841           ring.buffer[ring.head][1] = proc_status;
842           ring.buffer[ring.head][2] = proc_extra;
843           ring.buffer[ring.head][3] =
844               (long long unsigned int)CDTIME_T_TO_US(cdtime());
845         } else {
846           ring.buffer[ring.head][0] = proc_id;
847           ring.buffer[ring.head][1] = proc_status;
848           ring.buffer[ring.head][2] = 0;
849           ring.buffer[ring.head][3] =
850               (long long unsigned int)CDTIME_T_TO_US(cdtime());
851         }
852
853         ring.head = next;
854       }
855
856       pthread_mutex_unlock(&procevent_lock);
857     }
858   }
859
860   return ret;
861 }
862
863 static void *procevent_thread(void *arg) /* {{{ */
864 {
865   pthread_mutex_lock(&procevent_lock);
866
867   while (procevent_thread_loop > 0) {
868     int status;
869
870     pthread_mutex_unlock(&procevent_lock);
871
872     usleep(1000);
873
874     status = read_event();
875
876     pthread_mutex_lock(&procevent_lock);
877
878     if (status < 0) {
879       procevent_thread_error = 1;
880       break;
881     }
882
883     if (procevent_thread_loop <= 0)
884       break;
885   } /* while (procevent_thread_loop > 0) */
886
887   pthread_mutex_unlock(&procevent_lock);
888
889   return ((void *)0);
890 } /* }}} void *procevent_thread */
891
892 static int start_thread(void) /* {{{ */
893 {
894   int status;
895
896   pthread_mutex_lock(&procevent_lock);
897
898   if (procevent_thread_loop != 0) {
899     pthread_mutex_unlock(&procevent_lock);
900     return (0);
901   }
902
903   if (nl_sock == -1) {
904     status = nl_connect();
905
906     if (status != 0)
907       return status;
908
909     status = set_proc_ev_listen(true);
910     if (status == -1)
911       return status;
912   }
913
914   DEBUG("procevent plugin: socket created and bound");
915
916   procevent_thread_loop = 1;
917   procevent_thread_error = 0;
918
919   status = plugin_thread_create(&procevent_thread_id, /* attr = */ NULL,
920                                 procevent_thread,
921                                 /* arg = */ (void *)0, "procevent");
922   if (status != 0) {
923     procevent_thread_loop = 0;
924     ERROR("procevent plugin: Starting thread failed.");
925     pthread_mutex_unlock(&procevent_lock);
926     return (-1);
927   }
928
929   pthread_mutex_unlock(&procevent_lock);
930   return (0);
931 } /* }}} int start_thread */
932
933 static int stop_thread(int shutdown) /* {{{ */
934 {
935   int status;
936
937   if (nl_sock != -1) {
938     status = close(nl_sock);
939     if (status != 0) {
940       ERROR("procevent plugin: failed to close socket %d: %d (%s)", nl_sock,
941             status, strerror(errno));
942       return (-1);
943     } else
944       nl_sock = -1;
945   }
946
947   pthread_mutex_lock(&procevent_lock);
948
949   if (procevent_thread_loop == 0) {
950     pthread_mutex_unlock(&procevent_lock);
951     return (-1);
952   }
953
954   procevent_thread_loop = 0;
955   pthread_cond_broadcast(&procevent_cond);
956   pthread_mutex_unlock(&procevent_lock);
957
958   if (shutdown == 1) {
959     // Calling pthread_cancel here in
960     // the case of a shutdown just assures that the thread is
961     // gone and that the process has been fully terminated.
962
963     DEBUG("procevent plugin: Canceling thread for process shutdown");
964
965     status = pthread_cancel(procevent_thread_id);
966
967     if (status != 0) {
968       ERROR("procevent plugin: Unable to cancel thread: %d", status);
969       status = -1;
970     }
971   } else {
972     status = pthread_join(procevent_thread_id, /* return = */ NULL);
973     if (status != 0) {
974       ERROR("procevent plugin: Stopping thread failed.");
975       status = -1;
976     }
977   }
978
979   pthread_mutex_lock(&procevent_lock);
980   memset(&procevent_thread_id, 0, sizeof(procevent_thread_id));
981   procevent_thread_error = 0;
982   pthread_mutex_unlock(&procevent_lock);
983
984   DEBUG("procevent plugin: Finished requesting stop of thread");
985
986   return (status);
987 } /* }}} int stop_thread */
988
989 static int procevent_init(void) /* {{{ */
990 {
991   int status;
992
993   ring.head = 0;
994   ring.tail = 0;
995   ring.maxLen = buffer_length;
996   ring.buffer = (long long unsigned int **)malloc(
997       buffer_length * sizeof(long long unsigned int *));
998
999   for (int i = 0; i < buffer_length; i++) {
1000     ring.buffer[i] = (long long unsigned int *)malloc(
1001         PROCEVENT_FIELDS * sizeof(long long unsigned int));
1002   }
1003
1004   status = process_map_refresh();
1005
1006   if (status == -1) {
1007     ERROR("procevent plugin: Initial process mapping failed.");
1008     return (-1);
1009   }
1010
1011   if (ignorelist == NULL) {
1012     NOTICE("procevent plugin: No processes have been configured.");
1013     return (-1);
1014   }
1015
1016   return (start_thread());
1017 } /* }}} int procevent_init */
1018
1019 static int procevent_config(const char *key, const char *value) /* {{{ */
1020 {
1021   int status;
1022
1023   if (ignorelist == NULL)
1024     ignorelist = ignorelist_create(/* invert = */ 1);
1025
1026   if (strcasecmp(key, "BufferLength") == 0) {
1027     buffer_length = atoi(value);
1028   } else if (strcasecmp(key, "Process") == 0) {
1029     ignorelist_add(ignorelist, value);
1030   } else if (strcasecmp(key, "RegexProcess") == 0) {
1031 #if HAVE_REGEX_H
1032     status = ignorelist_add(ignorelist, value);
1033
1034     if (status != 0) {
1035       ERROR("procevent plugin: invalid regular expression: %s", value);
1036       return (1);
1037     }
1038 #else
1039     WARNING("procevent plugin: The plugin has been compiled without support "
1040             "for the \"RegexProcess\" option.");
1041 #endif
1042   } else {
1043     return (-1);
1044   }
1045
1046   return (0);
1047 } /* }}} int procevent_config */
1048
1049 static void procevent_dispatch_notification(int pid, const char *type, /* {{{ */
1050                                             gauge_t value, char *process,
1051                                             long long unsigned int timestamp) {
1052   char *buf = NULL;
1053   notification_t n = {NOTIF_FAILURE, cdtime(), "", "", "procevent", "", "", "",
1054                       NULL};
1055
1056   if (value == 1)
1057     n.severity = NOTIF_OKAY;
1058
1059   sstrncpy(n.host, hostname_g, sizeof(n.host));
1060   sstrncpy(n.plugin_instance, process, sizeof(n.plugin_instance));
1061   sstrncpy(n.type, "gauge", sizeof(n.type));
1062   sstrncpy(n.type_instance, "process_status", sizeof(n.type_instance));
1063
1064   gen_message_payload(value, pid, process, timestamp, &buf);
1065
1066   notification_meta_t *m = calloc(1, sizeof(*m));
1067
1068   if (m == NULL) {
1069     char errbuf[1024];
1070     sfree(buf);
1071     ERROR("procevent plugin: unable to allocate metadata: %s",
1072           sstrerror(errno, errbuf, sizeof(errbuf)));
1073     return;
1074   }
1075
1076   sstrncpy(m->name, "ves", sizeof(m->name));
1077   m->nm_value.nm_string = sstrdup(buf);
1078   m->type = NM_TYPE_STRING;
1079   n.meta = m;
1080
1081   DEBUG("procevent plugin: notification message: %s",
1082         n.meta->nm_value.nm_string);
1083
1084   DEBUG("procevent plugin: dispatching state %d for PID %d (%s)", (int)value,
1085         pid, process);
1086
1087   plugin_dispatch_notification(&n);
1088   plugin_notification_meta_free(n.meta);
1089
1090   // malloc'd in gen_message_payload
1091   if (buf != NULL)
1092     sfree(buf);
1093 }
1094
1095 static int procevent_read(void) /* {{{ */
1096 {
1097   if (procevent_thread_error != 0) {
1098     ERROR(
1099         "procevent plugin: The interface thread had a problem. Restarting it.");
1100
1101     stop_thread(0);
1102
1103     start_thread();
1104
1105     return (-1);
1106   } /* if (procevent_thread_error != 0) */
1107
1108   pthread_mutex_lock(&procevent_lock);
1109
1110   while (ring.head != ring.tail) {
1111     int next = ring.tail + 1;
1112
1113     if (next >= ring.maxLen)
1114       next = 0;
1115
1116     if (ring.buffer[ring.tail][1] == PROCEVENT_EXITED) {
1117       processlist_t *pl = process_map_check(ring.buffer[ring.tail][0], NULL);
1118
1119       if (pl != NULL) {
1120         // This process is of interest to us, so publish its EXITED status
1121         procevent_dispatch_notification(ring.buffer[ring.tail][0], "gauge",
1122                                         ring.buffer[ring.tail][1], pl->process,
1123                                         ring.buffer[ring.tail][3]);
1124         DEBUG("procevent plugin: PID %d (%s) EXITED, removing PID from process "
1125               "list",
1126               pl->pid, pl->process);
1127         pl->pid = -1;
1128         pl->last_status = -1;
1129       }
1130     } else if (ring.buffer[ring.tail][1] == PROCEVENT_STARTED) {
1131       // a new process has started, so check if we should monitor it
1132       processlist_t *pl = process_check(ring.buffer[ring.tail][0]);
1133
1134       // If we had already seen this process name and pid combo before,
1135       // and the last message was a "process started" message, don't send
1136       // the notfication again
1137
1138       if (pl != NULL && pl->last_status != PROCEVENT_STARTED) {
1139         // This process is of interest to us, so publish its STARTED status
1140         procevent_dispatch_notification(ring.buffer[ring.tail][0], "gauge",
1141                                         ring.buffer[ring.tail][1], pl->process,
1142                                         ring.buffer[ring.tail][3]);
1143
1144         pl->last_status = PROCEVENT_STARTED;
1145
1146         DEBUG("procevent plugin: PID %ld (%s) STARTED, adding PID to process "
1147               "list",
1148               pl->pid, pl->process);
1149       }
1150     }
1151
1152     ring.tail = next;
1153   }
1154
1155   pthread_mutex_unlock(&procevent_lock);
1156
1157   return (0);
1158 } /* }}} int procevent_read */
1159
1160 static int procevent_shutdown(void) /* {{{ */
1161 {
1162   processlist_t *pl;
1163
1164   DEBUG("procevent plugin: Shutting down thread.");
1165
1166   if (stop_thread(1) < 0)
1167     return (-1);
1168
1169   for (int i = 0; i < buffer_length; i++) {
1170     free(ring.buffer[i]);
1171   }
1172
1173   free(ring.buffer);
1174
1175   pl = processlist_head;
1176   while (pl != NULL) {
1177     processlist_t *pl_next;
1178
1179     pl_next = pl->next;
1180
1181     sfree(pl->process);
1182     sfree(pl);
1183
1184     pl = pl_next;
1185   }
1186
1187   return (0);
1188 } /* }}} int procevent_shutdown */
1189
1190 void module_register(void) {
1191   plugin_register_config("procevent", procevent_config, config_keys,
1192                          config_keys_num);
1193   plugin_register_init("procevent", procevent_init);
1194   plugin_register_read("procevent", procevent_read);
1195   plugin_register_shutdown("procevent", procevent_shutdown);
1196 } /* void module_register */