Styling + optimizations
[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 3 // pid, status, timestamp
63 #define BUFSIZE 512
64 #define PROCDIR "/proc"
65 #define RBUF_PROC_ID_INDEX 0
66 #define RBUF_PROC_STATUS_INDEX 1
67 #define RBUF_TIME_INDEX 2
68
69 #define PROCEVENT_DOMAIN_FIELD "domain"
70 #define PROCEVENT_DOMAIN_VALUE "fault"
71 #define PROCEVENT_EVENT_ID_FIELD "eventId"
72 #define PROCEVENT_EVENT_NAME_FIELD "eventName"
73 #define PROCEVENT_EVENT_NAME_DOWN_VALUE "down"
74 #define PROCEVENT_EVENT_NAME_UP_VALUE "up"
75 #define PROCEVENT_LAST_EPOCH_MICROSEC_FIELD "lastEpochMicrosec"
76 #define PROCEVENT_PRIORITY_FIELD "priority"
77 #define PROCEVENT_PRIORITY_VALUE "high"
78 #define PROCEVENT_REPORTING_ENTITY_NAME_FIELD "reportingEntityName"
79 #define PROCEVENT_REPORTING_ENTITY_NAME_VALUE "collectd procevent plugin"
80 #define PROCEVENT_SEQUENCE_FIELD "sequence"
81 #define PROCEVENT_SEQUENCE_VALUE "0"
82 #define PROCEVENT_SOURCE_NAME_FIELD "sourceName"
83 #define PROCEVENT_START_EPOCH_MICROSEC_FIELD "startEpochMicrosec"
84 #define PROCEVENT_VERSION_FIELD "version"
85 #define PROCEVENT_VERSION_VALUE "1.0"
86
87 #define PROCEVENT_ALARM_CONDITION_FIELD "alarmCondition"
88 #define PROCEVENT_ALARM_INTERFACE_A_FIELD "alarmInterfaceA"
89 #define PROCEVENT_EVENT_SEVERITY_FIELD "eventSeverity"
90 #define PROCEVENT_EVENT_SEVERITY_CRITICAL_VALUE "CRITICAL"
91 #define PROCEVENT_EVENT_SEVERITY_NORMAL_VALUE "NORMAL"
92 #define PROCEVENT_EVENT_SOURCE_TYPE_FIELD "eventSourceType"
93 #define PROCEVENT_EVENT_SOURCE_TYPE_VALUE "process"
94 #define PROCEVENT_FAULT_FIELDS_FIELD "faultFields"
95 #define PROCEVENT_FAULT_FIELDS_VERSION_FIELD "faultFieldsVersion"
96 #define PROCEVENT_FAULT_FIELDS_VERSION_VALUE "1.0"
97 #define PROCEVENT_SPECIFIC_PROBLEM_FIELD "specificProblem"
98 #define PROCEVENT_SPECIFIC_PROBLEM_DOWN_VALUE "down"
99 #define PROCEVENT_SPECIFIC_PROBLEM_UP_VALUE "up"
100 #define PROCEVENT_VF_STATUS_FIELD "vfStatus"
101 #define PROCEVENT_VF_STATUS_CRITICAL_VALUE "Ready to terminate"
102 #define PROCEVENT_VF_STATUS_NORMAL_VALUE "Active"
103
104 /*
105  * Private data types
106  */
107
108 typedef struct {
109   int head;
110   int tail;
111   int maxLen;
112   cdtime_t **buffer;
113 } circbuf_t;
114
115 struct processlist_s {
116   char *process;
117
118   long pid;
119   int32_t last_status;
120
121   struct processlist_s *next;
122 };
123 typedef struct processlist_s processlist_t;
124
125 /*
126  * Private variables
127  */
128 static ignorelist_t *ignorelist = NULL;
129
130 static int procevent_netlink_thread_loop = 0;
131 static int procevent_netlink_thread_error = 0;
132 static pthread_t procevent_netlink_thread_id;
133 static int procevent_dequeue_thread_loop = 0;
134 static pthread_t procevent_dequeue_thread_id;
135 static pthread_mutex_t procevent_thread_lock = PTHREAD_MUTEX_INITIALIZER;
136 static pthread_mutex_t procevent_data_lock = PTHREAD_MUTEX_INITIALIZER;
137 static pthread_cond_t procevent_cond = PTHREAD_COND_INITIALIZER;
138 static int nl_sock = -1;
139 static int buffer_length;
140 static circbuf_t ring;
141 static processlist_t *processlist_head = NULL;
142 static int event_id = 0;
143
144 static const char *config_keys[] = {"BufferLength", "Process", "ProcessRegex"};
145 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
146
147 /*
148  * Private functions
149  */
150
151 static int gen_message_payload(int state, long pid, char *process,
152                                cdtime_t timestamp, char **buf) {
153   const unsigned char *buf2;
154   yajl_gen g;
155   char json_str[DATA_MAX_NAME_LEN];
156
157 #if !defined(HAVE_YAJL_V2)
158   yajl_gen_config conf = {0};
159 #endif
160
161 #if HAVE_YAJL_V2
162   size_t len;
163   g = yajl_gen_alloc(NULL);
164   yajl_gen_config(g, yajl_gen_beautify, 0);
165 #else
166   unsigned int len;
167   g = yajl_gen_alloc(&conf, NULL);
168 #endif
169
170   yajl_gen_clear(g);
171
172   // *** BEGIN common event header ***
173
174   if (yajl_gen_map_open(g) != yajl_gen_status_ok)
175     goto err;
176
177   // domain
178   if (yajl_gen_string(g, (u_char *)PROCEVENT_DOMAIN_FIELD,
179                       strlen(PROCEVENT_DOMAIN_FIELD)) != yajl_gen_status_ok)
180     goto err;
181
182   if (yajl_gen_string(g, (u_char *)PROCEVENT_DOMAIN_VALUE,
183                       strlen(PROCEVENT_DOMAIN_VALUE)) != yajl_gen_status_ok)
184     goto err;
185
186   // eventId
187   if (yajl_gen_string(g, (u_char *)PROCEVENT_EVENT_ID_FIELD,
188                       strlen(PROCEVENT_EVENT_ID_FIELD)) != yajl_gen_status_ok)
189     goto err;
190
191   event_id = event_id + 1;
192   if (snprintf(json_str, sizeof(json_str), "%d", event_id) < 0) {
193     goto err;
194   }
195
196   if (yajl_gen_number(g, json_str, strlen(json_str)) != yajl_gen_status_ok) {
197     goto err;
198   }
199
200   // eventName
201   if (yajl_gen_string(g, (u_char *)PROCEVENT_EVENT_NAME_FIELD,
202                       strlen(PROCEVENT_EVENT_NAME_FIELD)) != yajl_gen_status_ok)
203     goto err;
204
205   if (snprintf(json_str, sizeof(json_str), "process %s (%ld) %s", process, pid,
206                (state == 0 ? PROCEVENT_EVENT_NAME_DOWN_VALUE
207                            : PROCEVENT_EVENT_NAME_UP_VALUE)) < 0) {
208     goto err;
209   }
210
211   if (yajl_gen_string(g, (u_char *)json_str, strlen(json_str)) !=
212       yajl_gen_status_ok) {
213     goto err;
214   }
215
216   // lastEpochMicrosec
217   if (yajl_gen_string(g, (u_char *)PROCEVENT_LAST_EPOCH_MICROSEC_FIELD,
218                       strlen(PROCEVENT_LAST_EPOCH_MICROSEC_FIELD)) !=
219       yajl_gen_status_ok)
220     goto err;
221
222   if (snprintf(json_str, sizeof(json_str), "%" PRIu64,
223                CDTIME_T_TO_US(cdtime())) < 0) {
224     goto err;
225   }
226
227   if (yajl_gen_number(g, json_str, strlen(json_str)) != yajl_gen_status_ok) {
228     goto err;
229   }
230
231   // priority
232   if (yajl_gen_string(g, (u_char *)PROCEVENT_PRIORITY_FIELD,
233                       strlen(PROCEVENT_PRIORITY_FIELD)) != yajl_gen_status_ok)
234     goto err;
235
236   if (yajl_gen_string(g, (u_char *)PROCEVENT_PRIORITY_VALUE,
237                       strlen(PROCEVENT_PRIORITY_VALUE)) != yajl_gen_status_ok)
238     goto err;
239
240   // reportingEntityName
241   if (yajl_gen_string(g, (u_char *)PROCEVENT_REPORTING_ENTITY_NAME_FIELD,
242                       strlen(PROCEVENT_REPORTING_ENTITY_NAME_FIELD)) !=
243       yajl_gen_status_ok)
244     goto err;
245
246   if (yajl_gen_string(g, (u_char *)PROCEVENT_REPORTING_ENTITY_NAME_VALUE,
247                       strlen(PROCEVENT_REPORTING_ENTITY_NAME_VALUE)) !=
248       yajl_gen_status_ok)
249     goto err;
250
251   // sequence
252   if (yajl_gen_string(g, (u_char *)PROCEVENT_SEQUENCE_FIELD,
253                       strlen(PROCEVENT_SEQUENCE_FIELD)) != yajl_gen_status_ok)
254     goto err;
255
256   if (yajl_gen_number(g, PROCEVENT_SEQUENCE_VALUE,
257                       strlen(PROCEVENT_SEQUENCE_VALUE)) != yajl_gen_status_ok)
258     goto err;
259
260   // sourceName
261   if (yajl_gen_string(g, (u_char *)PROCEVENT_SOURCE_NAME_FIELD,
262                       strlen(PROCEVENT_SOURCE_NAME_FIELD)) !=
263       yajl_gen_status_ok)
264     goto err;
265
266   if (yajl_gen_string(g, (u_char *)process, strlen(process)) !=
267       yajl_gen_status_ok)
268     goto err;
269
270   // startEpochMicrosec
271   if (yajl_gen_string(g, (u_char *)PROCEVENT_START_EPOCH_MICROSEC_FIELD,
272                       strlen(PROCEVENT_START_EPOCH_MICROSEC_FIELD)) !=
273       yajl_gen_status_ok)
274     goto err;
275
276   if (snprintf(json_str, sizeof(json_str), "%" PRIu64,
277                CDTIME_T_TO_US(timestamp)) < 0) {
278     goto err;
279   }
280
281   if (yajl_gen_number(g, json_str, strlen(json_str)) != yajl_gen_status_ok) {
282     goto err;
283   }
284
285   // version
286   if (yajl_gen_string(g, (u_char *)PROCEVENT_VERSION_FIELD,
287                       strlen(PROCEVENT_VERSION_FIELD)) != yajl_gen_status_ok)
288     goto err;
289
290   if (yajl_gen_number(g, PROCEVENT_VERSION_VALUE,
291                       strlen(PROCEVENT_VERSION_VALUE)) != yajl_gen_status_ok)
292     goto err;
293
294   // *** END common event header ***
295
296   // *** BEGIN fault fields ***
297
298   if (yajl_gen_string(g, (u_char *)PROCEVENT_FAULT_FIELDS_FIELD,
299                       strlen(PROCEVENT_FAULT_FIELDS_FIELD)) !=
300       yajl_gen_status_ok)
301     goto err;
302
303   if (yajl_gen_map_open(g) != yajl_gen_status_ok)
304     goto err;
305
306   // alarmCondition
307   if (yajl_gen_string(g, (u_char *)PROCEVENT_ALARM_CONDITION_FIELD,
308                       strlen(PROCEVENT_ALARM_CONDITION_FIELD)) !=
309       yajl_gen_status_ok)
310     goto err;
311
312   if (snprintf(json_str, sizeof(json_str), "process %s (%ld) state change",
313                process, pid) < 0) {
314     goto err;
315   }
316
317   if (yajl_gen_string(g, (u_char *)json_str, strlen(json_str)) !=
318       yajl_gen_status_ok) {
319     goto err;
320   }
321
322   // alarmInterfaceA
323   if (yajl_gen_string(g, (u_char *)PROCEVENT_ALARM_INTERFACE_A_FIELD,
324                       strlen(PROCEVENT_ALARM_INTERFACE_A_FIELD)) !=
325       yajl_gen_status_ok)
326     goto err;
327
328   if (yajl_gen_string(g, (u_char *)process, strlen(process)) !=
329       yajl_gen_status_ok)
330     goto err;
331
332   // eventSeverity
333   if (yajl_gen_string(g, (u_char *)PROCEVENT_EVENT_SEVERITY_FIELD,
334                       strlen(PROCEVENT_EVENT_SEVERITY_FIELD)) !=
335       yajl_gen_status_ok)
336     goto err;
337
338   if (yajl_gen_string(
339           g, (u_char *)(state == 0 ? PROCEVENT_EVENT_SEVERITY_CRITICAL_VALUE
340                                    : PROCEVENT_EVENT_SEVERITY_NORMAL_VALUE),
341           strlen((state == 0 ? PROCEVENT_EVENT_SEVERITY_CRITICAL_VALUE
342                              : PROCEVENT_EVENT_SEVERITY_NORMAL_VALUE))) !=
343       yajl_gen_status_ok)
344     goto err;
345
346   // eventSourceType
347   if (yajl_gen_string(g, (u_char *)PROCEVENT_EVENT_SOURCE_TYPE_FIELD,
348                       strlen(PROCEVENT_EVENT_SOURCE_TYPE_FIELD)) !=
349       yajl_gen_status_ok)
350     goto err;
351
352   if (yajl_gen_string(g, (u_char *)PROCEVENT_EVENT_SOURCE_TYPE_VALUE,
353                       strlen(PROCEVENT_EVENT_SOURCE_TYPE_VALUE)) !=
354       yajl_gen_status_ok)
355     goto err;
356
357   // faultFieldsVersion
358   if (yajl_gen_string(g, (u_char *)PROCEVENT_FAULT_FIELDS_VERSION_FIELD,
359                       strlen(PROCEVENT_FAULT_FIELDS_VERSION_FIELD)) !=
360       yajl_gen_status_ok)
361     goto err;
362
363   if (yajl_gen_number(g, PROCEVENT_FAULT_FIELDS_VERSION_VALUE,
364                       strlen(PROCEVENT_FAULT_FIELDS_VERSION_VALUE)) !=
365       yajl_gen_status_ok)
366     goto err;
367
368   // specificProblem
369   if (yajl_gen_string(g, (u_char *)PROCEVENT_SPECIFIC_PROBLEM_FIELD,
370                       strlen(PROCEVENT_SPECIFIC_PROBLEM_FIELD)) !=
371       yajl_gen_status_ok)
372     goto err;
373
374   if (snprintf(json_str, sizeof(json_str), "process %s (%ld) %s", process, pid,
375                (state == 0 ? PROCEVENT_SPECIFIC_PROBLEM_DOWN_VALUE
376                            : PROCEVENT_SPECIFIC_PROBLEM_UP_VALUE)) < 0) {
377     goto err;
378   }
379
380   if (yajl_gen_string(g, (u_char *)json_str, strlen(json_str)) !=
381       yajl_gen_status_ok) {
382     goto err;
383   }
384
385   // vfStatus
386   if (yajl_gen_string(g, (u_char *)PROCEVENT_VF_STATUS_FIELD,
387                       strlen(PROCEVENT_VF_STATUS_FIELD)) != yajl_gen_status_ok)
388     goto err;
389
390   if (yajl_gen_string(
391           g, (u_char *)(state == 0 ? PROCEVENT_VF_STATUS_CRITICAL_VALUE
392                                    : PROCEVENT_VF_STATUS_NORMAL_VALUE),
393           strlen((state == 0 ? PROCEVENT_VF_STATUS_CRITICAL_VALUE
394                              : PROCEVENT_VF_STATUS_NORMAL_VALUE))) !=
395       yajl_gen_status_ok)
396     goto err;
397
398   // *** END fault fields ***
399
400   // close fault and header fields
401   if (yajl_gen_map_close(g) != yajl_gen_status_ok ||
402       yajl_gen_map_close(g) != yajl_gen_status_ok)
403     goto err;
404
405   if (yajl_gen_get_buf(g, &buf2, &len) != yajl_gen_status_ok)
406     goto err;
407
408   *buf = strdup((char *)buf2);
409
410   if (*buf == NULL) {
411     ERROR("procevent plugin: strdup failed during gen_message_payload: %s",
412           STRERRNO);
413     goto err;
414   }
415
416   yajl_gen_free(g);
417
418   return 0;
419
420 err:
421   yajl_gen_free(g);
422   ERROR("procevent plugin: gen_message_payload failed to generate JSON");
423   return -1;
424 }
425
426 // Does /proc/<pid>/comm contain a process name we are interested in?
427 // NOTE: Caller MUST hold procevent_data_lock when calling this function
428 static processlist_t *process_check(long pid) {
429   char file[BUFSIZE];
430
431   int len = snprintf(file, sizeof(file), PROCDIR "/%ld/comm", pid);
432
433   if ((len < 0) || (len >= BUFSIZE)) {
434     WARNING("procevent process_check: process name too large");
435     return NULL;
436   }
437
438   FILE *fh;
439
440   if (NULL == (fh = fopen(file, "r"))) {
441     // No /proc/<pid>/comm for this pid, just ignore
442     DEBUG("procevent plugin: no comm file available for pid %ld", pid);
443     return NULL;
444   }
445
446   char buffer[BUFSIZE];
447   int retval = fscanf(fh, "%[^\n]", buffer);
448
449   if (retval < 0) {
450     WARNING("procevent process_check: unable to read comm file for pid %ld",
451             pid);
452     fclose(fh);
453     return NULL;
454   }
455
456   // Now that we have the process name in the buffer, check if we are
457   // even interested in it
458   if (ignorelist_match(ignorelist, buffer) != 0) {
459     DEBUG("procevent process_check: ignoring process %s (%ld)", buffer, pid);
460     fclose(fh);
461     return NULL;
462   }
463
464   if (fh != NULL) {
465     fclose(fh);
466     fh = NULL;
467   }
468
469   //
470   // Go through the processlist linked list and look for the process name
471   // in /proc/<pid>/comm.  If found:
472   // 1. If pl->pid is -1, then set pl->pid to <pid> (and return that object)
473   // 2. If pl->pid is not -1, then another <process name> process was already
474   //    found.  If <pid> == pl->pid, this is an old match, so do nothing.
475   //    If the <pid> is different, however, make a new processlist_t and
476   //    associate <pid> with it (with the same process name as the existing).
477   //
478
479   processlist_t *match = NULL;
480
481   for (processlist_t *pl = processlist_head; pl != NULL; pl = pl->next) {
482
483     int is_match = (strcmp(buffer, pl->process) == 0 ? 1 : 0);
484
485     if (is_match == 1) {
486       DEBUG("procevent plugin: process %ld name match for %s", pid, buffer);
487
488       if (pl->pid == pid) {
489         // this is a match, and we've already stored the exact pid/name combo
490         DEBUG("procevent plugin: found exact match with name %s, PID %ld for "
491               "incoming PID %ld",
492               pl->process, pl->pid, pid);
493         match = pl;
494         break;
495       } else if (pl->pid == -1) {
496         // this is a match, and we've found a candidate processlist_t to store
497         // this new pid/name combo
498         DEBUG("procevent plugin: reusing pl object with PID %ld for incoming "
499               "PID %ld",
500               pl->pid, pid);
501         pl->pid = pid;
502         match = pl;
503         break;
504       } else if (pl->pid != -1) {
505         // this is a match, but another instance of this process has already
506         // claimed this pid/name combo,
507         // so keep looking
508         DEBUG("procevent plugin: found pl object with matching name for "
509               "incoming PID %ld, but object is in use by PID %ld",
510               pid, pl->pid);
511         match = pl;
512         continue;
513       }
514     }
515   }
516
517   if (match == NULL ||
518       (match != NULL && match->pid != -1 && match->pid != pid)) {
519     // if there wasn't an existing match, OR
520     // if there was a match but the associated processlist_t object already
521     // contained a pid/name combo,
522     // then make a new one and add it to the linked list
523
524     DEBUG("procevent plugin: allocating new processlist_t object for PID %ld "
525           "(%s)",
526           pid, buffer);
527
528     processlist_t *pl2 = calloc(1, sizeof(*pl2));
529     if (pl2 == NULL) {
530       ERROR("procevent plugin: calloc failed during process_check: %s",
531             STRERRNO);
532       return NULL;
533     }
534
535     char *process = strdup(buffer);
536     if (process == NULL) {
537       sfree(pl2);
538       ERROR("procevent plugin: strdup failed during process_check: %s",
539             STRERRNO);
540       return NULL;
541     }
542
543     pl2->process = process;
544     pl2->pid = pid;
545     pl2->next = processlist_head;
546     processlist_head = pl2;
547
548     match = pl2;
549   }
550
551   return match;
552 }
553
554 // Does our map have this PID or name?
555 // NOTE: Caller MUST hold procevent_data_lock when calling this function
556 static processlist_t *process_map_check(long pid, char *process) {
557   for (processlist_t *pl = processlist_head; pl != NULL; pl = pl->next) {
558     int match_pid = 0;
559
560     if (pid > 0) {
561       if (pl->pid == pid)
562         match_pid = 1;
563     }
564
565     int match_process = 0;
566
567     if (process != NULL) {
568       if (strcmp(pl->process, process) == 0)
569         match_process = 1;
570     }
571
572     int match = 0;
573
574     if ((pid > 0 && process == NULL && match_pid == 1) ||
575         (pid < 0 && process != NULL && match_process == 1) ||
576         (pid > 0 && process != NULL && match_pid == 1 && match_process == 1)) {
577       match = 1;
578     }
579
580     if (match == 1) {
581       return pl;
582     }
583   }
584
585   return NULL;
586 }
587
588 static int process_map_refresh(void) {
589   errno = 0;
590   DIR *proc = opendir(PROCDIR);
591
592   if (proc == NULL) {
593     ERROR("procevent plugin: fopen (%s): %s", PROCDIR, STRERRNO);
594     return -1;
595   }
596
597   while (42) {
598     errno = 0;
599     struct dirent *dent = readdir(proc);
600     if (dent == NULL) {
601       if (errno == 0) /* end of directory */
602         break;
603
604       ERROR("procevent plugin: failed to read directory %s: %s", PROCDIR,
605             STRERRNO);
606       closedir(proc);
607       return -1;
608     }
609
610     if (dent->d_name[0] == '.')
611       continue;
612
613     char file[BUFSIZE];
614
615     int len = snprintf(file, sizeof(file), PROCDIR "/%s", dent->d_name);
616     if ((len < 0) || (len >= BUFSIZE))
617       continue;
618
619     struct stat statbuf;
620
621     int status = stat(file, &statbuf);
622     if (status != 0) {
623       WARNING("procevent plugin: stat (%s) failed: %s", file, STRERRNO);
624       continue;
625     }
626
627     if (!S_ISDIR(statbuf.st_mode))
628       continue;
629
630     len = snprintf(file, sizeof(file), PROCDIR "/%s/comm", dent->d_name);
631     if ((len < 0) || (len >= BUFSIZE))
632       continue;
633
634     int not_number = 0;
635
636     for (int i = 0; i < strlen(dent->d_name); i++) {
637       if (!isdigit(dent->d_name[i])) {
638         not_number = 1;
639         break;
640       }
641     }
642
643     if (not_number != 0)
644       continue;
645
646     // Check if we need to store this pid/name combo in our processlist_t linked
647     // list
648     int this_pid = atoi(dent->d_name);
649     pthread_mutex_lock(&procevent_data_lock);
650     processlist_t *pl = process_check(this_pid);
651     pthread_mutex_unlock(&procevent_data_lock);
652
653     if (pl != NULL)
654       DEBUG("procevent plugin: process map refreshed for PID %d and name %s",
655             this_pid, pl->process);
656   }
657
658   closedir(proc);
659
660   return 0;
661 }
662
663 static int nl_connect() {
664   struct sockaddr_nl sa_nl = {
665       .nl_family = AF_NETLINK, .nl_groups = CN_IDX_PROC, .nl_pid = getpid(),
666   };
667
668   nl_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
669   if (nl_sock == -1) {
670     ERROR("procevent plugin: socket open failed: %d", errno);
671     return -1;
672   }
673
674   int rc = bind(nl_sock, (struct sockaddr *)&sa_nl, sizeof(sa_nl));
675   if (rc == -1) {
676     ERROR("procevent plugin: socket bind failed: %d", errno);
677     close(nl_sock);
678     nl_sock = -1;
679     return -1;
680   }
681
682   return 0;
683 }
684
685 static int set_proc_ev_listen(bool enable) {
686   struct __attribute__((aligned(NLMSG_ALIGNTO))) {
687     struct nlmsghdr nl_hdr;
688     struct __attribute__((__packed__)) {
689       struct cn_msg cn_msg;
690       enum proc_cn_mcast_op cn_mcast;
691     };
692   } nlcn_msg;
693
694   memset(&nlcn_msg, 0, sizeof(nlcn_msg));
695   nlcn_msg.nl_hdr.nlmsg_len = sizeof(nlcn_msg);
696   nlcn_msg.nl_hdr.nlmsg_pid = getpid();
697   nlcn_msg.nl_hdr.nlmsg_type = NLMSG_DONE;
698
699   nlcn_msg.cn_msg.id.idx = CN_IDX_PROC;
700   nlcn_msg.cn_msg.id.val = CN_VAL_PROC;
701   nlcn_msg.cn_msg.len = sizeof(enum proc_cn_mcast_op);
702
703   nlcn_msg.cn_mcast = enable ? PROC_CN_MCAST_LISTEN : PROC_CN_MCAST_IGNORE;
704
705   int rc = send(nl_sock, &nlcn_msg, sizeof(nlcn_msg), 0);
706   if (rc == -1) {
707     ERROR("procevent plugin: subscribing to netlink process events failed: %d",
708           errno);
709     return -1;
710   }
711
712   return 0;
713 }
714
715 // Read from netlink socket and write to ring buffer
716 static int read_event() {
717   int recv_flags = MSG_DONTWAIT;
718   struct __attribute__((aligned(NLMSG_ALIGNTO))) {
719     struct nlmsghdr nl_hdr;
720     struct __attribute__((__packed__)) {
721       struct cn_msg cn_msg;
722       struct proc_event proc_ev;
723     };
724   } nlcn_msg;
725
726   if (nl_sock == -1)
727     return 0;
728
729   while (42) {
730     pthread_mutex_lock(&procevent_thread_lock);
731
732     if (procevent_netlink_thread_loop <= 0) {
733       pthread_mutex_unlock(&procevent_thread_lock);
734       return 0;
735     }
736
737     pthread_mutex_unlock(&procevent_thread_lock);
738
739     int status = recv(nl_sock, &nlcn_msg, sizeof(nlcn_msg), recv_flags);
740
741     if (status == 0) {
742       return 0;
743     } else if (status < 0) {
744       if (errno == EAGAIN || errno == EWOULDBLOCK) {
745         pthread_mutex_lock(&procevent_data_lock);
746
747         // There was nothing more to receive for now, so...
748         // If ring head does not equal ring tail, then there is data
749         // in the ring buffer for the dequeue thread to read, so
750         // signal it
751         if (ring.head != ring.tail)
752           pthread_cond_signal(&procevent_cond);
753
754         pthread_mutex_unlock(&procevent_data_lock);
755
756         // Since there was nothing to receive, set recv to block and
757         // try again
758         recv_flags = 0;
759         continue;
760       } else if (errno != EINTR) {
761         ERROR("procevent plugin: socket receive error: %d", errno);
762         return -1;
763       } else {
764         // Interrupt, so just continue and try again
765         continue;
766       }
767     }
768
769     // We successfully received a message, so don't block on the next
770     // read in case there are more (and if there aren't, it will be
771     // handled above in the EWOULDBLOCK error-checking)
772     recv_flags = MSG_DONTWAIT;
773
774     int proc_id = -1;
775     int proc_status = -1;
776
777     switch (nlcn_msg.proc_ev.what) {
778     case PROC_EVENT_EXEC:
779       proc_status = PROCEVENT_STARTED;
780       proc_id = nlcn_msg.proc_ev.event_data.exec.process_pid;
781       break;
782     case PROC_EVENT_EXIT:
783       proc_id = nlcn_msg.proc_ev.event_data.exit.process_pid;
784       proc_status = PROCEVENT_EXITED;
785       break;
786     default:
787       // Otherwise not of interest
788       break;
789     }
790
791     // If we're interested in this process status event, place the event
792     // in the ring buffer for consumption by the dequeue (dispatch) thread.
793
794     if (proc_status != -1) {
795       pthread_mutex_lock(&procevent_data_lock);
796
797       int next = ring.head + 1;
798       if (next >= ring.maxLen)
799         next = 0;
800
801       if (next == ring.tail) {
802         // Buffer is full, signal the dequeue thread to process the buffer
803         // and clean it out, and then sleep
804         WARNING("procevent plugin: ring buffer full");
805
806         pthread_cond_signal(&procevent_cond);
807         pthread_mutex_unlock(&procevent_data_lock);
808
809         usleep(1000);
810         continue;
811       } else {
812         DEBUG("procevent plugin: Process %d status is now %s at %lu", proc_id,
813               (proc_status == PROCEVENT_EXITED ? "EXITED" : "STARTED"),
814               CDTIME_T_TO_US(cdtime()));
815
816         ring.buffer[ring.head][RBUF_PROC_ID_INDEX] = proc_id;
817         ring.buffer[ring.head][RBUF_PROC_STATUS_INDEX] = proc_status;
818         ring.buffer[ring.head][RBUF_TIME_INDEX] = cdtime();
819
820         ring.head = next;
821       }
822
823       pthread_mutex_unlock(&procevent_data_lock);
824     }
825   }
826
827   return 0;
828 }
829
830 static void procevent_dispatch_notification(long pid, gauge_t value,
831                                             char *process, cdtime_t timestamp) {
832
833   notification_t n = {
834       .severity = (value == 1 ? NOTIF_OKAY : NOTIF_FAILURE),
835       .time = cdtime(),
836       .plugin = "procevent",
837       .type = "gauge",
838       .type_instance = "process_status",
839   };
840
841   sstrncpy(n.host, hostname_g, sizeof(n.host));
842   sstrncpy(n.plugin_instance, process, sizeof(n.plugin_instance));
843
844   char *buf = NULL;
845   gen_message_payload(value, pid, process, timestamp, &buf);
846
847   int status = plugin_notification_meta_add_string(&n, "ves", buf);
848
849   if (status < 0) {
850     sfree(buf);
851     ERROR("procevent plugin: unable to set notification VES metadata: %s",
852           STRERRNO);
853     return;
854   }
855
856   DEBUG("procevent plugin: notification VES metadata: %s",
857         n.meta->nm_value.nm_string);
858
859   DEBUG("procevent plugin: dispatching state %d for PID %ld (%s)", (int)value,
860         pid, process);
861
862   plugin_dispatch_notification(&n);
863   plugin_notification_meta_free(n.meta);
864
865   // strdup'd in gen_message_payload
866   if (buf != NULL)
867     sfree(buf);
868 }
869
870 // Read from ring buffer and dispatch to write plugins
871 static void read_ring_buffer() {
872   pthread_mutex_lock(&procevent_data_lock);
873
874   // If there's currently nothing to read from the buffer,
875   // then wait
876   if (ring.head == ring.tail)
877     pthread_cond_wait(&procevent_cond, &procevent_data_lock);
878
879   while (ring.head != ring.tail) {
880     int next = ring.tail + 1;
881
882     if (next >= ring.maxLen)
883       next = 0;
884
885     if (ring.buffer[ring.tail][RBUF_PROC_STATUS_INDEX] == PROCEVENT_EXITED) {
886       processlist_t *pl = process_map_check(ring.buffer[ring.tail][0], NULL);
887
888       if (pl != NULL) {
889         // This process is of interest to us, so publish its EXITED status
890         procevent_dispatch_notification(
891             ring.buffer[ring.tail][RBUF_PROC_ID_INDEX],
892             ring.buffer[ring.tail][RBUF_PROC_STATUS_INDEX], pl->process,
893             ring.buffer[ring.tail][RBUF_TIME_INDEX]);
894         DEBUG(
895             "procevent plugin: PID %ld (%s) EXITED, removing PID from process "
896             "list",
897             pl->pid, pl->process);
898         pl->pid = -1;
899         pl->last_status = -1;
900       }
901     } else if (ring.buffer[ring.tail][RBUF_PROC_STATUS_INDEX] ==
902                PROCEVENT_STARTED) {
903       // a new process has started, so check if we should monitor it
904       processlist_t *pl = process_check(ring.buffer[ring.tail][0]);
905
906       // If we had already seen this process name and pid combo before,
907       // and the last message was a "process started" message, don't send
908       // the notfication again
909
910       if (pl != NULL && pl->last_status != PROCEVENT_STARTED) {
911         // This process is of interest to us, so publish its STARTED status
912         procevent_dispatch_notification(
913             ring.buffer[ring.tail][RBUF_PROC_ID_INDEX],
914             ring.buffer[ring.tail][RBUF_PROC_STATUS_INDEX], pl->process,
915             ring.buffer[ring.tail][RBUF_TIME_INDEX]);
916
917         pl->last_status = PROCEVENT_STARTED;
918
919         DEBUG("procevent plugin: PID %ld (%s) STARTED, adding PID to process "
920               "list",
921               pl->pid, pl->process);
922       }
923     }
924
925     ring.tail = next;
926   }
927
928   pthread_mutex_unlock(&procevent_data_lock);
929 }
930
931 // Entry point for thread responsible for listening
932 // to netlink socket and writing data to ring buffer
933 static void *procevent_netlink_thread(void *arg) /* {{{ */
934 {
935   pthread_mutex_lock(&procevent_thread_lock);
936
937   while (procevent_netlink_thread_loop > 0) {
938     pthread_mutex_unlock(&procevent_thread_lock);
939
940     int status = read_event();
941
942     pthread_mutex_lock(&procevent_thread_lock);
943
944     if (status < 0) {
945       procevent_netlink_thread_error = 1;
946       break;
947     }
948   } /* while (procevent_netlink_thread_loop > 0) */
949
950   pthread_mutex_unlock(&procevent_thread_lock);
951
952   return (void *)0;
953 } /* }}} void *procevent_netlink_thread */
954
955 // Entry point for thread responsible for reading from
956 // ring buffer and dispatching notifications
957 static void *procevent_dequeue_thread(void *arg) /* {{{ */
958 {
959   pthread_mutex_lock(&procevent_thread_lock);
960
961   while (procevent_dequeue_thread_loop > 0) {
962     pthread_mutex_unlock(&procevent_thread_lock);
963
964     read_ring_buffer();
965
966     pthread_mutex_lock(&procevent_thread_lock);
967   } /* while (procevent_dequeue_thread_loop > 0) */
968
969   pthread_mutex_unlock(&procevent_thread_lock);
970
971   return (void *)0;
972 } /* }}} void *procevent_dequeue_thread */
973
974 static int start_netlink_thread(void) /* {{{ */
975 {
976   pthread_mutex_lock(&procevent_thread_lock);
977
978   if (procevent_netlink_thread_loop != 0) {
979     pthread_mutex_unlock(&procevent_thread_lock);
980     return 0;
981   }
982
983   int status;
984
985   if (nl_sock == -1) {
986     status = nl_connect();
987
988     if (status != 0) {
989       pthread_mutex_unlock(&procevent_thread_lock);
990       return status;
991     }
992
993     status = set_proc_ev_listen(true);
994     if (status == -1) {
995       pthread_mutex_unlock(&procevent_thread_lock);
996       return status;
997     }
998   }
999
1000   DEBUG("procevent plugin: socket created and bound");
1001
1002   procevent_netlink_thread_loop = 1;
1003   procevent_netlink_thread_error = 0;
1004
1005   status = plugin_thread_create(&procevent_netlink_thread_id, /* attr = */ NULL,
1006                                 procevent_netlink_thread,
1007                                 /* arg = */ (void *)0, "procevent");
1008   if (status != 0) {
1009     procevent_netlink_thread_loop = 0;
1010     ERROR("procevent plugin: Starting netlink thread failed.");
1011     pthread_mutex_unlock(&procevent_thread_lock);
1012
1013     int status2 = close(nl_sock);
1014
1015     if (status2 != 0) {
1016       ERROR("procevent plugin: failed to close socket %d: %d (%s)", nl_sock,
1017             status2, STRERRNO);
1018     }
1019
1020     nl_sock = -1;
1021
1022     return -1;
1023   }
1024
1025   pthread_mutex_unlock(&procevent_thread_lock);
1026
1027   return status;
1028 } /* }}} int start_netlink_thread */
1029
1030 static int start_dequeue_thread(void) /* {{{ */
1031 {
1032   pthread_mutex_lock(&procevent_thread_lock);
1033
1034   if (procevent_dequeue_thread_loop != 0) {
1035     pthread_mutex_unlock(&procevent_thread_lock);
1036     return 0;
1037   }
1038
1039   procevent_dequeue_thread_loop = 1;
1040
1041   int status = plugin_thread_create(&procevent_dequeue_thread_id,
1042                                     /* attr = */ NULL, procevent_dequeue_thread,
1043                                     /* arg = */ (void *)0, "procevent");
1044   if (status != 0) {
1045     procevent_dequeue_thread_loop = 0;
1046     ERROR("procevent plugin: Starting dequeue thread failed.");
1047     pthread_mutex_unlock(&procevent_thread_lock);
1048     return -1;
1049   }
1050
1051   pthread_mutex_unlock(&procevent_thread_lock);
1052
1053   return status;
1054 } /* }}} int start_dequeue_thread */
1055
1056 static int start_threads(void) /* {{{ */
1057 {
1058   int status = start_netlink_thread();
1059   int status2 = start_dequeue_thread();
1060
1061   if (status != 0)
1062     return status;
1063   else
1064     return status2;
1065 } /* }}} int start_threads */
1066
1067 static int stop_netlink_thread(int shutdown) /* {{{ */
1068 {
1069   int socket_status;
1070
1071   if (nl_sock != -1) {
1072     socket_status = close(nl_sock);
1073     if (socket_status != 0) {
1074       ERROR("procevent plugin: failed to close socket %d: %d (%s)", nl_sock,
1075             socket_status, strerror(errno));
1076     }
1077
1078     nl_sock = -1;
1079   } else
1080     socket_status = 0;
1081
1082   pthread_mutex_lock(&procevent_thread_lock);
1083
1084   if (procevent_netlink_thread_loop == 0) {
1085     pthread_mutex_unlock(&procevent_thread_lock);
1086     return -1;
1087   }
1088
1089   // Set thread termination status
1090   procevent_netlink_thread_loop = 0;
1091   pthread_mutex_unlock(&procevent_thread_lock);
1092
1093   // Let threads waiting on access to the data know to move
1094   // on such that they'll see the thread's termination status
1095   pthread_cond_broadcast(&procevent_cond);
1096
1097   int thread_status;
1098
1099   if (shutdown == 1) {
1100     // Calling pthread_cancel here in
1101     // the case of a shutdown just assures that the thread is
1102     // gone and that the process has been fully terminated.
1103
1104     DEBUG("procevent plugin: Canceling netlink thread for process shutdown");
1105
1106     thread_status = pthread_cancel(procevent_netlink_thread_id);
1107
1108     if (thread_status != 0 && thread_status != ESRCH) {
1109       ERROR("procevent plugin: Unable to cancel netlink thread: %d",
1110             thread_status);
1111       thread_status = -1;
1112     } else
1113       thread_status = 0;
1114   } else {
1115     thread_status =
1116         pthread_join(procevent_netlink_thread_id, /* return = */ NULL);
1117     if (thread_status != 0 && thread_status != ESRCH) {
1118       ERROR("procevent plugin: Stopping netlink thread failed.");
1119       thread_status = -1;
1120     } else
1121       thread_status = 0;
1122   }
1123
1124   pthread_mutex_lock(&procevent_thread_lock);
1125   memset(&procevent_netlink_thread_id, 0, sizeof(procevent_netlink_thread_id));
1126   procevent_netlink_thread_error = 0;
1127   pthread_mutex_unlock(&procevent_thread_lock);
1128
1129   DEBUG("procevent plugin: Finished requesting stop of netlink thread");
1130
1131   if (socket_status != 0)
1132     return socket_status;
1133   else
1134     return thread_status;
1135 } /* }}} int stop_netlink_thread */
1136
1137 static int stop_dequeue_thread() /* {{{ */
1138 {
1139   pthread_mutex_lock(&procevent_thread_lock);
1140
1141   if (procevent_dequeue_thread_loop == 0) {
1142     pthread_mutex_unlock(&procevent_thread_lock);
1143     return -1;
1144   }
1145
1146   procevent_dequeue_thread_loop = 0;
1147   pthread_mutex_unlock(&procevent_thread_lock);
1148
1149   pthread_cond_broadcast(&procevent_cond);
1150
1151   // Calling pthread_cancel here just assures that the thread is
1152   // gone and that the process has been fully terminated.
1153
1154   DEBUG("procevent plugin: Canceling dequeue thread for process shutdown");
1155
1156   int status = pthread_cancel(procevent_dequeue_thread_id);
1157
1158   if (status != 0 && status != ESRCH) {
1159     ERROR("procevent plugin: Unable to cancel dequeue thread: %d", status);
1160     status = -1;
1161   } else
1162     status = 0;
1163
1164   pthread_mutex_lock(&procevent_thread_lock);
1165   memset(&procevent_dequeue_thread_id, 0, sizeof(procevent_dequeue_thread_id));
1166   pthread_mutex_unlock(&procevent_thread_lock);
1167
1168   DEBUG("procevent plugin: Finished requesting stop of dequeue thread");
1169
1170   return status;
1171 } /* }}} int stop_dequeue_thread */
1172
1173 static int stop_threads() /* {{{ */
1174 {
1175   int status = stop_netlink_thread(1);
1176   int status2 = stop_dequeue_thread();
1177
1178   if (status != 0)
1179     return status;
1180   else
1181     return status2;
1182 } /* }}} int stop_threads */
1183
1184 static int procevent_init(void) /* {{{ */
1185 {
1186   ring.head = 0;
1187   ring.tail = 0;
1188   ring.maxLen = buffer_length;
1189   ring.buffer = (cdtime_t **)calloc(buffer_length, sizeof(cdtime_t *));
1190
1191   for (int i = 0; i < buffer_length; i++) {
1192     ring.buffer[i] = (cdtime_t *)calloc(PROCEVENT_FIELDS, sizeof(cdtime_t));
1193   }
1194
1195   int status = process_map_refresh();
1196
1197   if (status == -1) {
1198     ERROR("procevent plugin: Initial process mapping failed.");
1199     return -1;
1200   }
1201
1202   if (ignorelist == NULL) {
1203     NOTICE("procevent plugin: No processes have been configured.");
1204     return -1;
1205   }
1206
1207   return start_threads();
1208 } /* }}} int procevent_init */
1209
1210 static int procevent_config(const char *key, const char *value) /* {{{ */
1211 {
1212   if (ignorelist == NULL)
1213     ignorelist = ignorelist_create(/* invert = */ 1);
1214
1215   if (ignorelist == NULL) {
1216     return -1;
1217   }
1218
1219   if (strcasecmp(key, "BufferLength") == 0) {
1220     buffer_length = atoi(value);
1221   } else if (strcasecmp(key, "Process") == 0) {
1222     ignorelist_add(ignorelist, value);
1223   } else if (strcasecmp(key, "ProcessRegex") == 0) {
1224 #if HAVE_REGEX_H
1225     int status = ignorelist_add(ignorelist, value);
1226
1227     if (status != 0) {
1228       ERROR("procevent plugin: invalid regular expression: %s", value);
1229       return 1;
1230     }
1231 #else
1232     WARNING("procevent plugin: The plugin has been compiled without support "
1233             "for the \"ProcessRegex\" option.");
1234 #endif
1235   } else {
1236     return -1;
1237   }
1238
1239   return 0;
1240 } /* }}} int procevent_config */
1241
1242 static int procevent_read(void) /* {{{ */
1243 {
1244   pthread_mutex_lock(&procevent_thread_lock);
1245
1246   if (procevent_netlink_thread_error != 0) {
1247
1248     pthread_mutex_unlock(&procevent_thread_lock);
1249
1250     ERROR("procevent plugin: The netlink thread had a problem. Restarting it.");
1251
1252     stop_netlink_thread(0);
1253
1254     start_netlink_thread();
1255
1256     return -1;
1257   } /* if (procevent_netlink_thread_error != 0) */
1258
1259   pthread_mutex_unlock(&procevent_thread_lock);
1260
1261   return 0;
1262 } /* }}} int procevent_read */
1263
1264 static int procevent_shutdown(void) /* {{{ */
1265 {
1266   DEBUG("procevent plugin: Shutting down threads.");
1267
1268   int status = stop_threads();
1269
1270   for (int i = 0; i < buffer_length; i++) {
1271     free(ring.buffer[i]);
1272   }
1273
1274   free(ring.buffer);
1275
1276   processlist_t *pl = processlist_head;
1277   while (pl != NULL) {
1278     processlist_t *pl_next;
1279
1280     pl_next = pl->next;
1281
1282     sfree(pl->process);
1283     sfree(pl);
1284
1285     pl = pl_next;
1286   }
1287
1288   ignorelist_free(ignorelist);
1289
1290   return status;
1291 } /* }}} int procevent_shutdown */
1292
1293 void module_register(void) {
1294   plugin_register_config("procevent", procevent_config, config_keys,
1295                          config_keys_num);
1296   plugin_register_init("procevent", procevent_init);
1297   plugin_register_read("procevent", procevent_read);
1298   plugin_register_shutdown("procevent", procevent_shutdown);
1299 } /* void module_register */