Merge pull request #2097 from YmrDtnJu/zfs_arc
[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 int socket_reinit(socket_adapter_t *self) {
156   char errbuff[MCELOG_BUFF_SIZE];
157   int ret = -1;
158   cdtime_t interval = plugin_get_interval();
159   struct timeval socket_timeout = CDTIME_T_TO_TIMEVAL(interval);
160
161   /* synchronization via write lock since sock_fd may be changed here */
162   pthread_rwlock_wrlock(&self->lock);
163   self->sock_fd = socket(PF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
164   if (self->sock_fd < 0) {
165     ERROR("%s: Could not create a socket. %s", MCELOG_PLUGIN,
166           sstrerror(errno, errbuff, sizeof(errbuff)));
167     pthread_rwlock_unlock(&self->lock);
168     return ret;
169   }
170
171   /* Set socket timeout option */
172   if (setsockopt(self->sock_fd, SOL_SOCKET, SO_SNDTIMEO,
173                  &socket_timeout, sizeof(socket_timeout)) < 0)
174     ERROR("%s: Failed to set the socket timeout option.", MCELOG_PLUGIN);
175
176   /* downgrading to read lock due to possible recursive read locks
177    * in self->close(self) call */
178   pthread_rwlock_unlock(&self->lock);
179   pthread_rwlock_rdlock(&self->lock);
180   if (connect(self->sock_fd, (struct sockaddr *)&(self->unix_sock),
181               sizeof(self->unix_sock)) < 0) {
182     ERROR("%s: Failed to connect to mcelog server. %s", MCELOG_PLUGIN,
183           sstrerror(errno, errbuff, sizeof(errbuff)));
184     self->close(self);
185     ret = -1;
186   } else
187     ret = 0;
188
189   pthread_rwlock_unlock(&self->lock);
190   return ret;
191 }
192
193 static void mcelog_dispatch_notification(notification_t n) {
194   sstrncpy(n.host, hostname_g, sizeof(n.host));
195   sstrncpy(n.type, "gauge", sizeof(n.type));
196   plugin_dispatch_notification(&n);
197 }
198
199 static int mcelog_prepare_notification(notification_t *n,
200                                        mcelog_memory_rec_t mr) {
201   if (n == NULL)
202     return (-1);
203
204   if (plugin_notification_meta_add_string(n, MCELOG_SOCKET_STR, mr.location) <
205       0) {
206     ERROR("%s: add memory location meta data failed", MCELOG_PLUGIN);
207     return (-1);
208   }
209   if (strlen(mr.dimm_name) > 0)
210     if (plugin_notification_meta_add_string(n, MCELOG_DIMM_NAME, mr.dimm_name) <
211         0) {
212       ERROR("%s: add DIMM name meta data failed", MCELOG_PLUGIN);
213       return (-1);
214     }
215   if (plugin_notification_meta_add_signed_int(n, MCELOG_CORRECTED_ERR,
216                                               mr.corrected_err_total) < 0) {
217     ERROR("%s: add corrected errors meta data failed", MCELOG_PLUGIN);
218     return (-1);
219   }
220   if (plugin_notification_meta_add_signed_int(
221           n, "corrected memory timed errors", mr.corrected_err_timed) < 0) {
222     ERROR("%s: add corrected timed errors meta data failed", MCELOG_PLUGIN);
223     return (-1);
224   }
225   if (plugin_notification_meta_add_string(n, "corrected errors time period",
226                                           mr.corrected_err_timed_period) < 0) {
227     ERROR("%s: add corrected errors period meta data failed", MCELOG_PLUGIN);
228     return (-1);
229   }
230   if (plugin_notification_meta_add_signed_int(n, MCELOG_UNCORRECTED_ERR,
231                                               mr.uncorrected_err_total) < 0) {
232     ERROR("%s: add corrected errors meta data failed", MCELOG_PLUGIN);
233     return (-1);
234   }
235   if (plugin_notification_meta_add_signed_int(
236           n, "uncorrected memory timed errors", mr.uncorrected_err_timed) < 0) {
237     ERROR("%s: add corrected timed errors meta data failed", MCELOG_PLUGIN);
238     return (-1);
239   }
240   if (plugin_notification_meta_add_string(n, "uncorrected errors time period",
241                                           mr.uncorrected_err_timed_period) <
242       0) {
243     ERROR("%s: add corrected errors period meta data failed", MCELOG_PLUGIN);
244     return (-1);
245   }
246
247   return (0);
248 }
249
250 static int mcelog_submit(mcelog_memory_rec_t mr) {
251
252   value_list_t vl = VALUE_LIST_INIT;
253   vl.values_len = 1;
254   vl.time = cdtime();
255
256   sstrncpy(vl.plugin, MCELOG_PLUGIN, sizeof(vl.plugin));
257   sstrncpy(vl.type, "errors", sizeof(vl.type));
258   if (strlen(mr.dimm_name) > 0) {
259     ssnprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%s_%s",
260               mr.location, mr.dimm_name);
261   } else
262     sstrncpy(vl.plugin_instance, mr.location, sizeof(vl.plugin_instance));
263
264   sstrncpy(vl.type_instance, "corrected_memory_errors",
265            sizeof(vl.type_instance));
266   vl.values = &(value_t){.derive = (derive_t)mr.corrected_err_total};
267   plugin_dispatch_values(&vl);
268
269   ssnprintf(vl.type_instance, sizeof(vl.type_instance),
270             "corrected_memory_errors_in_%s", mr.corrected_err_timed_period);
271   vl.values = &(value_t){.derive = (derive_t)mr.corrected_err_timed};
272   plugin_dispatch_values(&vl);
273
274   sstrncpy(vl.type_instance, "uncorrected_memory_errors",
275            sizeof(vl.type_instance));
276   vl.values = &(value_t){.derive = (derive_t)mr.uncorrected_err_total};
277   plugin_dispatch_values(&vl);
278
279   ssnprintf(vl.type_instance, sizeof(vl.type_instance),
280             "uncorrected_memory_errors_in_%s", mr.uncorrected_err_timed_period);
281   vl.values = &(value_t){.derive = (derive_t)mr.uncorrected_err_timed};
282   plugin_dispatch_values(&vl);
283
284   return 0;
285 }
286
287 static int parse_memory_info(FILE *p_file, mcelog_memory_rec_t *memory_record) {
288   char buf[DATA_MAX_NAME_LEN] = {0};
289   while (fgets(buf, sizeof(buf), p_file)) {
290     /* Got empty line or "done" */
291     if ((!strncmp("\n", buf, strlen(buf))) ||
292         (!strncmp(buf, "done\n", strlen(buf))))
293       return 1;
294     if (strlen(buf) < 5)
295       continue;
296     if (!strncmp(buf, MCELOG_SOCKET_STR, strlen(MCELOG_SOCKET_STR))) {
297       sstrncpy(memory_record->location, buf, strlen(buf));
298       /* replace spaces with '_' */
299       for (size_t i = 0; i < strlen(memory_record->location); i++)
300         if (memory_record->location[i] == ' ')
301           memory_record->location[i] = '_';
302       DEBUG("%s: Got SOCKET INFO %s", MCELOG_PLUGIN, memory_record->location);
303     }
304     if (!strncmp(buf, MCELOG_DIMM_NAME, strlen(MCELOG_DIMM_NAME))) {
305       char *name = NULL;
306       char *saveptr = NULL;
307       name = strtok_r(buf, "\"", &saveptr);
308       if (name != NULL && saveptr != NULL) {
309         name = strtok_r(NULL, "\"", &saveptr);
310         if (name != NULL) {
311           sstrncpy(memory_record->dimm_name, name,
312                    sizeof(memory_record->dimm_name));
313           DEBUG("%s: Got DIMM NAME %s", MCELOG_PLUGIN,
314                 memory_record->dimm_name);
315         }
316       }
317     }
318     if (!strncmp(buf, MCELOG_CORRECTED_ERR, strlen(MCELOG_CORRECTED_ERR))) {
319       /* Get next line*/
320       if (fgets(buf, sizeof(buf), p_file) != NULL) {
321         sscanf(buf, "\t%d total", &(memory_record->corrected_err_total));
322         DEBUG("%s: Got corrected error total %d", MCELOG_PLUGIN,
323               memory_record->corrected_err_total);
324       }
325       if (fgets(buf, sizeof(buf), p_file) != NULL) {
326         sscanf(buf, "\t%d in %s", &(memory_record->corrected_err_timed),
327                memory_record->corrected_err_timed_period);
328         DEBUG("%s: Got timed corrected errors %d in %s", MCELOG_PLUGIN,
329               memory_record->corrected_err_total,
330               memory_record->corrected_err_timed_period);
331       }
332     }
333     if (!strncmp(buf, MCELOG_UNCORRECTED_ERR, strlen(MCELOG_UNCORRECTED_ERR))) {
334       if (fgets(buf, sizeof(buf), p_file) != NULL) {
335         sscanf(buf, "\t%d total", &(memory_record->uncorrected_err_total));
336         DEBUG("%s: Got uncorrected error total %d", MCELOG_PLUGIN,
337               memory_record->uncorrected_err_total);
338       }
339       if (fgets(buf, sizeof(buf), p_file) != NULL) {
340         sscanf(buf, "\t%d in %s", &(memory_record->uncorrected_err_timed),
341                memory_record->uncorrected_err_timed_period);
342         DEBUG("%s: Got timed uncorrected errors %d in %s", MCELOG_PLUGIN,
343               memory_record->uncorrected_err_total,
344               memory_record->uncorrected_err_timed_period);
345       }
346     }
347     memset(buf, 0, sizeof(buf));
348   }
349   /* parsing definitely finished */
350   return 0;
351 }
352
353 static void poll_worker_cleanup(void *arg) {
354   mcelog_thread_running = 0;
355   FILE *p_file = *((FILE **)arg);
356   if (p_file != NULL)
357     fclose(p_file);
358   free(arg);
359 }
360
361 static int socket_receive(socket_adapter_t *self, FILE **pp_file) {
362   int res = -1;
363   pthread_rwlock_rdlock(&self->lock);
364   struct pollfd poll_fd = {
365       .fd = self->sock_fd, .events = POLLIN | POLLPRI,
366   };
367
368   if ((res = poll(&poll_fd, 1, MCELOG_POLL_TIMEOUT)) <= 0) {
369     if (res != 0 && errno != EINTR) {
370       char errbuf[MCELOG_BUFF_SIZE];
371       ERROR("mcelog: poll failed: %s",
372             sstrerror(errno, errbuf, sizeof(errbuf)));
373     }
374     pthread_rwlock_unlock(&self->lock);
375     return res;
376   }
377
378   if (poll_fd.revents & (POLLERR | POLLHUP | POLLNVAL)) {
379     /* connection is broken */
380     ERROR("%s: Connection to socket is broken", MCELOG_PLUGIN);
381     if (poll_fd.revents & (POLLERR | POLLHUP)) {
382       notification_t n = {
383           NOTIF_FAILURE, cdtime(), "", "", MCELOG_PLUGIN, "", "", "", NULL};
384       ssnprintf(n.message, sizeof(n.message),
385                 "Connection to mcelog socket is broken.");
386       sstrncpy(n.type_instance, "mcelog_status", sizeof(n.type_instance));
387       mcelog_dispatch_notification(n);
388     }
389     pthread_rwlock_unlock(&self->lock);
390     return -1;
391   }
392
393   if (!(poll_fd.revents & (POLLIN | POLLPRI))) {
394     INFO("%s: No data to read", MCELOG_PLUGIN);
395     pthread_rwlock_unlock(&self->lock);
396     return 0;
397   }
398
399   if ((*pp_file = fdopen(dup(self->sock_fd), "r")) == NULL)
400     res = -1;
401
402   pthread_rwlock_unlock(&self->lock);
403   return res;
404 }
405
406 static void *poll_worker(__attribute__((unused)) void *arg) {
407   char errbuf[MCELOG_BUFF_SIZE];
408   mcelog_thread_running = 1;
409   FILE **pp_file = calloc(1, sizeof(*pp_file));
410   if (pp_file == NULL) {
411     ERROR("mcelog: memory allocation failed: %s",
412           sstrerror(errno, errbuf, sizeof(errbuf)));
413     pthread_exit((void *)1);
414   }
415
416   pthread_cleanup_push(poll_worker_cleanup, pp_file);
417
418   while (1) {
419     int res = 0;
420     /* blocking call */
421     res = socket_adapter.receive(&socket_adapter, pp_file);
422     if (res < 0) {
423       socket_adapter.close(&socket_adapter);
424       if (socket_adapter.reinit(&socket_adapter) != 0) {
425         socket_adapter.close(&socket_adapter);
426         usleep(MCELOG_POLL_TIMEOUT);
427       }
428       continue;
429     }
430     /* timeout or no data to read */
431     else if (res == 0)
432       continue;
433
434     if (*pp_file == NULL)
435       continue;
436
437     mcelog_memory_rec_t memory_record = {0};
438     while (parse_memory_info(*pp_file, &memory_record)) {
439       notification_t n = {NOTIF_OKAY, cdtime(), "", "",  MCELOG_PLUGIN,
440                           "",         "",       "", NULL};
441       ssnprintf(n.message, sizeof(n.message), "Got memory errors info.");
442       sstrncpy(n.type_instance, "memory_erros", sizeof(n.type_instance));
443       if (mcelog_prepare_notification(&n, memory_record) == 0)
444         mcelog_dispatch_notification(n);
445       if (mcelog_submit(memory_record) != 0)
446         ERROR("%s: Failed to submit memory errors", MCELOG_PLUGIN);
447       memset(&memory_record, 0, sizeof(memory_record));
448     }
449
450     fclose(*pp_file);
451     *pp_file = NULL;
452   }
453
454   mcelog_thread_running = 0;
455   pthread_cleanup_pop(1);
456   return NULL;
457 }
458
459 static int mcelog_init(void) {
460   if (socket_adapter.reinit(&socket_adapter) != 0) {
461     ERROR("%s: Cannot connect to client socket", MCELOG_PLUGIN);
462     return -1;
463   }
464
465   if (plugin_thread_create(&g_mcelog_config.tid, NULL, poll_worker, NULL,
466                            NULL) != 0) {
467     ERROR("%s: Error creating poll thread.", MCELOG_PLUGIN);
468     return -1;
469   }
470   return 0;
471 }
472
473 static int get_memory_machine_checks(void) {
474   static const char dump[] = "dump all bios\n";
475   int ret = socket_adapter.write(&socket_adapter, dump, sizeof(dump));
476   if (ret != 0)
477     ERROR("%s: SENT DUMP REQUEST FAILED", MCELOG_PLUGIN);
478   else
479     DEBUG("%s: SENT DUMP REQUEST OK", MCELOG_PLUGIN);
480   return ret;
481 }
482
483 static int mcelog_read(__attribute__((unused)) user_data_t *ud) {
484   DEBUG("%s: %s", MCELOG_PLUGIN, __FUNCTION__);
485
486   if (get_memory_machine_checks() != 0)
487     ERROR("%s: MACHINE CHECK INFO NOT AVAILABLE", MCELOG_PLUGIN);
488
489   return 0;
490 }
491
492 static int mcelog_shutdown(void) {
493   int ret = 0;
494   if (mcelog_thread_running) {
495     pthread_cancel(g_mcelog_config.tid);
496     if (pthread_join(g_mcelog_config.tid, NULL) != 0) {
497       ERROR("%s: Stopping thread failed.", MCELOG_PLUGIN);
498       ret = -1;
499     }
500   }
501
502   ret = socket_adapter.close(&socket_adapter) || ret;
503   pthread_rwlock_destroy(&(socket_adapter.lock));
504   return -ret;
505 }
506
507 void module_register(void) {
508   plugin_register_complex_config(MCELOG_PLUGIN, mcelog_config);
509   plugin_register_init(MCELOG_PLUGIN, mcelog_init);
510   plugin_register_complex_read(NULL, MCELOG_PLUGIN, mcelog_read, 0, NULL);
511   plugin_register_shutdown(MCELOG_PLUGIN, mcelog_shutdown);
512 }