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