Merge pull request #2024 from rpv-tomsk/master-ipmi
[collectd.git] / src / ipmi.c
1 /**
2  * collectd - src/ipmi.c
3  * Copyright (C) 2008-2009  Florian octo Forster
4  * Copyright (C) 2008       Peter Holik
5  * Copyright (C) 2009       Bruno PrĂ©mont
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; only version 2 of the License is applicable.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  *
20  * Authors:
21  *   Florian octo Forster <octo at collectd.org>
22  *   Peter Holik <peter at holik.at>
23  *   Bruno PrĂ©mont <bonbons at linux-vserver.org>
24  *   Pavel Rochnyak <pavel2000 ngs.ru>
25  **/
26
27 #include "collectd.h"
28
29 #include "common.h"
30 #include "plugin.h"
31 #include "utils_ignorelist.h"
32
33 #include <OpenIPMI/ipmi_auth.h>
34 #include <OpenIPMI/ipmi_conn.h>
35 #include <OpenIPMI/ipmi_err.h>
36 #include <OpenIPMI/ipmi_lan.h>
37 #include <OpenIPMI/ipmi_posix.h>
38 #include <OpenIPMI/ipmi_smi.h>
39 #include <OpenIPMI/ipmiif.h>
40
41 #define ERR_BUF_SIZE 1024
42
43 /*
44  * Private data types
45  */
46 struct c_ipmi_sensor_list_s;
47 typedef struct c_ipmi_sensor_list_s c_ipmi_sensor_list_t;
48
49 struct c_ipmi_instance_s {
50   char *name;
51   ignorelist_t *ignorelist;
52   _Bool notify_add;
53   _Bool notify_remove;
54   _Bool notify_notpresent;
55   _Bool notify_conn;
56   _Bool sel_enabled;
57   _Bool sel_clear_event;
58
59   char *host;
60   char *connaddr;
61   char *username;
62   char *password;
63   unsigned int authtype;
64
65   _Bool connected;
66   ipmi_con_t *connection;
67   pthread_mutex_t sensor_list_lock;
68   c_ipmi_sensor_list_t *sensor_list;
69
70   _Bool active;
71   pthread_t thread_id;
72   int init_in_progress;
73
74   struct c_ipmi_instance_s *next;
75 };
76 typedef struct c_ipmi_instance_s c_ipmi_instance_t;
77
78 struct c_ipmi_sensor_list_s {
79   ipmi_sensor_id_t sensor_id;
80   char sensor_name[DATA_MAX_NAME_LEN];
81   char sensor_type[DATA_MAX_NAME_LEN];
82   int sensor_not_present;
83   c_ipmi_sensor_list_t *next;
84   c_ipmi_instance_t *instance;
85   unsigned int use;
86 };
87
88 /*
89  * Module global variables
90  */
91 static os_handler_t *os_handler = NULL;
92 static c_ipmi_instance_t *instances = NULL;
93
94 /*
95  * Misc private functions
96  */
97 static void c_ipmi_error(c_ipmi_instance_t *st, const char *func, int status) {
98   char errbuf[ERR_BUF_SIZE] = {0};
99
100   if (IPMI_IS_OS_ERR(status) || IPMI_IS_RMCPP_ERR(status) ||
101       IPMI_IS_IPMI_ERR(status)) {
102     ipmi_get_error_string(status, errbuf, sizeof(errbuf));
103   }
104
105   if (errbuf[0] == 0) {
106     snprintf(errbuf, sizeof(errbuf), "Unknown error %#x", status);
107   }
108   errbuf[sizeof(errbuf) - 1] = 0;
109
110   ERROR("ipmi plugin: %s failed for `%s`: %s", func, st->name, errbuf);
111 } /* void c_ipmi_error */
112
113 static void c_ipmi_log(os_handler_t *handler, const char *format,
114                        enum ipmi_log_type_e log_type, va_list ap) {
115   char msg[ERR_BUF_SIZE];
116
117   vsnprintf(msg, sizeof(msg), format, ap);
118
119   switch (log_type) {
120   case IPMI_LOG_INFO:
121     INFO("ipmi plugin: %s", msg);
122     break;
123   case IPMI_LOG_WARNING:
124     NOTICE("ipmi plugin: %s", msg);
125     break;
126   case IPMI_LOG_SEVERE:
127     WARNING("ipmi plugin: %s", msg);
128     break;
129   case IPMI_LOG_FATAL:
130     ERROR("ipmi plugin: %s", msg);
131     break;
132   case IPMI_LOG_ERR_INFO:
133     ERROR("ipmi plugin: %s", msg);
134     break;
135 #if COLLECT_DEBUG
136   case IPMI_LOG_DEBUG_START:
137   case IPMI_LOG_DEBUG:
138     DEBUG("ipmi plugin: %s", msg);
139     break;
140   case IPMI_LOG_DEBUG_CONT:
141   case IPMI_LOG_DEBUG_END:
142     DEBUG("%s", msg);
143     break;
144 #else
145   case IPMI_LOG_DEBUG_START:
146   case IPMI_LOG_DEBUG:
147   case IPMI_LOG_DEBUG_CONT:
148   case IPMI_LOG_DEBUG_END:
149     break;
150 #endif
151   }
152 } /* void c_ipmi_log */
153
154 static notification_t c_ipmi_notification_init(c_ipmi_instance_t const *st,
155                                                int severity) {
156   notification_t n = {severity, cdtime(), "", "", "ipmi", "", "", "", NULL};
157
158   sstrncpy(n.host, (st->host != NULL) ? st->host : hostname_g, sizeof(n.host));
159   return n;
160 } /* notification_t c_ipmi_notification_init */
161
162 /*
163  * Sensor handlers
164  */
165 /* Prototype for sensor_list_remove, so sensor_read_handler can call it. */
166 static int sensor_list_remove(c_ipmi_instance_t *st, ipmi_sensor_t *sensor);
167
168 static void sensor_read_handler(ipmi_sensor_t *sensor, int err,
169                                 enum ipmi_value_present_e value_present,
170                                 unsigned int __attribute__((unused)) raw_value,
171                                 double value, ipmi_states_t *states,
172                                 void *user_data) {
173   value_list_t vl = VALUE_LIST_INIT;
174
175   c_ipmi_sensor_list_t *list_item = user_data;
176   c_ipmi_instance_t *st = list_item->instance;
177
178   list_item->use--;
179
180   if (err != 0) {
181     if (IPMI_IS_IPMI_ERR(err) &&
182         IPMI_GET_IPMI_ERR(err) == IPMI_NOT_PRESENT_CC) {
183       if (list_item->sensor_not_present == 0) {
184         list_item->sensor_not_present = 1;
185
186         INFO("ipmi plugin: sensor_read_handler: sensor `%s` of `%s` "
187              "not present.",
188              list_item->sensor_name, st->name);
189
190         if (st->notify_notpresent) {
191           notification_t n = c_ipmi_notification_init(st, NOTIF_WARNING);
192
193           sstrncpy(n.type_instance, list_item->sensor_name,
194                    sizeof(n.type_instance));
195           sstrncpy(n.type, list_item->sensor_type, sizeof(n.type));
196           snprintf(n.message, sizeof(n.message), "sensor %s not present",
197                    list_item->sensor_name);
198
199           plugin_dispatch_notification(&n);
200         }
201       }
202     } else if (IPMI_IS_IPMI_ERR(err) &&
203                IPMI_GET_IPMI_ERR(err) ==
204                    IPMI_NOT_SUPPORTED_IN_PRESENT_STATE_CC) {
205       INFO("ipmi plugin: sensor_read_handler: Sensor `%s` of `%s` not ready.",
206            list_item->sensor_name, st->name);
207     } else if (IPMI_IS_IPMI_ERR(err) &&
208                IPMI_GET_IPMI_ERR(err) == IPMI_TIMEOUT_CC) {
209       INFO("ipmi plugin: sensor_read_handler: Sensor `%s` of `%s` timed out.",
210            list_item->sensor_name, st->name);
211     } else {
212       char errbuf[ERR_BUF_SIZE] = {0};
213       ipmi_get_error_string(err, errbuf, sizeof(errbuf) - 1);
214
215       if (IPMI_IS_IPMI_ERR(err))
216         INFO("ipmi plugin: sensor_read_handler: Sensor `%s` of `%s` failed: "
217              "%s.",
218              list_item->sensor_name, st->name, errbuf);
219       else if (IPMI_IS_OS_ERR(err))
220         INFO("ipmi plugin: sensor_read_handler: Sensor `%s` of `%s` failed: "
221              "%s (%#x).",
222              list_item->sensor_name, st->name, errbuf, IPMI_GET_OS_ERR(err));
223       else if (IPMI_IS_RMCPP_ERR(err))
224         INFO("ipmi plugin: sensor_read_handler: Sensor `%s` of `%s` failed: "
225              "%s.",
226              list_item->sensor_name, st->name, errbuf);
227       else if (IPMI_IS_SOL_ERR(err))
228         INFO("ipmi plugin: sensor_read_handler: Sensor `%s` of `%s` failed: "
229              "%s (%#x).",
230              list_item->sensor_name, st->name, errbuf, IPMI_GET_SOL_ERR(err));
231       else
232         INFO("ipmi plugin: sensor_read_handler: Sensor `%s` of `%s` failed "
233              "with error %#x. of class %#x",
234              list_item->sensor_name, st->name, err & 0xff, err & 0xffffff00);
235     }
236     return;
237   } else if (list_item->sensor_not_present == 1) {
238     list_item->sensor_not_present = 0;
239
240     INFO("ipmi plugin: sensor_read_handler: sensor `%s` of `%s` present.",
241          list_item->sensor_name, st->name);
242
243     if (st->notify_notpresent) {
244       notification_t n = c_ipmi_notification_init(st, NOTIF_OKAY);
245
246       sstrncpy(n.type_instance, list_item->sensor_name,
247                sizeof(n.type_instance));
248       sstrncpy(n.type, list_item->sensor_type, sizeof(n.type));
249       snprintf(n.message, sizeof(n.message), "sensor %s present",
250                list_item->sensor_name);
251
252       plugin_dispatch_notification(&n);
253     }
254   }
255
256   if (value_present != IPMI_BOTH_VALUES_PRESENT) {
257     INFO("ipmi plugin: sensor_read_handler: Removing sensor `%s` of `%s`, "
258          "because it provides %s. If you need this sensor, "
259          "please file a bug report.",
260          list_item->sensor_name, st->name,
261          (value_present == IPMI_RAW_VALUE_PRESENT) ? "only the raw value"
262                                                    : "no value");
263     sensor_list_remove(st, sensor);
264     return;
265   }
266
267   if (!ipmi_is_sensor_scanning_enabled(states)) {
268     DEBUG("ipmi plugin: sensor_read_handler: Skipping sensor `%s` of `%s`, "
269           "it is in 'scanning disabled' state.",
270           list_item->sensor_name, st->name);
271     return;
272   }
273
274   if (ipmi_is_initial_update_in_progress(states)) {
275     DEBUG("ipmi plugin: sensor_read_handler: Skipping sensor `%s` of `%s`, "
276           "it is in 'initial update in progress' state.",
277           list_item->sensor_name, st->name);
278     return;
279   }
280
281   vl.values = &(value_t){.gauge = value};
282   vl.values_len = 1;
283
284   if (st->host != NULL)
285     sstrncpy(vl.host, st->host, sizeof(vl.host));
286   sstrncpy(vl.plugin, "ipmi", sizeof(vl.plugin));
287   sstrncpy(vl.type, list_item->sensor_type, sizeof(vl.type));
288   sstrncpy(vl.type_instance, list_item->sensor_name, sizeof(vl.type_instance));
289
290   plugin_dispatch_values(&vl);
291 } /* void sensor_read_handler */
292
293 static void sensor_get_name(ipmi_sensor_t *sensor, char *buffer, int buf_len) {
294   char temp[DATA_MAX_NAME_LEN] = {0};
295   ipmi_entity_t *ent = ipmi_sensor_get_entity(sensor);
296   const char *entity_id_string = ipmi_entity_get_entity_id_string(ent);
297   char sensor_name[DATA_MAX_NAME_LEN] = "";
298   char *sensor_name_ptr;
299
300   if ((buffer == NULL) || (buf_len == 0))
301     return;
302
303   ipmi_sensor_get_name(sensor, temp, sizeof(temp));
304   temp[sizeof(temp) - 1] = 0;
305
306   if (entity_id_string != NULL && strlen(temp))
307     snprintf(sensor_name, sizeof(sensor_name), "%s %s", temp, entity_id_string);
308   else if (entity_id_string != NULL)
309     sstrncpy(sensor_name, entity_id_string, sizeof(sensor_name));
310   else
311     sstrncpy(sensor_name, temp, sizeof(sensor_name));
312
313   if (strlen(temp)) {
314     sstrncpy(temp, sensor_name, sizeof(temp));
315     sensor_name_ptr = strstr(temp, ").");
316     if (sensor_name_ptr != NULL) {
317       /* If name is something like "foo (123).bar",
318        * change that to "bar (123)".
319        * Both, sensor_name_ptr and sensor_id_ptr point to memory within the
320        * `temp' array, which holds a copy of the current `sensor_name'. */
321       char *sensor_id_ptr;
322
323       /* `sensor_name_ptr' points to ").bar". */
324       sensor_name_ptr[1] = 0;
325       /* `temp' holds "foo (123)\0bar\0". */
326       sensor_name_ptr += 2;
327       /* `sensor_name_ptr' now points to "bar". */
328
329       sensor_id_ptr = strstr(temp, "(");
330       if (sensor_id_ptr != NULL) {
331         /* `sensor_id_ptr' now points to "(123)". */
332         snprintf(sensor_name, sizeof(sensor_name), "%s %s", sensor_name_ptr,
333                  sensor_id_ptr);
334       }
335       /* else: don't touch sensor_name. */
336     }
337   }
338   sstrncpy(buffer, sensor_name, buf_len);
339 }
340
341 static int sensor_list_add(c_ipmi_instance_t *st, ipmi_sensor_t *sensor) {
342   ipmi_sensor_id_t sensor_id;
343   c_ipmi_sensor_list_t *list_item;
344   c_ipmi_sensor_list_t *list_prev;
345
346   char buffer[DATA_MAX_NAME_LEN] = {0};
347   char *sensor_name_ptr = buffer;
348   int sensor_type;
349   const char *type;
350
351   sensor_id = ipmi_sensor_convert_to_id(sensor);
352   sensor_get_name(sensor, buffer, sizeof(buffer));
353
354   DEBUG("ipmi plugin: sensor_list_add: Found sensor `%s` of `%s`,"
355         " Type: %#x"
356         " Event reading type: %#x"
357         " Direction: %#x"
358         " Event support: %#x",
359         sensor_name_ptr, st->name, ipmi_sensor_get_sensor_type(sensor),
360         ipmi_sensor_get_event_reading_type(sensor),
361         ipmi_sensor_get_sensor_direction(sensor),
362         ipmi_sensor_get_event_support(sensor));
363
364   /* Both `ignorelist' and `sensor_name_ptr' may be NULL. */
365   if (ignorelist_match(st->ignorelist, sensor_name_ptr) != 0)
366     return 0;
367
368   /* FIXME: Use rate unit or base unit to scale the value */
369
370   sensor_type = ipmi_sensor_get_sensor_type(sensor);
371
372   /*
373    * ipmitool/lib/ipmi_sdr.c sdr_sensor_has_analog_reading() has a notice
374    * about 'Threshold sensors' and 'analog readings'. Discrete sensor may
375    * have analog data, but discrete sensors support is not implemented
376    * in Collectd yet.
377    *
378    * ipmi_sensor_id_get_reading() supports only 'Threshold' sensors.
379    * See lib/sensor.c:4842, stand_ipmi_sensor_get_reading() for details.
380   */
381   if (!ipmi_sensor_get_is_readable(sensor)) {
382     INFO("ipmi plugin: sensor_list_add: Ignore sensor `%s` of `%s`, "
383          "because it don't readable! Its type: (%#x, %s). ",
384          sensor_name_ptr, st->name, sensor_type,
385          ipmi_sensor_get_sensor_type_string(sensor));
386     return -1;
387   }
388
389   if (ipmi_sensor_get_event_reading_type(sensor) !=
390       IPMI_EVENT_READING_TYPE_THRESHOLD) {
391     INFO("ipmi plugin: sensor_list_add: Ignore sensor `%s` of `%s`, "
392          "because it is discrete (%#x)! Its type: (%#x, %s). ",
393          sensor_name_ptr, st->name, sensor_type,
394          ipmi_sensor_get_event_reading_type(sensor),
395          ipmi_sensor_get_sensor_type_string(sensor));
396     return -1;
397   }
398
399   switch (sensor_type) {
400   case IPMI_SENSOR_TYPE_TEMPERATURE:
401     type = "temperature";
402     break;
403
404   case IPMI_SENSOR_TYPE_VOLTAGE:
405     type = "voltage";
406     break;
407
408   case IPMI_SENSOR_TYPE_CURRENT:
409     type = "current";
410     break;
411
412   case IPMI_SENSOR_TYPE_FAN:
413     type = "fanspeed";
414     break;
415
416   default: {
417     INFO("ipmi plugin: sensor_list_add: Ignore sensor `%s` of `%s`, "
418          "because I don't know how to handle its type (%#x, %s). "
419          "If you need this sensor, please file a bug report.",
420          sensor_name_ptr, st->name, sensor_type,
421          ipmi_sensor_get_sensor_type_string(sensor));
422     return -1;
423   }
424   } /* switch (sensor_type) */
425
426   pthread_mutex_lock(&st->sensor_list_lock);
427
428   list_prev = NULL;
429   for (list_item = st->sensor_list; list_item != NULL;
430        list_item = list_item->next) {
431     if (ipmi_cmp_sensor_id(sensor_id, list_item->sensor_id) == 0)
432       break;
433     list_prev = list_item;
434   } /* for (list_item) */
435
436   if (list_item != NULL) {
437     pthread_mutex_unlock(&st->sensor_list_lock);
438     return 0;
439   }
440
441   list_item = (c_ipmi_sensor_list_t *)calloc(1, sizeof(c_ipmi_sensor_list_t));
442   if (list_item == NULL) {
443     pthread_mutex_unlock(&st->sensor_list_lock);
444     return -1;
445   }
446
447   list_item->instance = st;
448   list_item->sensor_id = ipmi_sensor_convert_to_id(sensor);
449
450   if (list_prev != NULL)
451     list_prev->next = list_item;
452   else
453     st->sensor_list = list_item;
454
455   sstrncpy(list_item->sensor_name, sensor_name_ptr,
456            sizeof(list_item->sensor_name));
457   sstrncpy(list_item->sensor_type, type, sizeof(list_item->sensor_type));
458
459   pthread_mutex_unlock(&st->sensor_list_lock);
460
461   if (st->notify_add && (st->init_in_progress == 0)) {
462     notification_t n = c_ipmi_notification_init(st, NOTIF_OKAY);
463
464     sstrncpy(n.type_instance, list_item->sensor_name, sizeof(n.type_instance));
465     sstrncpy(n.type, list_item->sensor_type, sizeof(n.type));
466     snprintf(n.message, sizeof(n.message), "sensor %s added",
467              list_item->sensor_name);
468
469     plugin_dispatch_notification(&n);
470   }
471
472   return 0;
473 } /* int sensor_list_add */
474
475 static int sensor_list_remove(c_ipmi_instance_t *st, ipmi_sensor_t *sensor) {
476   ipmi_sensor_id_t sensor_id;
477   c_ipmi_sensor_list_t *list_item;
478   c_ipmi_sensor_list_t *list_prev;
479
480   sensor_id = ipmi_sensor_convert_to_id(sensor);
481
482   pthread_mutex_lock(&st->sensor_list_lock);
483
484   list_prev = NULL;
485   for (list_item = st->sensor_list; list_item != NULL;
486        list_item = list_item->next) {
487     if (ipmi_cmp_sensor_id(sensor_id, list_item->sensor_id) == 0)
488       break;
489     list_prev = list_item;
490   } /* for (list_item) */
491
492   if (list_item == NULL) {
493     pthread_mutex_unlock(&st->sensor_list_lock);
494     return -1;
495   }
496
497   if (list_prev == NULL)
498     st->sensor_list = list_item->next;
499   else
500     list_prev->next = list_item->next;
501
502   list_prev = NULL;
503   list_item->next = NULL;
504
505   pthread_mutex_unlock(&st->sensor_list_lock);
506
507   if (st->notify_remove && st->active) {
508     notification_t n = c_ipmi_notification_init(st, NOTIF_WARNING);
509
510     sstrncpy(n.type_instance, list_item->sensor_name, sizeof(n.type_instance));
511     sstrncpy(n.type, list_item->sensor_type, sizeof(n.type));
512     snprintf(n.message, sizeof(n.message), "sensor %s removed",
513              list_item->sensor_name);
514
515     plugin_dispatch_notification(&n);
516   }
517
518   free(list_item);
519   return 0;
520 } /* int sensor_list_remove */
521
522 static int sensor_list_read_all(c_ipmi_instance_t *st) {
523   pthread_mutex_lock(&st->sensor_list_lock);
524
525   for (c_ipmi_sensor_list_t *list_item = st->sensor_list; list_item != NULL;
526        list_item = list_item->next) {
527     DEBUG("ipmi plugin: try read sensor `%s` of `%s`, use: %d",
528           list_item->sensor_name, st->name, list_item->use);
529
530     /* Reading already initiated */
531     if (list_item->use)
532       continue;
533
534     list_item->use++;
535     ipmi_sensor_id_get_reading(list_item->sensor_id, sensor_read_handler,
536                                /* user data = */ (void *)list_item);
537   } /* for (list_item) */
538
539   pthread_mutex_unlock(&st->sensor_list_lock);
540
541   return 0;
542 } /* int sensor_list_read_all */
543
544 static int sensor_list_remove_all(c_ipmi_instance_t *st) {
545   c_ipmi_sensor_list_t *list_item;
546
547   pthread_mutex_lock(&st->sensor_list_lock);
548
549   list_item = st->sensor_list;
550   st->sensor_list = NULL;
551
552   pthread_mutex_unlock(&st->sensor_list_lock);
553
554   while (list_item != NULL) {
555     c_ipmi_sensor_list_t *list_next = list_item->next;
556
557     free(list_item);
558
559     list_item = list_next;
560   } /* while (list_item) */
561
562   return 0;
563 } /* int sensor_list_remove_all */
564
565 static int sensor_convert_threshold_severity(enum ipmi_thresh_e severity) {
566   switch (severity) {
567   case IPMI_LOWER_NON_CRITICAL:
568   case IPMI_UPPER_NON_CRITICAL:
569     return NOTIF_OKAY;
570   case IPMI_LOWER_CRITICAL:
571   case IPMI_UPPER_CRITICAL:
572     return NOTIF_WARNING;
573   case IPMI_LOWER_NON_RECOVERABLE:
574   case IPMI_UPPER_NON_RECOVERABLE:
575     return NOTIF_FAILURE;
576   default:
577     return NOTIF_OKAY;
578   } /* switch (severity) */
579 } /* int sensor_convert_threshold_severity */
580
581 static void add_event_common_data(notification_t *n, ipmi_sensor_t *sensor,
582                                   enum ipmi_event_dir_e dir,
583                                   ipmi_event_t *event) {
584   ipmi_entity_t *ent = ipmi_sensor_get_entity(sensor);
585
586   plugin_notification_meta_add_string(n, "entity_name",
587                                       ipmi_entity_get_entity_id_string(ent));
588   plugin_notification_meta_add_signed_int(n, "entity_id",
589                                           ipmi_entity_get_entity_id(ent));
590   plugin_notification_meta_add_signed_int(n, "entity_instance",
591                                           ipmi_entity_get_entity_instance(ent));
592   plugin_notification_meta_add_boolean(n, "assert", dir == IPMI_ASSERTION);
593
594   if (event)
595     plugin_notification_meta_add_signed_int(n, "event_type",
596                                             ipmi_event_get_type(event));
597 } /* void add_event_sensor_meta_data */
598
599 static int sensor_threshold_event_handler(
600     ipmi_sensor_t *sensor, enum ipmi_event_dir_e dir,
601     enum ipmi_thresh_e threshold, enum ipmi_event_value_dir_e high_low,
602     enum ipmi_value_present_e value_present, unsigned int raw_value,
603     double value, void *cb_data, ipmi_event_t *event) {
604
605   c_ipmi_instance_t *st = cb_data;
606
607   /* From the IPMI specification Chapter 2: Events.
608    * If a callback handles the event, then all future callbacks called due to
609    * the event will receive a NULL for the event. So be ready to handle a NULL
610    * event in all your event handlers. A NULL may also be passed to an event
611    * handler if the callback was not due to an event. */
612   if (event == NULL)
613     return IPMI_EVENT_NOT_HANDLED;
614
615   notification_t n = c_ipmi_notification_init(st, NOTIF_OKAY);
616   /* offset is a table index and it's represented as enum of strings that are
617      organized in the way - high and low for each threshold severity level */
618   unsigned int offset = (2 * threshold) + high_low;
619   unsigned int event_type = ipmi_sensor_get_event_reading_type(sensor);
620   unsigned int sensor_type = ipmi_sensor_get_sensor_type(sensor);
621   const char *event_state =
622       ipmi_get_reading_name(event_type, sensor_type, offset);
623   sensor_get_name(sensor, n.type_instance, sizeof(n.type_instance));
624   if (value_present != IPMI_NO_VALUES_PRESENT)
625     snprintf(n.message, sizeof(n.message),
626              "sensor %s received event: %s, value is %f", n.type_instance,
627              event_state, value);
628   else
629     snprintf(n.message, sizeof(n.message),
630              "sensor %s received event: %s, value not provided",
631              n.type_instance, event_state);
632
633   DEBUG("Threshold event received for sensor %s", n.type_instance);
634
635   sstrncpy(n.type, ipmi_sensor_get_sensor_type_string(sensor), sizeof(n.type));
636   n.severity = sensor_convert_threshold_severity(threshold);
637   n.time = NS_TO_CDTIME_T(ipmi_event_get_timestamp(event));
638
639   plugin_notification_meta_add_string(&n, "severity",
640                                       ipmi_get_threshold_string(threshold));
641   plugin_notification_meta_add_string(&n, "direction",
642                                       ipmi_get_value_dir_string(high_low));
643
644   switch (value_present) {
645   case IPMI_BOTH_VALUES_PRESENT:
646     plugin_notification_meta_add_double(&n, "val", value);
647   /* both values present, so fall-through to add raw value too */
648   case IPMI_RAW_VALUE_PRESENT: {
649     char buf[DATA_MAX_NAME_LEN] = {0};
650     snprintf(buf, sizeof(buf), "0x%2.2x", raw_value);
651     plugin_notification_meta_add_string(&n, "raw", buf);
652   } break;
653   default:
654     break;
655   } /* switch (value_present) */
656
657   add_event_common_data(&n, sensor, dir, event);
658
659   plugin_dispatch_notification(&n);
660   plugin_notification_meta_free(n.meta);
661
662   /* Delete handled ipmi event from the list */
663   if (st->sel_clear_event) {
664     ipmi_event_delete(event, NULL, NULL);
665     return IPMI_EVENT_HANDLED;
666   }
667
668   return IPMI_EVENT_NOT_HANDLED;
669 } /* int sensor_threshold_event_handler */
670
671 static int sensor_discrete_event_handler(ipmi_sensor_t *sensor,
672                                          enum ipmi_event_dir_e dir, int offset,
673                                          int severity, int prev_severity,
674                                          void *cb_data, ipmi_event_t *event) {
675
676   c_ipmi_instance_t *st = cb_data;
677
678   /* From the IPMI specification Chapter 2: Events.
679    * If a callback handles the event, then all future callbacks called due to
680    * the event will receive a NULL for the event. So be ready to handle a NULL
681    * event in all your event handlers. A NULL may also be passed to an event
682    * handler if the callback was not due to an event. */
683   if (event == NULL)
684     return IPMI_EVENT_NOT_HANDLED;
685
686   notification_t n = c_ipmi_notification_init(st, NOTIF_OKAY);
687   unsigned int event_type = ipmi_sensor_get_event_reading_type(sensor);
688   unsigned int sensor_type = ipmi_sensor_get_sensor_type(sensor);
689   const char *event_state =
690       ipmi_get_reading_name(event_type, sensor_type, offset);
691   sensor_get_name(sensor, n.type_instance, sizeof(n.type_instance));
692   snprintf(n.message, sizeof(n.message), "sensor %s received event: %s",
693            n.type_instance, event_state);
694
695   DEBUG("Discrete event received for sensor %s", n.type_instance);
696
697   sstrncpy(n.type, ipmi_sensor_get_sensor_type_string(sensor), sizeof(n.type));
698   n.time = NS_TO_CDTIME_T(ipmi_event_get_timestamp(event));
699
700   plugin_notification_meta_add_signed_int(&n, "offset", offset);
701
702   if (severity != -1)
703     plugin_notification_meta_add_signed_int(&n, "severity", severity);
704
705   if (prev_severity != -1)
706     plugin_notification_meta_add_signed_int(&n, "prevseverity", prev_severity);
707
708   add_event_common_data(&n, sensor, dir, event);
709
710   plugin_dispatch_notification(&n);
711   plugin_notification_meta_free(n.meta);
712
713   /* Delete handled ipmi event from the list */
714   if (st->sel_clear_event) {
715     ipmi_event_delete(event, NULL, NULL);
716     return IPMI_EVENT_HANDLED;
717   }
718
719   return IPMI_EVENT_NOT_HANDLED;
720 } /* int sensor_discrete_event_handler */
721
722 /*
723  * Entity handlers
724  */
725 static void
726 entity_sensor_update_handler(enum ipmi_update_e op,
727                              ipmi_entity_t __attribute__((unused)) * entity,
728                              ipmi_sensor_t *sensor, void *user_data) {
729   c_ipmi_instance_t *st = user_data;
730
731   if ((op == IPMI_ADDED) || (op == IPMI_CHANGED)) {
732     /* Will check for duplicate entries.. */
733     sensor_list_add(st, sensor);
734
735     if (st->sel_enabled) {
736       int status = 0;
737       /* register threshold event if threshold sensor support events */
738       if ((ipmi_sensor_get_event_reading_type(sensor) ==
739            IPMI_EVENT_READING_TYPE_THRESHOLD) &&
740           (ipmi_sensor_get_threshold_access(sensor) !=
741            IPMI_THRESHOLD_ACCESS_SUPPORT_NONE))
742         status = ipmi_sensor_add_threshold_event_handler(
743             sensor, sensor_threshold_event_handler, st);
744       /* register discrete handler if discrete/specific sensor support events */
745       else if (ipmi_sensor_get_event_support(sensor) != IPMI_EVENT_SUPPORT_NONE)
746         status = ipmi_sensor_add_discrete_event_handler(
747             sensor, sensor_discrete_event_handler, st);
748
749       if (status) {
750         char buf[DATA_MAX_NAME_LEN] = {0};
751         sensor_get_name(sensor, buf, sizeof(buf));
752         ERROR("Unable to add sensor %s event handler, status: %d", buf, status);
753       }
754     }
755   } else if (op == IPMI_DELETED) {
756     sensor_list_remove(st, sensor);
757
758     if (st->sel_enabled) {
759       if (ipmi_sensor_get_event_reading_type(sensor) ==
760           IPMI_EVENT_READING_TYPE_THRESHOLD)
761         ipmi_sensor_remove_threshold_event_handler(
762             sensor, sensor_threshold_event_handler, st);
763       else
764         ipmi_sensor_remove_discrete_event_handler(
765             sensor, sensor_discrete_event_handler, st);
766     }
767   }
768 } /* void entity_sensor_update_handler */
769
770 /*
771  * Domain handlers
772  */
773 static void
774 domain_entity_update_handler(enum ipmi_update_e op,
775                              ipmi_domain_t __attribute__((unused)) * domain,
776                              ipmi_entity_t *entity, void *user_data) {
777   int status;
778   c_ipmi_instance_t *st = user_data;
779
780   if (op == IPMI_ADDED) {
781     status = ipmi_entity_add_sensor_update_handler(
782         entity, entity_sensor_update_handler, /* user data = */ (void *)st);
783     if (status != 0) {
784       c_ipmi_error(st, "ipmi_entity_add_sensor_update_handler", status);
785     }
786   } else if (op == IPMI_DELETED) {
787     status = ipmi_entity_remove_sensor_update_handler(
788         entity, entity_sensor_update_handler, /* user data = */ (void *)st);
789     if (status != 0) {
790       c_ipmi_error(st, "ipmi_entity_remove_sensor_update_handler", status);
791     }
792   }
793 } /* void domain_entity_update_handler */
794
795 static void smi_event_handler(ipmi_con_t __attribute__((unused)) * ipmi,
796                               const ipmi_addr_t __attribute__((unused)) * addr,
797                               unsigned int __attribute__((unused)) addr_len,
798                               ipmi_event_t *event, void *cb_data) {
799   unsigned int type = ipmi_event_get_type(event);
800   ipmi_domain_t *domain = cb_data;
801
802   DEBUG("%s: Event received: type %u", __FUNCTION__, type);
803
804   if (type != 0x02)
805     /* It's not a standard IPMI event. */
806     return;
807
808   /* force domain to reread SELs */
809   ipmi_domain_reread_sels(domain, NULL, NULL);
810 }
811
812 static void domain_connection_change_handler(ipmi_domain_t *domain, int err,
813                                              unsigned int conn_num,
814                                              unsigned int port_num,
815                                              int still_connected,
816                                              void *user_data) {
817
818   DEBUG("domain_connection_change_handler (domain = %p, err = %i, "
819         "conn_num = %u, port_num = %u, still_connected = %i, "
820         "user_data = %p);",
821         (void *)domain, err, conn_num, port_num, still_connected, user_data);
822
823   c_ipmi_instance_t *st = user_data;
824
825   if (err != 0)
826     c_ipmi_error(st, "domain_connection_change_handler", err);
827
828   if (!still_connected) {
829
830     if (st->notify_conn && st->connected && st->init_in_progress == 0) {
831       notification_t n = c_ipmi_notification_init(st, NOTIF_FAILURE);
832
833       sstrncpy(n.message, "IPMI connection lost", sizeof(n.plugin));
834
835       plugin_dispatch_notification(&n);
836     }
837
838     st->connected = 0;
839     return;
840   }
841
842   if (st->notify_conn && !st->connected && st->init_in_progress == 0) {
843     notification_t n = c_ipmi_notification_init(st, NOTIF_OKAY);
844
845     sstrncpy(n.message, "IPMI connection restored", sizeof(n.plugin));
846
847     plugin_dispatch_notification(&n);
848   }
849
850   st->connected = 1;
851
852   int status = ipmi_domain_add_entity_update_handler(
853       domain, domain_entity_update_handler, /* user data = */ st);
854   if (status != 0) {
855     c_ipmi_error(st, "ipmi_domain_add_entity_update_handler", status);
856   }
857
858   status = st->connection->add_event_handler(st->connection, smi_event_handler,
859                                              (void *)domain);
860
861   if (status != 0)
862     c_ipmi_error(st, "Failed to register smi event handler", status);
863 } /* void domain_connection_change_handler */
864
865 static int c_ipmi_thread_init(c_ipmi_instance_t *st) {
866   ipmi_domain_id_t domain_id;
867   int status;
868
869   if (st->connaddr != NULL) {
870     status = ipmi_ip_setup_con(
871         &st->connaddr, &(char *){IPMI_LAN_STD_PORT_STR}, 1, st->authtype,
872         (unsigned int)IPMI_PRIVILEGE_USER, st->username, strlen(st->username),
873         st->password, strlen(st->password), os_handler,
874         /* user data = */ NULL, &st->connection);
875     if (status != 0) {
876       c_ipmi_error(st, "ipmi_ip_setup_con", status);
877       return -1;
878     }
879   } else {
880     status = ipmi_smi_setup_con(/* if_num = */ 0, os_handler,
881                                 /* user data = */ NULL, &st->connection);
882     if (status != 0) {
883       c_ipmi_error(st, "ipmi_smi_setup_con", status);
884       return -1;
885     }
886   }
887
888   ipmi_open_option_t opts[] = {
889       {.option = IPMI_OPEN_OPTION_ALL, {.ival = 1}},
890 #ifdef IPMI_OPEN_OPTION_USE_CACHE
891       /* OpenIPMI-2.0.17 and later: Disable SDR cache in local file */
892       {.option = IPMI_OPEN_OPTION_USE_CACHE, {.ival = 0}},
893 #endif
894   };
895
896   /*
897    * NOTE: Domain names must be unique. There is static `domains_list` common
898    * to all threads inside lib/domain.c and some ops are done by name.
899    */
900   status = ipmi_open_domain(
901       st->name, &st->connection, /* num_con = */ 1,
902       domain_connection_change_handler, /* user data = */ (void *)st,
903       /* domain_fully_up_handler = */ NULL, /* user data = */ NULL, opts,
904       STATIC_ARRAY_SIZE(opts), &domain_id);
905   if (status != 0) {
906     c_ipmi_error(st, "ipmi_open_domain", status);
907     return -1;
908   }
909
910   return 0;
911 } /* int c_ipmi_thread_init */
912
913 static void *c_ipmi_thread_main(void *user_data) {
914   c_ipmi_instance_t *st = user_data;
915
916   int status = c_ipmi_thread_init(st);
917   if (status != 0) {
918     ERROR("ipmi plugin: c_ipmi_thread_init failed.");
919     st->active = 0;
920     return (void *)-1;
921   }
922
923   while (st->active != 0) {
924     struct timeval tv = {1, 0};
925     os_handler->perform_one_op(os_handler, &tv);
926   }
927   return (void *)0;
928 } /* void *c_ipmi_thread_main */
929
930 static c_ipmi_instance_t *c_ipmi_init_instance() {
931   c_ipmi_instance_t *st;
932
933   st = calloc(1, sizeof(*st));
934   if (st == NULL) {
935     ERROR("ipmi plugin: calloc failed.");
936     return NULL;
937   }
938
939   st->name = strdup("main");
940   if (st->name == NULL) {
941     sfree(st);
942     ERROR("ipmi plugin: strdup() failed.");
943     return NULL;
944   }
945
946   st->ignorelist = ignorelist_create(/* invert = */ 1);
947   if (st->ignorelist == NULL) {
948     sfree(st->name);
949     sfree(st);
950     ERROR("ipmi plugin: ignorelist_create() failed.");
951     return NULL;
952   }
953
954   st->sensor_list = NULL;
955   pthread_mutex_init(&st->sensor_list_lock, /* attr = */ NULL);
956
957   st->host = NULL;
958   st->connaddr = NULL;
959   st->username = NULL;
960   st->password = NULL;
961   st->authtype = IPMI_AUTHTYPE_DEFAULT;
962
963   st->next = NULL;
964
965   return st;
966 } /* c_ipmi_instance_t *c_ipmi_init_instance */
967
968 static void c_ipmi_free_instance(c_ipmi_instance_t *st) {
969   if (st == NULL)
970     return;
971
972   assert(st->next == NULL);
973
974   sfree(st->name);
975   sfree(st->host);
976   sfree(st->connaddr);
977   sfree(st->username);
978   sfree(st->password);
979
980   ignorelist_free(st->ignorelist);
981   pthread_mutex_destroy(&st->sensor_list_lock);
982   sfree(st);
983 } /* void c_ipmi_free_instance */
984
985 static void c_ipmi_add_instance(c_ipmi_instance_t *instance) {
986   if (instances == NULL) {
987     instances = instance;
988     return;
989   }
990
991   c_ipmi_instance_t *last = instances;
992
993   while (last->next != NULL)
994     last = last->next;
995
996   last->next = instance;
997 } /* void c_ipmi_add_instance */
998
999 static int c_ipmi_config_add_instance(oconfig_item_t *ci) {
1000   int status = 0;
1001   c_ipmi_instance_t *st = c_ipmi_init_instance();
1002   if (st == NULL)
1003     return ENOMEM;
1004
1005   if (strcasecmp(ci->key, "Instance") == 0)
1006     status = cf_util_get_string(ci, &st->name);
1007
1008   if (status != 0) {
1009     c_ipmi_free_instance(st);
1010     return status;
1011   }
1012
1013   for (int i = 0; i < ci->children_num; i++) {
1014     oconfig_item_t *child = ci->children + i;
1015
1016     if (strcasecmp("Sensor", child->key) == 0)
1017       ignorelist_add(st->ignorelist, ci->values[0].value.string);
1018     else if (strcasecmp("IgnoreSelected", child->key) == 0) {
1019       _Bool t;
1020       status = cf_util_get_boolean(child, &t);
1021       if (status != 0)
1022         break;
1023       ignorelist_set_invert(st->ignorelist, /* invert = */ !t);
1024     } else if (strcasecmp("NotifyIPMIConnectionState", child->key) == 0) {
1025       status = cf_util_get_boolean(child, &st->notify_conn);
1026     } else if (strcasecmp("NotifySensorAdd", child->key) == 0) {
1027       status = cf_util_get_boolean(child, &st->notify_add);
1028     } else if (strcasecmp("NotifySensorRemove", child->key) == 0) {
1029       status = cf_util_get_boolean(child, &st->notify_remove);
1030     } else if (strcasecmp("NotifySensorNotPresent", child->key) == 0) {
1031       status = cf_util_get_boolean(child, &st->notify_notpresent);
1032     } else if (strcasecmp("SELEnabled", child->key) == 0) {
1033       status = cf_util_get_boolean(child, &st->sel_enabled);
1034     } else if (strcasecmp("SELClearEvent", child->key) == 0) {
1035       status = cf_util_get_boolean(child, &st->sel_clear_event);
1036     } else if (strcasecmp("Host", child->key) == 0)
1037       status = cf_util_get_string(child, &st->host);
1038     else if (strcasecmp("Address", child->key) == 0)
1039       status = cf_util_get_string(child, &st->connaddr);
1040     else if (strcasecmp("Username", child->key) == 0)
1041       status = cf_util_get_string(child, &st->username);
1042     else if (strcasecmp("Password", child->key) == 0)
1043       status = cf_util_get_string(child, &st->password);
1044     else if (strcasecmp("AuthType", child->key) == 0) {
1045       char tmp[8];
1046       status = cf_util_get_string_buffer(child, tmp, sizeof(tmp));
1047       if (status != 0)
1048         break;
1049
1050       if (strcasecmp("MD5", tmp) == 0)
1051         st->authtype = IPMI_AUTHTYPE_MD5;
1052       else if (strcasecmp("rmcp+", tmp) == 0)
1053         st->authtype = IPMI_AUTHTYPE_RMCP_PLUS;
1054       else
1055         WARNING("ipmi plugin: The value \"%s\" is not valid for the "
1056                 "\"AuthType\" option.",
1057                 tmp);
1058     } else {
1059       WARNING("ipmi plugin: Option `%s' not allowed here.", child->key);
1060       status = -1;
1061     }
1062
1063     if (status != 0)
1064       break;
1065   }
1066
1067   if (status != 0) {
1068     c_ipmi_free_instance(st);
1069     return status;
1070   }
1071
1072   c_ipmi_add_instance(st);
1073
1074   return 0;
1075 } /* int c_ipmi_config_add_instance */
1076
1077 static int c_ipmi_config(oconfig_item_t *ci) {
1078   _Bool have_instance_block = 0;
1079
1080   for (int i = 0; i < ci->children_num; i++) {
1081     oconfig_item_t *child = ci->children + i;
1082
1083     if (strcasecmp("Instance", child->key) == 0) {
1084       int status = c_ipmi_config_add_instance(child);
1085       if (status != 0)
1086         return status;
1087
1088       have_instance_block = 1;
1089     } else if (!have_instance_block) {
1090       /* Non-instance option: Assume legacy configuration (without <Instance />
1091        * blocks) and call c_ipmi_config_add_instance with the <Plugin /> block.
1092        */
1093       WARNING("ipmi plugin: Legacy configuration found! Please update your "
1094               "config file.");
1095       return c_ipmi_config_add_instance(ci);
1096     } else {
1097       WARNING("ipmi plugin: The configuration option "
1098               "\"%s\" is not allowed here. Did you "
1099               "forget to add an <Instance /> block "
1100               "around the configuration?",
1101               child->key);
1102       return -1;
1103     }
1104   } /* for (ci->children) */
1105
1106   return 0;
1107 } /* int c_ipmi_config */
1108
1109 static int c_ipmi_read(user_data_t *user_data) {
1110   c_ipmi_instance_t *st = user_data->data;
1111
1112   if (st->active == 0) {
1113     INFO("ipmi plugin: c_ipmi_read: I'm not active, returning false.");
1114     return -1;
1115   }
1116
1117   if (st->connected == 0)
1118     return 0;
1119
1120   sensor_list_read_all(st);
1121
1122   if (st->init_in_progress > 0)
1123     st->init_in_progress--;
1124   else
1125     st->init_in_progress = 0;
1126
1127   return 0;
1128 } /* int c_ipmi_read */
1129
1130 static int c_ipmi_init(void) {
1131   c_ipmi_instance_t *st;
1132   char callback_name[3 * DATA_MAX_NAME_LEN];
1133
1134   if (os_handler != NULL) {
1135     return 0;
1136   }
1137
1138   os_handler = ipmi_posix_thread_setup_os_handler(SIGIO);
1139   if (os_handler == NULL) {
1140     ERROR("ipmi plugin: ipmi_posix_thread_setup_os_handler failed.");
1141     return -1;
1142   }
1143
1144   os_handler->set_log_handler(os_handler, c_ipmi_log);
1145
1146   if (ipmi_init(os_handler) != 0) {
1147     ERROR("ipmi plugin: ipmi_init() failed.");
1148     os_handler->free_os_handler(os_handler);
1149     return -1;
1150   };
1151
1152   if (instances == NULL) {
1153     /* No instances were configured, let's start a default instance. */
1154     st = c_ipmi_init_instance();
1155     if (st == NULL)
1156       return ENOMEM;
1157
1158     c_ipmi_add_instance(st);
1159   }
1160
1161   /* Don't send `ADD' notifications during startup (~ 1 minute) */
1162   int cycles = 1 + (60 / CDTIME_T_TO_TIME_T(plugin_get_interval()));
1163
1164   st = instances;
1165   while (NULL != st) {
1166     /* The `st->name` is used as "domain name" for ipmi_open_domain().
1167      * That value should be unique, so we do plugin_register_complex_read()
1168      * at first as it checks the uniqueness. */
1169     snprintf(callback_name, sizeof(callback_name), "ipmi/%s", st->name);
1170
1171     user_data_t ud = {
1172         .data = st,
1173     };
1174
1175     int status = plugin_register_complex_read(
1176         /* group     = */ "ipmi",
1177         /* name      = */ callback_name,
1178         /* callback  = */ c_ipmi_read,
1179         /* interval  = */ 0,
1180         /* user_data = */ &ud);
1181
1182     if (status != 0) {
1183       st = st->next;
1184       continue;
1185     }
1186
1187     st->init_in_progress = cycles;
1188     st->active = 1;
1189
1190     status = plugin_thread_create(&st->thread_id, /* attr = */ NULL,
1191                                   c_ipmi_thread_main,
1192                                   /* user data = */ (void *)st, "ipmi");
1193
1194     if (status != 0) {
1195       st->active = 0;
1196       st->thread_id = (pthread_t){0};
1197
1198       plugin_unregister_read(callback_name);
1199
1200       ERROR("ipmi plugin: pthread_create failed for `%s`.", callback_name);
1201     }
1202
1203     st = st->next;
1204   }
1205
1206   return 0;
1207 } /* int c_ipmi_init */
1208
1209 static int c_ipmi_shutdown(void) {
1210   c_ipmi_instance_t *st = instances;
1211   instances = NULL;
1212
1213   while (st != NULL) {
1214     c_ipmi_instance_t *next = st->next;
1215
1216     st->next = NULL;
1217     st->active = 0;
1218
1219     if (!pthread_equal(st->thread_id, (pthread_t){0})) {
1220       pthread_join(st->thread_id, NULL);
1221       st->thread_id = (pthread_t){0};
1222     }
1223
1224     sensor_list_remove_all(st);
1225     c_ipmi_free_instance(st);
1226
1227     st = next;
1228   }
1229
1230   os_handler->free_os_handler(os_handler);
1231   os_handler = NULL;
1232
1233   return 0;
1234 } /* int c_ipmi_shutdown */
1235
1236 void module_register(void) {
1237   plugin_register_complex_config("ipmi", c_ipmi_config);
1238   plugin_register_init("ipmi", c_ipmi_init);
1239   plugin_register_shutdown("ipmi", c_ipmi_shutdown);
1240 } /* void module_register */