mcelog: notification persist option
[collectd.git] / src / mcelog.c
1 /*-
2  * collectd - src/mcelog.c
3  * MIT License
4  *
5  * Copyright(c) 2016-2017 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 "collectd.h"
33
34 #include "common.h"
35 #include "utils_llist.h"
36
37 #include <poll.h>
38 #include <sys/socket.h>
39 #include <sys/un.h>
40 #include <unistd.h>
41
42 #define MCELOG_PLUGIN "mcelog"
43 #define MCELOG_BUFF_SIZE 1024
44 #define MCELOG_POLL_TIMEOUT 1000 /* ms */
45 #define MCELOG_SOCKET_STR "SOCKET"
46 #define MCELOG_DIMM_NAME "DMI_NAME"
47 #define MCELOG_CORRECTED_ERR "corrected memory errors"
48 #define MCELOG_UNCORRECTED_ERR "uncorrected memory errors"
49 #define MCELOG_CORRECTED_ERR_TYPE_INS "corrected_memory_errors"
50 #define MCELOG_UNCORRECTED_ERR_TYPE_INS "uncorrected_memory_errors"
51
52 typedef struct mcelog_config_s {
53   char logfile[PATH_MAX]; /* mcelog logfile */
54   pthread_t tid;          /* poll thread id */
55   llist_t *dimms_list;    /* DIMMs list */
56   /* lock for dimms cache */
57   _Bool persist;
58   pthread_mutex_t dimms_lock;
59 } mcelog_config_t;
60
61 typedef struct socket_adapter_s socket_adapter_t;
62
63 struct socket_adapter_s {
64   int sock_fd;                  /* mcelog server socket fd */
65   struct sockaddr_un unix_sock; /* mcelog client socket */
66   pthread_rwlock_t lock;
67   /* function pointers for socket operations */
68   int (*write)(socket_adapter_t *self, const char *msg, const size_t len);
69   int (*reinit)(socket_adapter_t *self);
70   int (*receive)(socket_adapter_t *self, FILE **p_file);
71   int (*close)(socket_adapter_t *self);
72 };
73
74 typedef struct mcelog_memory_rec_s {
75   int corrected_err_total; /* x total*/
76   int corrected_err_timed; /* x in 24h*/
77   char corrected_err_timed_period[DATA_MAX_NAME_LEN];
78   int uncorrected_err_total; /* x total*/
79   int uncorrected_err_timed; /* x in 24h*/
80   char uncorrected_err_timed_period[DATA_MAX_NAME_LEN];
81   char location[DATA_MAX_NAME_LEN];  /* SOCKET x CHANNEL x DIMM x*/
82   char dimm_name[DATA_MAX_NAME_LEN]; /* DMI_NAME "DIMM_F1" */
83 } mcelog_memory_rec_t;
84
85 static int socket_close(socket_adapter_t *self);
86 static int socket_write(socket_adapter_t *self, const char *msg,
87                         const size_t len);
88 static int socket_reinit(socket_adapter_t *self);
89 static int socket_receive(socket_adapter_t *self, FILE **p_file);
90
91 static mcelog_config_t g_mcelog_config = {
92     .logfile = "/var/log/mcelog", .persist = 0,
93 };
94
95 static socket_adapter_t socket_adapter = {
96     .sock_fd = -1,
97     .unix_sock =
98         {
99             .sun_family = AF_UNIX, .sun_path = "/var/run/mcelog-client",
100         },
101     .lock = PTHREAD_RWLOCK_INITIALIZER,
102     .close = socket_close,
103     .write = socket_write,
104     .reinit = socket_reinit,
105     .receive = socket_receive,
106 };
107
108 static _Bool mcelog_thread_running;
109
110 static void mcelog_free_dimms_list_records(llist_t *dimms_list) {
111
112   for (llentry_t *e = llist_head(dimms_list); e != NULL; e = e->next) {
113     sfree(e->key);
114     sfree(e->value);
115   }
116 }
117
118 /* Create or get dimm by dimm name/location */
119 static llentry_t *mcelog_dimm(const mcelog_memory_rec_t *rec,
120                               llist_t *dimms_list) {
121
122   char dimm_name[DATA_MAX_NAME_LEN];
123
124   if (strlen(rec->dimm_name) > 0) {
125     ssnprintf(dimm_name, sizeof(dimm_name), "%s_%s", rec->location,
126               rec->dimm_name);
127   } else
128     sstrncpy(dimm_name, rec->location, sizeof(dimm_name));
129
130   llentry_t *dimm_le = llist_search(g_mcelog_config.dimms_list, dimm_name);
131
132   if (dimm_le == NULL) {
133     mcelog_memory_rec_t *dimm_mr = calloc(1, sizeof(*dimm_mr));
134     if (dimm_mr == NULL) {
135       ERROR(MCELOG_PLUGIN ": Error allocating dimm memory item");
136       return NULL;
137     }
138     char *p_name = strdup(dimm_name);
139     if (p_name == NULL) {
140       ERROR(MCELOG_PLUGIN ": strdup: error");
141       return NULL;
142     }
143
144     /* add new dimm */
145     dimm_le = llentry_create(p_name, dimm_mr);
146     if (dimm_le == NULL) {
147       ERROR(MCELOG_PLUGIN ": llentry_create(): error");
148       free(dimm_mr);
149       return NULL;
150     }
151     pthread_mutex_lock(&g_mcelog_config.dimms_lock);
152     llist_append(g_mcelog_config.dimms_list, dimm_le);
153     pthread_mutex_unlock(&g_mcelog_config.dimms_lock);
154   }
155
156   return dimm_le;
157 }
158
159 static void mcelog_update_dimm_stats(llentry_t *dimm,
160                                      const mcelog_memory_rec_t *rec) {
161   pthread_mutex_lock(&g_mcelog_config.dimms_lock);
162   memcpy(dimm->value, rec, sizeof(mcelog_memory_rec_t));
163   pthread_mutex_unlock(&g_mcelog_config.dimms_lock);
164 }
165
166 static int mcelog_config(oconfig_item_t *ci) {
167   for (int i = 0; i < ci->children_num; i++) {
168     oconfig_item_t *child = ci->children + i;
169     if (strcasecmp("McelogLogfile", child->key) == 0) {
170       if (cf_util_get_string_buffer(child, g_mcelog_config.logfile,
171                                     sizeof(g_mcelog_config.logfile)) < 0) {
172         ERROR(MCELOG_PLUGIN ": Invalid configuration option: \"%s\".",
173               child->key);
174         return (-1);
175       }
176     } else if (strcasecmp("Memory", child->key) == 0) {
177       oconfig_item_t *mem_child = child->children;
178       for (int j = 0; j < child->children_num; j++) {
179         mem_child += j;
180         if (strcasecmp("McelogClientSocket", mem_child->key) == 0) {
181           if (cf_util_get_string_buffer(
182                   mem_child, socket_adapter.unix_sock.sun_path,
183                   sizeof(socket_adapter.unix_sock.sun_path)) < 0) {
184             ERROR(MCELOG_PLUGIN ": Invalid configuration option: \"%s\".",
185                   mem_child->key);
186             return (-1);
187           }
188         } else if (strcasecmp("PersistentNotification", mem_child->key) == 0) {
189           if (cf_util_get_boolean(mem_child, &g_mcelog_config.persist) < 0) {
190             ERROR(MCELOG_PLUGIN ": Invalid configuration option: \"%s\".",
191                   mem_child->key);
192             return (-1);
193           }
194         } else {
195           ERROR(MCELOG_PLUGIN ": Invalid Memory configuration option: \"%s\".",
196                 mem_child->key);
197           return (-1);
198         }
199       }
200     } else {
201       ERROR(MCELOG_PLUGIN ": Invalid configuration option: \"%s\".",
202             child->key);
203       return (-1);
204     }
205   }
206   return (0);
207 }
208
209 static int socket_close(socket_adapter_t *self) {
210   int ret = 0;
211   pthread_rwlock_rdlock(&self->lock);
212   if (fcntl(self->sock_fd, F_GETFL) != -1) {
213     char errbuf[MCELOG_BUFF_SIZE];
214     if (shutdown(self->sock_fd, SHUT_RDWR) != 0) {
215       ERROR(MCELOG_PLUGIN ": Socket shutdown failed: %s",
216             sstrerror(errno, errbuf, sizeof(errbuf)));
217       ret = -1;
218     }
219     if (close(self->sock_fd) != 0) {
220       ERROR(MCELOG_PLUGIN ": Socket close failed: %s",
221             sstrerror(errno, errbuf, sizeof(errbuf)));
222       ret = -1;
223     }
224   }
225   pthread_rwlock_unlock(&self->lock);
226   return (ret);
227 }
228
229 static int socket_write(socket_adapter_t *self, const char *msg,
230                         const size_t len) {
231   int ret = 0;
232   pthread_rwlock_rdlock(&self->lock);
233   if (swrite(self->sock_fd, msg, len) < 0)
234     ret = -1;
235   pthread_rwlock_unlock(&self->lock);
236   return (ret);
237 }
238
239 static void mcelog_dispatch_notification(notification_t *n) {
240   if (!n) {
241     ERROR(MCELOG_PLUGIN ": %s: NULL pointer", __FUNCTION__);
242     return;
243   }
244
245   sstrncpy(n->host, hostname_g, sizeof(n->host));
246   sstrncpy(n->type, "gauge", sizeof(n->type));
247   plugin_dispatch_notification(n);
248   if (n->meta)
249     plugin_notification_meta_free(n->meta);
250 }
251
252 static int socket_reinit(socket_adapter_t *self) {
253   char errbuff[MCELOG_BUFF_SIZE];
254   int ret = -1;
255   cdtime_t interval = plugin_get_interval();
256   struct timeval socket_timeout = CDTIME_T_TO_TIMEVAL(interval);
257
258   /* synchronization via write lock since sock_fd may be changed here */
259   pthread_rwlock_wrlock(&self->lock);
260   self->sock_fd =
261       socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
262   if (self->sock_fd < 0) {
263     ERROR(MCELOG_PLUGIN ": Could not create a socket. %s",
264           sstrerror(errno, errbuff, sizeof(errbuff)));
265     pthread_rwlock_unlock(&self->lock);
266     return (ret);
267   }
268
269   /* Set socket timeout option */
270   if (setsockopt(self->sock_fd, SOL_SOCKET, SO_SNDTIMEO, &socket_timeout,
271                  sizeof(socket_timeout)) < 0)
272     ERROR(MCELOG_PLUGIN ": Failed to set the socket timeout option.");
273
274   /* downgrading to read lock due to possible recursive read locks
275    * in self->close(self) call */
276   pthread_rwlock_unlock(&self->lock);
277   pthread_rwlock_rdlock(&self->lock);
278   if (connect(self->sock_fd, (struct sockaddr *)&(self->unix_sock),
279               sizeof(self->unix_sock)) < 0) {
280     ERROR(MCELOG_PLUGIN ": Failed to connect to mcelog server. %s",
281           sstrerror(errno, errbuff, sizeof(errbuff)));
282     self->close(self);
283     ret = -1;
284   } else {
285     ret = 0;
286     mcelog_dispatch_notification(
287         &(notification_t){.severity = NOTIF_OKAY,
288                           .time = cdtime(),
289                           .message = "Connected to mcelog server",
290                           .plugin = MCELOG_PLUGIN,
291                           .type_instance = "mcelog_status"});
292   }
293   pthread_rwlock_unlock(&self->lock);
294   return (ret);
295 }
296
297 static int mcelog_dispatch_mem_notifications(const mcelog_memory_rec_t *mr) {
298   notification_t n = {.severity = NOTIF_WARNING,
299                       .time = cdtime(),
300                       .plugin = MCELOG_PLUGIN,
301                       .type = "errors"};
302
303   int dispatch_corrected_notifs = 0, dispatch_uncorrected_notifs = 0;
304
305   if (mr == NULL)
306     return (-1);
307
308   llentry_t *dimm = mcelog_dimm(mr, g_mcelog_config.dimms_list);
309   if (dimm == NULL) {
310     ERROR(MCELOG_PLUGIN
311           ": Error adding/getting dimm memory item to/from cache");
312     return (-1);
313   }
314   mcelog_memory_rec_t *mr_old = dimm->value;
315   if (!g_mcelog_config.persist) {
316
317     if (mr_old->corrected_err_total != mr->corrected_err_total ||
318         mr_old->corrected_err_timed != mr->corrected_err_timed)
319       dispatch_corrected_notifs = 1;
320
321     if (mr_old->uncorrected_err_total != mr->uncorrected_err_total ||
322         mr_old->uncorrected_err_timed != mr->uncorrected_err_timed)
323       dispatch_uncorrected_notifs = 1;
324
325     if (!dispatch_corrected_notifs && !dispatch_uncorrected_notifs) {
326       DEBUG("%s: No new notifications to dispatch", MCELOG_PLUGIN);
327       return (0);
328     }
329   } else {
330     dispatch_corrected_notifs = 1;
331     dispatch_uncorrected_notifs = 1;
332   }
333
334   sstrncpy(n.host, hostname_g, sizeof(n.host));
335
336   if (mr->dimm_name[0] != '\0')
337     ssnprintf(n.plugin_instance, sizeof(n.plugin_instance), "%s_%s",
338               mr->location, mr->dimm_name);
339   else
340     sstrncpy(n.plugin_instance, mr->location, sizeof(n.plugin_instance));
341
342   if (dispatch_corrected_notifs) {
343     /* Corrected Error Notifications */
344     if (mr->corrected_err_total > 0 || mr->corrected_err_timed > 0) {
345       if (plugin_notification_meta_add_signed_int(
346               &n, MCELOG_CORRECTED_ERR, mr->corrected_err_total) < 0) {
347         ERROR(MCELOG_PLUGIN ": add corrected errors meta data failed");
348         plugin_notification_meta_free(n.meta);
349         return (-1);
350       }
351       if (plugin_notification_meta_add_signed_int(
352               &n, "corrected memory timed errors", mr->corrected_err_timed) <
353           0) {
354         ERROR(MCELOG_PLUGIN ": add corrected timed errors meta data failed");
355         plugin_notification_meta_free(n.meta);
356         return (-1);
357       }
358       ssnprintf(n.message, sizeof(n.message), "Corrected Memory Errors");
359       sstrncpy(n.type_instance, MCELOG_CORRECTED_ERR_TYPE_INS,
360                sizeof(n.type_instance));
361       plugin_dispatch_notification(&n);
362
363       if (n.meta)
364         plugin_notification_meta_free(n.meta);
365     }
366   }
367
368   if (dispatch_uncorrected_notifs) {
369     /* Uncorrected Error Notifications */
370     if (mr->uncorrected_err_total > 0 || mr->uncorrected_err_timed > 0) {
371       if (plugin_notification_meta_add_signed_int(
372               &n, MCELOG_UNCORRECTED_ERR, mr->uncorrected_err_total) < 0) {
373         ERROR(MCELOG_PLUGIN ": add uncorrected errors meta data failed");
374         plugin_notification_meta_free(n.meta);
375         return (-1);
376       }
377       if (plugin_notification_meta_add_signed_int(
378               &n, "uncorrected memory timed errors",
379               mr->uncorrected_err_timed) < 0) {
380         ERROR(MCELOG_PLUGIN ": add uncorrected timed errors meta data failed");
381         plugin_notification_meta_free(n.meta);
382         return (-1);
383       }
384       ssnprintf(n.message, sizeof(n.message), "Uncorrected Memory Errors");
385       sstrncpy(n.type_instance, MCELOG_UNCORRECTED_ERR_TYPE_INS,
386                sizeof(n.type_instance));
387       n.severity = NOTIF_FAILURE;
388       plugin_dispatch_notification(&n);
389
390       if (n.meta)
391         plugin_notification_meta_free(n.meta);
392     }
393   }
394
395   return (0);
396 }
397
398 static int mcelog_submit(const mcelog_memory_rec_t *mr) {
399
400   if (!mr) {
401     ERROR(MCELOG_PLUGIN ": %s: NULL pointer", __FUNCTION__);
402     return (-1);
403   }
404
405   llentry_t *dimm = mcelog_dimm(mr, g_mcelog_config.dimms_list);
406   if (dimm == NULL) {
407     ERROR(MCELOG_PLUGIN
408           ": Error adding/getting dimm memory item to/from cache");
409     return (-1);
410   }
411
412   value_list_t vl = {
413       .values_len = 1,
414       .values = &(value_t){.derive = (derive_t)mr->corrected_err_total},
415       .time = cdtime(),
416       .plugin = MCELOG_PLUGIN,
417       .type = "errors",
418       .type_instance = MCELOG_CORRECTED_ERR_TYPE_INS};
419
420   mcelog_update_dimm_stats(dimm, mr);
421
422   if (mr->dimm_name[0] != '\0')
423     ssnprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%s_%s",
424               mr->location, mr->dimm_name);
425   else
426     sstrncpy(vl.plugin_instance, mr->location, sizeof(vl.plugin_instance));
427
428   plugin_dispatch_values(&vl);
429
430   ssnprintf(vl.type_instance, sizeof(vl.type_instance),
431             "corrected_memory_errors_in_%s", mr->corrected_err_timed_period);
432   vl.values = &(value_t){.derive = (derive_t)mr->corrected_err_timed};
433   plugin_dispatch_values(&vl);
434
435   sstrncpy(vl.type_instance, MCELOG_UNCORRECTED_ERR_TYPE_INS,
436            sizeof(vl.type_instance));
437   vl.values = &(value_t){.derive = (derive_t)mr->uncorrected_err_total};
438   plugin_dispatch_values(&vl);
439
440   ssnprintf(vl.type_instance, sizeof(vl.type_instance),
441             "uncorrected_memory_errors_in_%s",
442             mr->uncorrected_err_timed_period);
443   vl.values = &(value_t){.derive = (derive_t)mr->uncorrected_err_timed};
444   plugin_dispatch_values(&vl);
445
446   return (0);
447 }
448
449 static int parse_memory_info(FILE *p_file, mcelog_memory_rec_t *memory_record) {
450   char buf[DATA_MAX_NAME_LEN] = {0};
451   while (fgets(buf, sizeof(buf), p_file)) {
452     /* Got empty line or "done" */
453     if ((!strncmp("\n", buf, strlen(buf))) ||
454         (!strncmp(buf, "done\n", strlen(buf))))
455       return (1);
456     if (strlen(buf) < 5)
457       continue;
458     if (!strncmp(buf, MCELOG_SOCKET_STR, strlen(MCELOG_SOCKET_STR))) {
459       sstrncpy(memory_record->location, buf, strlen(buf));
460       /* replace spaces with '_' */
461       for (size_t i = 0; i < strlen(memory_record->location); i++)
462         if (memory_record->location[i] == ' ')
463           memory_record->location[i] = '_';
464       DEBUG(MCELOG_PLUGIN ": Got SOCKET INFO %s", memory_record->location);
465     }
466     if (!strncmp(buf, MCELOG_DIMM_NAME, strlen(MCELOG_DIMM_NAME))) {
467       char *name = NULL;
468       char *saveptr = NULL;
469       name = strtok_r(buf, "\"", &saveptr);
470       if (name != NULL && saveptr != NULL) {
471         name = strtok_r(NULL, "\"", &saveptr);
472         if (name != NULL) {
473           sstrncpy(memory_record->dimm_name, name,
474                    sizeof(memory_record->dimm_name));
475           DEBUG(MCELOG_PLUGIN ": Got DIMM NAME %s", memory_record->dimm_name);
476         }
477       }
478     }
479     if (!strncmp(buf, MCELOG_CORRECTED_ERR, strlen(MCELOG_CORRECTED_ERR))) {
480       /* Get next line*/
481       if (fgets(buf, sizeof(buf), p_file) != NULL) {
482         sscanf(buf, "\t%d total", &(memory_record->corrected_err_total));
483         DEBUG(MCELOG_PLUGIN ": Got corrected error total %d",
484               memory_record->corrected_err_total);
485       }
486       if (fgets(buf, sizeof(buf), p_file) != NULL) {
487         sscanf(buf, "\t%d in %s", &(memory_record->corrected_err_timed),
488                memory_record->corrected_err_timed_period);
489         DEBUG(MCELOG_PLUGIN ": Got timed corrected errors %d in %s",
490               memory_record->corrected_err_total,
491               memory_record->corrected_err_timed_period);
492       }
493     }
494     if (!strncmp(buf, MCELOG_UNCORRECTED_ERR, strlen(MCELOG_UNCORRECTED_ERR))) {
495       if (fgets(buf, sizeof(buf), p_file) != NULL) {
496         sscanf(buf, "\t%d total", &(memory_record->uncorrected_err_total));
497         DEBUG(MCELOG_PLUGIN ": Got uncorrected error total %d",
498               memory_record->uncorrected_err_total);
499       }
500       if (fgets(buf, sizeof(buf), p_file) != NULL) {
501         sscanf(buf, "\t%d in %s", &(memory_record->uncorrected_err_timed),
502                memory_record->uncorrected_err_timed_period);
503         DEBUG(MCELOG_PLUGIN ": Got timed uncorrected errors %d in %s",
504               memory_record->uncorrected_err_total,
505               memory_record->uncorrected_err_timed_period);
506       }
507     }
508     memset(buf, 0, sizeof(buf));
509   }
510   /* parsing definitely finished */
511   return (0);
512 }
513
514 static void poll_worker_cleanup(void *arg) {
515   mcelog_thread_running = 0;
516   FILE *p_file = *((FILE **)arg);
517   if (p_file != NULL)
518     fclose(p_file);
519   free(arg);
520 }
521
522 static int socket_receive(socket_adapter_t *self, FILE **pp_file) {
523   int res = -1;
524   pthread_rwlock_rdlock(&self->lock);
525   struct pollfd poll_fd = {
526       .fd = self->sock_fd, .events = POLLIN | POLLPRI,
527   };
528
529   if ((res = poll(&poll_fd, 1, MCELOG_POLL_TIMEOUT)) <= 0) {
530     if (res != 0 && errno != EINTR) {
531       char errbuf[MCELOG_BUFF_SIZE];
532       ERROR("mcelog: poll failed: %s",
533             sstrerror(errno, errbuf, sizeof(errbuf)));
534     }
535     pthread_rwlock_unlock(&self->lock);
536     return (res);
537   }
538
539   if (poll_fd.revents & (POLLERR | POLLHUP | POLLNVAL)) {
540     /* connection is broken */
541     ERROR(MCELOG_PLUGIN ": Connection to socket is broken");
542     if (poll_fd.revents & (POLLERR | POLLHUP)) {
543       mcelog_dispatch_notification(
544           &(notification_t){.severity = NOTIF_FAILURE,
545                             .time = cdtime(),
546                             .message = "Connection to mcelog socket is broken.",
547                             .plugin = MCELOG_PLUGIN,
548                             .type_instance = "mcelog_status"});
549     }
550     pthread_rwlock_unlock(&self->lock);
551     return (-1);
552   }
553
554   if (!(poll_fd.revents & (POLLIN | POLLPRI))) {
555     INFO(MCELOG_PLUGIN ": No data to read");
556     pthread_rwlock_unlock(&self->lock);
557     return (0);
558   }
559
560   if ((*pp_file = fdopen(dup(self->sock_fd), "r")) == NULL)
561     res = -1;
562
563   pthread_rwlock_unlock(&self->lock);
564   return (res);
565 }
566
567 static void *poll_worker(__attribute__((unused)) void *arg) {
568   char errbuf[MCELOG_BUFF_SIZE];
569   mcelog_thread_running = 1;
570   FILE **pp_file = calloc(1, sizeof(*pp_file));
571   if (pp_file == NULL) {
572     ERROR("mcelog: memory allocation failed: %s",
573           sstrerror(errno, errbuf, sizeof(errbuf)));
574     pthread_exit((void *)1);
575   }
576
577   pthread_cleanup_push(poll_worker_cleanup, pp_file);
578
579   while (1) {
580     /* blocking call */
581     int res = socket_adapter.receive(&socket_adapter, pp_file);
582     if (res < 0) {
583       socket_adapter.close(&socket_adapter);
584       while (socket_adapter.reinit(&socket_adapter) != 0) {
585         nanosleep(&CDTIME_T_TO_TIMESPEC(MS_TO_CDTIME_T(MCELOG_POLL_TIMEOUT)),
586                   NULL);
587       }
588       continue;
589     }
590     /* timeout or no data to read */
591     else if (res == 0)
592       continue;
593
594     if (*pp_file == NULL)
595       continue;
596
597     mcelog_memory_rec_t memory_record = {0};
598     while (parse_memory_info(*pp_file, &memory_record)) {
599       /* Check if location was successfully parsed */
600       if (memory_record.location[0] == '\0') {
601         memset(&memory_record, 0, sizeof(memory_record));
602         continue;
603       }
604
605       if (mcelog_dispatch_mem_notifications(&memory_record) != 0)
606         ERROR(MCELOG_PLUGIN ": Failed to submit memory errors notification");
607       if (mcelog_submit(&memory_record) != 0)
608         ERROR(MCELOG_PLUGIN ": Failed to submit memory errors");
609       memset(&memory_record, 0, sizeof(memory_record));
610     }
611
612     fclose(*pp_file);
613     *pp_file = NULL;
614   }
615
616   mcelog_thread_running = 0;
617   pthread_cleanup_pop(1);
618   return (NULL);
619 }
620
621 static int mcelog_init(void) {
622   g_mcelog_config.dimms_list = llist_create();
623   int err = pthread_mutex_init(&g_mcelog_config.dimms_lock, NULL);
624   if (err < 0) {
625     ERROR(MCELOG_PLUGIN ": plugin: failed to initialize cache lock");
626     return (-1);
627   }
628
629   if (socket_adapter.reinit(&socket_adapter) != 0) {
630     ERROR(MCELOG_PLUGIN ": Cannot connect to client socket");
631     return (-1);
632   }
633
634   if (plugin_thread_create(&g_mcelog_config.tid, NULL, poll_worker, NULL,
635                            NULL) != 0) {
636     ERROR(MCELOG_PLUGIN ": Error creating poll thread.");
637     return (-1);
638   }
639   return (0);
640 }
641
642 static int get_memory_machine_checks(void) {
643   static const char dump[] = "dump all bios\n";
644   int ret = socket_adapter.write(&socket_adapter, dump, sizeof(dump));
645   if (ret != 0)
646     ERROR(MCELOG_PLUGIN ": SENT DUMP REQUEST FAILED");
647   else
648     DEBUG(MCELOG_PLUGIN ": SENT DUMP REQUEST OK");
649   return (ret);
650 }
651
652 static int mcelog_read(__attribute__((unused)) user_data_t *ud) {
653   DEBUG(MCELOG_PLUGIN ": %s", __FUNCTION__);
654
655   if (get_memory_machine_checks() != 0)
656     ERROR(MCELOG_PLUGIN ": MACHINE CHECK INFO NOT AVAILABLE");
657
658   return (0);
659 }
660
661 static int mcelog_shutdown(void) {
662   int ret = 0;
663   if (mcelog_thread_running) {
664     pthread_cancel(g_mcelog_config.tid);
665     if (pthread_join(g_mcelog_config.tid, NULL) != 0) {
666       ERROR(MCELOG_PLUGIN ": Stopping thread failed.");
667       ret = -1;
668     }
669   }
670   pthread_mutex_lock(&g_mcelog_config.dimms_lock);
671   mcelog_free_dimms_list_records(g_mcelog_config.dimms_list);
672   llist_destroy(g_mcelog_config.dimms_list);
673   pthread_mutex_unlock(&g_mcelog_config.dimms_lock);
674   pthread_mutex_destroy(&g_mcelog_config.dimms_lock);
675   g_mcelog_config.dimms_list = NULL;
676   ret = socket_adapter.close(&socket_adapter) || ret;
677   pthread_rwlock_destroy(&(socket_adapter.lock));
678   return (-ret);
679 }
680
681 void module_register(void) {
682   plugin_register_complex_config(MCELOG_PLUGIN, mcelog_config);
683   plugin_register_init(MCELOG_PLUGIN, mcelog_init);
684   plugin_register_complex_read(NULL, MCELOG_PLUGIN, mcelog_read, 0, NULL);
685   plugin_register_shutdown(MCELOG_PLUGIN, mcelog_shutdown);
686 }