484464f98bd37e31c1d35f9f483ccf5c17fe09cf
[collectd.git] / src / mcelog.c
1 /*-
2  * collectd - src/mcelog.c
3  * MIT License
4  *
5  * Copyright(c) 2016 Intel Corporation. All rights reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the "Software"),
9  * to deal in the Software without restriction, including without limitation
10  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11  * and/or sell copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23  * DEALINGS IN THE SOFTWARE.
24
25  * Authors:
26  *   Maryam Tahhan <maryam.tahhan@intel.com>
27  *   Volodymyr Mytnyk <volodymyrx.mytnyk@intel.com>
28  *   Taras Chornyi <tarasx.chornyi@intel.com>
29  *   Krzysztof Matczak <krzysztofx.matczak@intel.com>
30  */
31
32 #include "common.h"
33 #include "collectd.h"
34
35 #include <poll.h>
36 #include <sys/socket.h>
37 #include <sys/un.h>
38 #include <unistd.h>
39
40 #define MCELOG_PLUGIN "mcelog"
41 #define MCELOG_BUFF_SIZE 1024
42 #define MCELOG_POLL_TIMEOUT 1000 /* ms */
43 #define MCELOG_SOCKET_STR "SOCKET"
44 #define MCELOG_DIMM_NAME "DMI_NAME"
45 #define MCELOG_CORRECTED_ERR "corrected memory errors:"
46 #define MCELOG_UNCORRECTED_ERR "uncorrected memory errors:"
47
48 typedef struct mcelog_config_s {
49   char logfile[PATH_MAX]; /* mcelog logfile */
50   pthread_t tid;          /* poll thread id */
51 } mcelog_config_t;
52
53 typedef struct socket_adapter_s socket_adapter_t;
54
55 struct socket_adapter_s {
56   int sock_fd;                  /* mcelog server socket fd */
57   struct sockaddr_un unix_sock; /* mcelog client socket */
58   pthread_rwlock_t lock;
59   /* function pointers for socket operations */
60   int (*write)(socket_adapter_t *self, const char *msg, const size_t len);
61   int (*reinit)(socket_adapter_t *self);
62   int (*receive)(socket_adapter_t *self, FILE **p_file);
63   int (*close)(socket_adapter_t *self);
64 };
65
66 typedef struct mcelog_memory_rec_s {
67   int corrected_err_total;           /* x total*/
68   int corrected_err_timed;           /* x in 24h*/
69   char corrected_err_timed_period[DATA_MAX_NAME_LEN];
70   int uncorrected_err_total; /* x total*/
71   int uncorrected_err_timed; /* x in 24h*/
72   char uncorrected_err_timed_period[DATA_MAX_NAME_LEN];
73   char location[DATA_MAX_NAME_LEN];  /* SOCKET x CHANNEL x DIMM x*/
74   char dimm_name[DATA_MAX_NAME_LEN]; /* DMI_NAME "DIMM_F1" */
75 } mcelog_memory_rec_t;
76
77 static int socket_close(socket_adapter_t *self);
78 static int socket_write(socket_adapter_t *self, const char *msg,
79                         const size_t len);
80 static int socket_reinit(socket_adapter_t *self);
81 static int socket_receive(socket_adapter_t *self, FILE **p_file);
82
83 static mcelog_config_t g_mcelog_config = {
84     .logfile = "/var/log/mcelog", .tid = 0,
85 };
86
87 static socket_adapter_t socket_adapter = {
88     .sock_fd = -1,
89     .unix_sock =
90         {
91             .sun_family = AF_UNIX, .sun_path = "/var/run/mcelog-client",
92         },
93     .lock = PTHREAD_RWLOCK_INITIALIZER,
94     .close = socket_close,
95     .write = socket_write,
96     .reinit = socket_reinit,
97     .receive = socket_receive,
98 };
99
100 static _Bool mcelog_thread_running = 0;
101
102 static int mcelog_config(oconfig_item_t *ci) {
103   for (int i = 0; i < ci->children_num; i++) {
104     oconfig_item_t *child = ci->children + i;
105     if (strcasecmp("McelogClientSocket", child->key) == 0) {
106       if (cf_util_get_string_buffer(child, socket_adapter.unix_sock.sun_path,
107                                     sizeof(socket_adapter.unix_sock.sun_path)) <
108           0) {
109         ERROR("%s: Invalid configuration option: \"%s\".", MCELOG_PLUGIN,
110               child->key);
111         return -1;
112       }
113     } else if (strcasecmp("McelogLogfile", child->key) == 0) {
114       if (cf_util_get_string_buffer(child, g_mcelog_config.logfile,
115                                     sizeof(g_mcelog_config.logfile)) < 0) {
116         ERROR("%s: Invalid configuration option: \"%s\".", MCELOG_PLUGIN,
117               child->key);
118         return -1;
119       }
120     } else {
121       ERROR("%s: Invalid configuration option: \"%s\".", MCELOG_PLUGIN,
122             child->key);
123       return -1;
124     }
125   }
126   return (0);
127 }
128
129 static int socket_close(socket_adapter_t *self) {
130   int ret = 0;
131   pthread_rwlock_rdlock(&self->lock);
132   if (fcntl(self->sock_fd, F_GETFL) != -1) {
133     if (shutdown(self->sock_fd, SHUT_RDWR) != 0) {
134       char errbuf[MCELOG_BUFF_SIZE];
135       ERROR("%s: Socket shutdown failed: %s", MCELOG_PLUGIN,
136             sstrerror(errno, errbuf, sizeof(errbuf)));
137       ret = -1;
138     }
139     close(self->sock_fd);
140   }
141   pthread_rwlock_unlock(&self->lock);
142   return ret;
143 }
144
145 static int socket_write(socket_adapter_t *self, const char *msg,
146                         const size_t len) {
147   int ret = 0;
148   pthread_rwlock_rdlock(&self->lock);
149   if (swrite(self->sock_fd, msg, len) < 0)
150     ret = -1;
151   pthread_rwlock_unlock(&self->lock);
152   return ret;
153 }
154
155 static void mcelog_dispatch_notification(notification_t *n) {
156   if (!n) {
157     ERROR(MCELOG_PLUGIN ": %s: NULL pointer", __FUNCTION__);
158     return;
159   }
160
161   sstrncpy(n->host, hostname_g, sizeof(n->host));
162   sstrncpy(n->type, "gauge", sizeof(n->type));
163   plugin_dispatch_notification(n);
164 }
165
166 static int socket_reinit(socket_adapter_t *self) {
167   char errbuff[MCELOG_BUFF_SIZE];
168   int ret = -1;
169   cdtime_t interval = plugin_get_interval();
170   struct timeval socket_timeout = CDTIME_T_TO_TIMEVAL(interval);
171
172   /* synchronization via write lock since sock_fd may be changed here */
173   pthread_rwlock_wrlock(&self->lock);
174   self->sock_fd = socket(PF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
175   if (self->sock_fd < 0) {
176     ERROR("%s: Could not create a socket. %s", MCELOG_PLUGIN,
177           sstrerror(errno, errbuff, sizeof(errbuff)));
178     pthread_rwlock_unlock(&self->lock);
179     return ret;
180   }
181
182   /* Set socket timeout option */
183   if (setsockopt(self->sock_fd, SOL_SOCKET, SO_SNDTIMEO,
184                  &socket_timeout, sizeof(socket_timeout)) < 0)
185     ERROR("%s: Failed to set the socket timeout option.", MCELOG_PLUGIN);
186
187   /* downgrading to read lock due to possible recursive read locks
188    * in self->close(self) call */
189   pthread_rwlock_unlock(&self->lock);
190   pthread_rwlock_rdlock(&self->lock);
191   if (connect(self->sock_fd, (struct sockaddr *)&(self->unix_sock),
192               sizeof(self->unix_sock)) < 0) {
193     ERROR("%s: Failed to connect to mcelog server. %s", MCELOG_PLUGIN,
194           sstrerror(errno, errbuff, sizeof(errbuff)));
195     self->close(self);
196     ret = -1;
197   } else {
198     ret = 0;
199     mcelog_dispatch_notification(
200         &(notification_t){.severity = NOTIF_OKAY,
201                           .time = cdtime(),
202                           .message = "Connected to mcelog server",
203                           .plugin = MCELOG_PLUGIN,
204                           .type_instance = "mcelog_status"});
205   }
206   pthread_rwlock_unlock(&self->lock);
207   return ret;
208 }
209
210 static int mcelog_prepare_notification(notification_t *n,
211                                        mcelog_memory_rec_t mr) {
212   if (n == NULL)
213     return (-1);
214
215   if (plugin_notification_meta_add_string(n, MCELOG_SOCKET_STR, mr.location) <
216       0) {
217     ERROR("%s: add memory location meta data failed", MCELOG_PLUGIN);
218     return (-1);
219   }
220   if (strlen(mr.dimm_name) > 0)
221     if (plugin_notification_meta_add_string(n, MCELOG_DIMM_NAME, mr.dimm_name) <
222         0) {
223       ERROR("%s: add DIMM name meta data failed", MCELOG_PLUGIN);
224       return (-1);
225     }
226   if (plugin_notification_meta_add_signed_int(n, MCELOG_CORRECTED_ERR,
227                                               mr.corrected_err_total) < 0) {
228     ERROR("%s: add corrected errors meta data failed", MCELOG_PLUGIN);
229     return (-1);
230   }
231   if (plugin_notification_meta_add_signed_int(
232           n, "corrected memory timed errors", mr.corrected_err_timed) < 0) {
233     ERROR("%s: add corrected timed errors meta data failed", MCELOG_PLUGIN);
234     return (-1);
235   }
236   if (plugin_notification_meta_add_string(n, "corrected errors time period",
237                                           mr.corrected_err_timed_period) < 0) {
238     ERROR("%s: add corrected errors period meta data failed", MCELOG_PLUGIN);
239     return (-1);
240   }
241   if (plugin_notification_meta_add_signed_int(n, MCELOG_UNCORRECTED_ERR,
242                                               mr.uncorrected_err_total) < 0) {
243     ERROR("%s: add corrected errors meta data failed", MCELOG_PLUGIN);
244     return (-1);
245   }
246   if (plugin_notification_meta_add_signed_int(
247           n, "uncorrected memory timed errors", mr.uncorrected_err_timed) < 0) {
248     ERROR("%s: add corrected timed errors meta data failed", MCELOG_PLUGIN);
249     return (-1);
250   }
251   if (plugin_notification_meta_add_string(n, "uncorrected errors time period",
252                                           mr.uncorrected_err_timed_period) <
253       0) {
254     ERROR("%s: add corrected errors period meta data failed", MCELOG_PLUGIN);
255     return (-1);
256   }
257
258   return (0);
259 }
260
261 static int mcelog_submit(mcelog_memory_rec_t mr) {
262
263   value_list_t vl = VALUE_LIST_INIT;
264   vl.values_len = 1;
265   vl.time = cdtime();
266
267   sstrncpy(vl.plugin, MCELOG_PLUGIN, sizeof(vl.plugin));
268   sstrncpy(vl.type, "errors", sizeof(vl.type));
269   if (strlen(mr.dimm_name) > 0) {
270     ssnprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%s_%s",
271               mr.location, mr.dimm_name);
272   } else
273     sstrncpy(vl.plugin_instance, mr.location, sizeof(vl.plugin_instance));
274
275   sstrncpy(vl.type_instance, "corrected_memory_errors",
276            sizeof(vl.type_instance));
277   vl.values = &(value_t){.derive = (derive_t)mr.corrected_err_total};
278   plugin_dispatch_values(&vl);
279
280   ssnprintf(vl.type_instance, sizeof(vl.type_instance),
281             "corrected_memory_errors_in_%s", mr.corrected_err_timed_period);
282   vl.values = &(value_t){.derive = (derive_t)mr.corrected_err_timed};
283   plugin_dispatch_values(&vl);
284
285   sstrncpy(vl.type_instance, "uncorrected_memory_errors",
286            sizeof(vl.type_instance));
287   vl.values = &(value_t){.derive = (derive_t)mr.uncorrected_err_total};
288   plugin_dispatch_values(&vl);
289
290   ssnprintf(vl.type_instance, sizeof(vl.type_instance),
291             "uncorrected_memory_errors_in_%s", mr.uncorrected_err_timed_period);
292   vl.values = &(value_t){.derive = (derive_t)mr.uncorrected_err_timed};
293   plugin_dispatch_values(&vl);
294
295   return 0;
296 }
297
298 static int parse_memory_info(FILE *p_file, mcelog_memory_rec_t *memory_record) {
299   char buf[DATA_MAX_NAME_LEN] = {0};
300   while (fgets(buf, sizeof(buf), p_file)) {
301     /* Got empty line or "done" */
302     if ((!strncmp("\n", buf, strlen(buf))) ||
303         (!strncmp(buf, "done\n", strlen(buf))))
304       return 1;
305     if (strlen(buf) < 5)
306       continue;
307     if (!strncmp(buf, MCELOG_SOCKET_STR, strlen(MCELOG_SOCKET_STR))) {
308       sstrncpy(memory_record->location, buf, strlen(buf));
309       /* replace spaces with '_' */
310       for (size_t i = 0; i < strlen(memory_record->location); i++)
311         if (memory_record->location[i] == ' ')
312           memory_record->location[i] = '_';
313       DEBUG("%s: Got SOCKET INFO %s", MCELOG_PLUGIN, memory_record->location);
314     }
315     if (!strncmp(buf, MCELOG_DIMM_NAME, strlen(MCELOG_DIMM_NAME))) {
316       char *name = NULL;
317       char *saveptr = NULL;
318       name = strtok_r(buf, "\"", &saveptr);
319       if (name != NULL && saveptr != NULL) {
320         name = strtok_r(NULL, "\"", &saveptr);
321         if (name != NULL) {
322           sstrncpy(memory_record->dimm_name, name,
323                    sizeof(memory_record->dimm_name));
324           DEBUG("%s: Got DIMM NAME %s", MCELOG_PLUGIN,
325                 memory_record->dimm_name);
326         }
327       }
328     }
329     if (!strncmp(buf, MCELOG_CORRECTED_ERR, strlen(MCELOG_CORRECTED_ERR))) {
330       /* Get next line*/
331       if (fgets(buf, sizeof(buf), p_file) != NULL) {
332         sscanf(buf, "\t%d total", &(memory_record->corrected_err_total));
333         DEBUG("%s: Got corrected error total %d", MCELOG_PLUGIN,
334               memory_record->corrected_err_total);
335       }
336       if (fgets(buf, sizeof(buf), p_file) != NULL) {
337         sscanf(buf, "\t%d in %s", &(memory_record->corrected_err_timed),
338                memory_record->corrected_err_timed_period);
339         DEBUG("%s: Got timed corrected errors %d in %s", MCELOG_PLUGIN,
340               memory_record->corrected_err_total,
341               memory_record->corrected_err_timed_period);
342       }
343     }
344     if (!strncmp(buf, MCELOG_UNCORRECTED_ERR, strlen(MCELOG_UNCORRECTED_ERR))) {
345       if (fgets(buf, sizeof(buf), p_file) != NULL) {
346         sscanf(buf, "\t%d total", &(memory_record->uncorrected_err_total));
347         DEBUG("%s: Got uncorrected error total %d", MCELOG_PLUGIN,
348               memory_record->uncorrected_err_total);
349       }
350       if (fgets(buf, sizeof(buf), p_file) != NULL) {
351         sscanf(buf, "\t%d in %s", &(memory_record->uncorrected_err_timed),
352                memory_record->uncorrected_err_timed_period);
353         DEBUG("%s: Got timed uncorrected errors %d in %s", MCELOG_PLUGIN,
354               memory_record->uncorrected_err_total,
355               memory_record->uncorrected_err_timed_period);
356       }
357     }
358     memset(buf, 0, sizeof(buf));
359   }
360   /* parsing definitely finished */
361   return 0;
362 }
363
364 static void poll_worker_cleanup(void *arg) {
365   mcelog_thread_running = 0;
366   FILE *p_file = *((FILE **)arg);
367   if (p_file != NULL)
368     fclose(p_file);
369   free(arg);
370 }
371
372 static int socket_receive(socket_adapter_t *self, FILE **pp_file) {
373   int res = -1;
374   pthread_rwlock_rdlock(&self->lock);
375   struct pollfd poll_fd = {
376       .fd = self->sock_fd, .events = POLLIN | POLLPRI,
377   };
378
379   if ((res = poll(&poll_fd, 1, MCELOG_POLL_TIMEOUT)) <= 0) {
380     if (res != 0 && errno != EINTR) {
381       char errbuf[MCELOG_BUFF_SIZE];
382       ERROR("mcelog: poll failed: %s",
383             sstrerror(errno, errbuf, sizeof(errbuf)));
384     }
385     pthread_rwlock_unlock(&self->lock);
386     return res;
387   }
388
389   if (poll_fd.revents & (POLLERR | POLLHUP | POLLNVAL)) {
390     /* connection is broken */
391     ERROR("%s: Connection to socket is broken", MCELOG_PLUGIN);
392     if (poll_fd.revents & (POLLERR | POLLHUP)) {
393       mcelog_dispatch_notification(
394           &(notification_t){.severity = NOTIF_FAILURE,
395                             .time = cdtime(),
396                             .message = "Connection to mcelog socket is broken.",
397                             .plugin = MCELOG_PLUGIN,
398                             .type_instance = "mcelog_status"});
399     }
400     pthread_rwlock_unlock(&self->lock);
401     return -1;
402   }
403
404   if (!(poll_fd.revents & (POLLIN | POLLPRI))) {
405     INFO("%s: No data to read", MCELOG_PLUGIN);
406     pthread_rwlock_unlock(&self->lock);
407     return 0;
408   }
409
410   if ((*pp_file = fdopen(dup(self->sock_fd), "r")) == NULL)
411     res = -1;
412
413   pthread_rwlock_unlock(&self->lock);
414   return res;
415 }
416
417 static void *poll_worker(__attribute__((unused)) void *arg) {
418   char errbuf[MCELOG_BUFF_SIZE];
419   mcelog_thread_running = 1;
420   FILE **pp_file = calloc(1, sizeof(*pp_file));
421   if (pp_file == NULL) {
422     ERROR("mcelog: memory allocation failed: %s",
423           sstrerror(errno, errbuf, sizeof(errbuf)));
424     pthread_exit((void *)1);
425   }
426
427   pthread_cleanup_push(poll_worker_cleanup, pp_file);
428
429   while (1) {
430     /* blocking call */
431     int res = socket_adapter.receive(&socket_adapter, pp_file);
432     if (res < 0) {
433       socket_adapter.close(&socket_adapter);
434       while (socket_adapter.reinit(&socket_adapter) != 0) {
435         nanosleep(&CDTIME_T_TO_TIMESPEC(MS_TO_CDTIME_T(MCELOG_POLL_TIMEOUT)),
436                   NULL);
437       }
438       continue;
439     }
440     /* timeout or no data to read */
441     else if (res == 0)
442       continue;
443
444     if (*pp_file == NULL)
445       continue;
446
447     mcelog_memory_rec_t memory_record = {0};
448     while (parse_memory_info(*pp_file, &memory_record)) {
449       /* Check if location was successfully parsed */
450       if (memory_record.location[0] == '\0') {
451         memset(&memory_record, 0, sizeof(memory_record));
452         continue;
453       }
454
455       notification_t n = {.severity = NOTIF_OKAY,
456                           .time = cdtime(),
457                           .message = "Got memory errors info.",
458                           .plugin = MCELOG_PLUGIN,
459                           .type_instance = "memory_erros"};
460
461       if (mcelog_prepare_notification(&n, memory_record) == 0)
462         mcelog_dispatch_notification(&n);
463       if (mcelog_submit(memory_record) != 0)
464         ERROR("%s: Failed to submit memory errors", MCELOG_PLUGIN);
465       memset(&memory_record, 0, sizeof(memory_record));
466     }
467
468     fclose(*pp_file);
469     *pp_file = NULL;
470   }
471
472   mcelog_thread_running = 0;
473   pthread_cleanup_pop(1);
474   return NULL;
475 }
476
477 static int mcelog_init(void) {
478   if (socket_adapter.reinit(&socket_adapter) != 0) {
479     ERROR("%s: Cannot connect to client socket", MCELOG_PLUGIN);
480     return -1;
481   }
482
483   if (plugin_thread_create(&g_mcelog_config.tid, NULL, poll_worker, NULL,
484                            NULL) != 0) {
485     ERROR("%s: Error creating poll thread.", MCELOG_PLUGIN);
486     return -1;
487   }
488   return 0;
489 }
490
491 static int get_memory_machine_checks(void) {
492   static const char dump[] = "dump all bios\n";
493   int ret = socket_adapter.write(&socket_adapter, dump, sizeof(dump));
494   if (ret != 0)
495     ERROR("%s: SENT DUMP REQUEST FAILED", MCELOG_PLUGIN);
496   else
497     DEBUG("%s: SENT DUMP REQUEST OK", MCELOG_PLUGIN);
498   return ret;
499 }
500
501 static int mcelog_read(__attribute__((unused)) user_data_t *ud) {
502   DEBUG("%s: %s", MCELOG_PLUGIN, __FUNCTION__);
503
504   if (get_memory_machine_checks() != 0)
505     ERROR("%s: MACHINE CHECK INFO NOT AVAILABLE", MCELOG_PLUGIN);
506
507   return 0;
508 }
509
510 static int mcelog_shutdown(void) {
511   int ret = 0;
512   if (mcelog_thread_running) {
513     pthread_cancel(g_mcelog_config.tid);
514     if (pthread_join(g_mcelog_config.tid, NULL) != 0) {
515       ERROR("%s: Stopping thread failed.", MCELOG_PLUGIN);
516       ret = -1;
517     }
518   }
519
520   ret = socket_adapter.close(&socket_adapter) || ret;
521   pthread_rwlock_destroy(&(socket_adapter.lock));
522   return -ret;
523 }
524
525 void module_register(void) {
526   plugin_register_complex_config(MCELOG_PLUGIN, mcelog_config);
527   plugin_register_init(MCELOG_PLUGIN, mcelog_init);
528   plugin_register_complex_read(NULL, MCELOG_PLUGIN, mcelog_read, 0, NULL);
529   plugin_register_shutdown(MCELOG_PLUGIN, mcelog_shutdown);
530 }