nut plugin: Multi-threaded ups polling with connect timeout.
[collectd.git] / src / nut.c
1 /**
2  * collectd - src/nut.c
3  * Copyright (C) 2007       Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  *   Pavel Rochnyak <pavel2000 ngs.ru>
26  **/
27
28 #include "collectd.h"
29
30 #include "common.h"
31 #include "plugin.h"
32
33 #include <upsclient.h>
34
35 #if HAVE_UPSCONN_T
36 typedef UPSCONN_t collectd_upsconn_t;
37 #elif HAVE_UPSCONN
38 typedef UPSCONN collectd_upsconn_t;
39 #else
40 #error "Unable to determine the UPS connection type."
41 #endif
42
43 struct nut_ups_s;
44 typedef struct nut_ups_s nut_ups_t;
45 struct nut_ups_s {
46   collectd_upsconn_t *conn;
47   char *upsname;
48   char *hostname;
49   int port;
50   nut_ups_t *next;
51 };
52
53 static const char *config_keys[] = {"UPS", "FORCESSL", "VERIFYPEER", "CAPATH",
54                                     "CONNECTTIMEOUT"};
55 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
56 static int force_ssl = 0;   // Initialized to default of 0 (false)
57 static int verify_peer = 0; // Initialized to default of 0 (false)
58 static int ssl_flags = UPSCLI_CONN_TRYSSL;
59 static int connect_timeout = -1;
60 static char *ca_path = NULL;
61
62 static int nut_read(user_data_t *user_data);
63
64 static void free_nut_ups_t(void *arg) {
65   nut_ups_t *ups = arg;
66
67   if (ups->conn != NULL) {
68     upscli_disconnect(ups->conn);
69     sfree(ups->conn);
70   }
71   sfree(ups->hostname);
72   sfree(ups->upsname);
73   sfree(ups);
74 } /* void free_nut_ups_t */
75
76 static int nut_add_ups(const char *name) {
77   nut_ups_t *ups;
78   int status;
79   char *cb_name;
80
81   DEBUG("nut plugin: nut_add_ups (name = %s);", name);
82
83   ups = calloc(1, sizeof(*ups));
84   if (ups == NULL) {
85     ERROR("nut plugin: nut_add_ups: calloc failed.");
86     return 1;
87   }
88
89   status = upscli_splitname(name, &ups->upsname, &ups->hostname, &ups->port);
90   if (status != 0) {
91     ERROR("nut plugin: nut_add_ups: upscli_splitname (%s) failed.", name);
92     free_nut_ups_t(ups);
93     return 1;
94   }
95
96   cb_name = ssnprintf_alloc("nut/%s", name);
97
98   status = plugin_register_complex_read(
99     /* group = */ "nut",
100     /* name      = */ cb_name,
101     /* callback  = */ nut_read,
102     /* interval  = */ 0,
103     /* user_data = */ &(user_data_t){
104                         .data = ups, .free_func = free_nut_ups_t,
105                       });
106
107   sfree(cb_name);
108
109   if (status == EINVAL) {
110     WARNING("nut plugin: UPS \"%s\" already added. "
111             "Please check your configuration.",
112             name);
113     return -1;
114   }
115
116   return 0;
117 } /* int nut_add_ups */
118
119 static int nut_force_ssl(const char *value) {
120   if (strcasecmp(value, "true") == 0)
121     force_ssl = 1;
122   else if (strcasecmp(value, "false") == 0)
123     force_ssl = 0; // Should already be set to 0 from initialization
124   else {
125     force_ssl = 0;
126     WARNING("nut plugin: nut_force_ssl: invalid FORCESSL value "
127             "found. Defaulting to false.");
128   }
129   return 0;
130 } /* int nut_parse_force_ssl */
131
132 static int nut_verify_peer(const char *value) {
133   if (strcasecmp(value, "true") == 0)
134     verify_peer = 1;
135   else if (strcasecmp(value, "false") == 0)
136     verify_peer = 0; // Should already be set to 0 from initialization
137   else {
138     verify_peer = 0;
139     WARNING("nut plugin: nut_verify_peer: invalid VERIFYPEER value "
140             "found. Defaulting to false.");
141   }
142   return 0;
143 } /* int nut_verify_peer */
144
145 static int nut_ca_path(const char *value) {
146   if (value != NULL && strcmp(value, "") != 0) {
147     ca_path = malloc(strlen(value) + 1);
148     strncpy(ca_path, value, (strlen(value) + 1));
149   } else {
150     ca_path = NULL; // Should alread be set to NULL from initialization
151   }
152   return 0;
153 } /* int nut_ca_path */
154
155 static int nut_set_connect_timeout(const char *value) {
156 #if HAVE_UPSCLI_TRYCONNECT
157   long ret;
158
159   errno = 0;
160   ret = strtol(value, /* endptr = */ NULL, /* base = */ 10);
161   if (errno == 0)
162     connect_timeout = ret;
163   else 
164     WARNING("nut plugin: The ConnectTimeout option requires numeric argument. "
165             "Setting ignored.");
166 #else /* #if HAVE_UPSCLI_TRYCONNECT */
167   WARNING("nut plugin: Dependency libupsclient version insufficient (<2.6.2) "
168           "for ConnectTimeout option support. Setting ignored.");
169 #endif
170   return 0;
171 } /* int nut_set_connect_timeout */
172
173 static int nut_config(const char *key, const char *value) {
174   if (strcasecmp(key, "UPS") == 0)
175     return nut_add_ups(value);
176   else if (strcasecmp(key, "FORCESSL") == 0)
177     return nut_force_ssl(value);
178   else if (strcasecmp(key, "VERIFYPEER") == 0)
179     return nut_verify_peer(value);
180   else if (strcasecmp(key, "CAPATH") == 0)
181     return nut_ca_path(value);
182   else if (strcasecmp(key, "CONNECTTIMEOUT") == 0)
183     return nut_set_connect_timeout(value);
184   else
185     return -1;
186 } /* int nut_config */
187
188 static void nut_submit(nut_ups_t *ups, const char *type,
189                        const char *type_instance, gauge_t value) {
190   value_list_t vl = VALUE_LIST_INIT;
191
192   vl.values = &(value_t){.gauge = value};
193   vl.values_len = 1;
194   sstrncpy(vl.host,
195            (strcasecmp(ups->hostname, "localhost") == 0) ? hostname_g
196                                                          : ups->hostname,
197            sizeof(vl.host));
198   sstrncpy(vl.plugin, "nut", sizeof(vl.plugin));
199   sstrncpy(vl.plugin_instance, ups->upsname, sizeof(vl.plugin_instance));
200   sstrncpy(vl.type, type, sizeof(vl.type));
201   sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
202
203   plugin_dispatch_values(&vl);
204 } /* void nut_submit */
205
206 static int nut_connect(nut_ups_t *ups) {
207   int status, ssl_status;
208
209 #if HAVE_UPSCLI_TRYCONNECT
210   struct timeval tv;
211   tv.tv_sec = connect_timeout / 1000;
212   tv.tv_usec = connect_timeout % 1000;
213
214   status = upscli_tryconnect(ups->conn, ups->hostname, ups->port, ssl_flags,
215                              &tv);
216 #else /* #if HAVE_UPSCLI_TRYCONNECT */
217   status = upscli_connect(ups->conn, ups->hostname, ups->port, ssl_flags);
218 #endif
219
220   if (status != 0) {
221     ERROR("nut plugin: nut_connect: upscli_connect (%s, %i) failed: %s",
222           ups->hostname, ups->port, upscli_strerror(ups->conn));
223     sfree(ups->conn);
224     return -1;
225   } /* if (status != 0) */
226
227   INFO("nut plugin: Connection to (%s, %i) established.", ups->hostname,
228        ups->port);
229
230   // Output INFO or WARNING based on SSL and VERIFICATION
231   ssl_status = upscli_ssl(ups->conn); // 1 for SSL, 0 for not, -1 for error
232   if (ssl_status == 1 && verify_peer == 1) {
233     INFO("nut plugin: Connection is secured with SSL and certificate "
234          "has been verified.");
235   } else if (ssl_status == 1) {
236     INFO("nut plugin: Connection is secured with SSL with no verification "
237          "of server SSL certificate.");
238   } else if (ssl_status == 0) {
239     WARNING("nut plugin: Connection is unsecured (no SSL).");
240   } else {
241     ERROR("nut plugin: nut_connect: upscli_ssl failed: %s",
242           upscli_strerror(ups->conn));
243     sfree(ups->conn);
244     return -1;
245   } /* if (ssl_status == 1 && verify_peer == 1) */
246   return 0;
247 }
248
249 static int nut_read(user_data_t *user_data) {
250   nut_ups_t *ups = user_data->data;
251   const char *query[3] = {"VAR", ups->upsname, NULL};
252   unsigned int query_num = 2;
253   char **answer;
254   unsigned int answer_num;
255   int status;
256
257   /* (Re-)Connect if we have no connection */
258   if (ups->conn == NULL) {
259     ups->conn = malloc(sizeof(*ups->conn));
260     if (ups->conn == NULL) {
261       ERROR("nut plugin: malloc failed.");
262       return -1;
263     }
264
265     status = nut_connect(ups);
266     if (status == -1)
267       return -1;
268
269   } /* if (ups->conn == NULL) */
270
271   /* nut plugin: nut_read_one: upscli_list_start (adpos) failed: Protocol
272    * error */
273   status = upscli_list_start(ups->conn, query_num, query);
274   if (status != 0) {
275     ERROR("nut plugin: nut_read: upscli_list_start (%s) failed: %s",
276           ups->upsname, upscli_strerror(ups->conn));
277     upscli_disconnect(ups->conn);
278     sfree(ups->conn);
279     return -1;
280   }
281
282   while ((status = upscli_list_next(ups->conn, query_num, query, &answer_num,
283                                     &answer)) == 1) {
284     char *key;
285     double value;
286
287     if (answer_num < 4)
288       continue;
289
290     key = answer[2];
291     value = atof(answer[3]);
292
293     if (strncmp("ambient.", key, 8) == 0) {
294       if (strcmp("ambient.humidity", key) == 0)
295         nut_submit(ups, "humidity", "ambient", value);
296       else if (strcmp("ambient.temperature", key) == 0)
297         nut_submit(ups, "temperature", "ambient", value);
298     } else if (strncmp("battery.", key, 8) == 0) {
299       if (strcmp("battery.charge", key) == 0)
300         nut_submit(ups, "percent", "charge", value);
301       else if (strcmp("battery.current", key) == 0)
302         nut_submit(ups, "current", "battery", value);
303       else if (strcmp("battery.runtime", key) == 0)
304         nut_submit(ups, "timeleft", "battery", value);
305       else if (strcmp("battery.temperature", key) == 0)
306         nut_submit(ups, "temperature", "battery", value);
307       else if (strcmp("battery.voltage", key) == 0)
308         nut_submit(ups, "voltage", "battery", value);
309     } else if (strncmp("input.", key, 6) == 0) {
310       if (strcmp("input.frequency", key) == 0)
311         nut_submit(ups, "frequency", "input", value);
312       else if (strcmp("input.voltage", key) == 0)
313         nut_submit(ups, "voltage", "input", value);
314     } else if (strncmp("output.", key, 7) == 0) {
315       if (strcmp("output.current", key) == 0)
316         nut_submit(ups, "current", "output", value);
317       else if (strcmp("output.frequency", key) == 0)
318         nut_submit(ups, "frequency", "output", value);
319       else if (strcmp("output.voltage", key) == 0)
320         nut_submit(ups, "voltage", "output", value);
321     } else if (strncmp("ups.", key, 4) == 0) {
322       if (strcmp("ups.load", key) == 0)
323         nut_submit(ups, "percent", "load", value);
324       else if (strcmp("ups.power", key) == 0)
325         nut_submit(ups, "power", "ups", value);
326       else if (strcmp("ups.temperature", key) == 0)
327         nut_submit(ups, "temperature", "ups", value);
328     }
329   } /* while (upscli_list_next) */
330
331   return 0;
332 } /* int nut_read */
333
334 static int nut_init(void) {
335 #if HAVE_UPSCLI_INIT
336   if (verify_peer == 1 && force_ssl == 0) {
337     WARNING("nut plugin: nut_connect: VerifyPeer true but ForceSSL "
338             "false. Setting ForceSSL to true.");
339     force_ssl = 1;
340   }
341
342   if (verify_peer == 1 && ca_path == NULL) {
343     ERROR("nut plugin: nut_connect: VerifyPeer true but missing "
344           "CAPath value.");
345     plugin_unregister_read_group("nut");
346     return -1;
347   }
348
349   if (verify_peer == 1 || force_ssl == 1) {
350     int status = upscli_init(verify_peer, ca_path, NULL, NULL);
351
352     if (status != 1) {
353       ERROR("nut plugin: upscli_init (%i, %s) failed", verify_peer, ca_path);
354       upscli_cleanup();
355       plugin_unregister_read_group("nut");
356       return -1;
357     }
358   } /* if (verify_peer == 1) */
359
360   if (verify_peer == 1)
361     ssl_flags = (UPSCLI_CONN_REQSSL | UPSCLI_CONN_CERTVERIF);
362   else if (force_ssl == 1)
363     ssl_flags = UPSCLI_CONN_REQSSL;
364
365 #else /* #if HAVE_UPSCLI_INIT */
366   if (verify_peer == 1 || ca_path != NULL) {
367     WARNING("nut plugin: nut_connect: Dependency libupsclient version "
368             "insufficient (<2.7) for VerifyPeer support. Ignoring VerifyPeer "
369             "and CAPath.");
370     verify_peer = 0;
371   }
372
373   if (force_ssl == 1)
374     ssl_flags = UPSCLI_CONN_REQSSL;
375 #endif
376
377   if (connect_timeout <= 0)
378     connect_timeout = (long)CDTIME_T_TO_MS(plugin_get_interval());
379
380   return 0;
381 } /* int nut_init */
382
383 static int nut_shutdown(void) {
384 #if HAVE_UPSCLI_INIT
385   upscli_cleanup();
386 #endif
387
388   return 0;
389 } /* int nut_shutdown */
390
391 void module_register(void) {
392   plugin_register_config("nut", nut_config, config_keys, config_keys_num);
393   plugin_register_init("nut", nut_init);
394   plugin_register_shutdown("nut", nut_shutdown);
395 } /* void module_register */