Merge pull request #3329 from efuss/fix-3311
[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 "plugin.h"
31 #include "utils/common/common.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;   // Initialized to default of 0 (false)
57 static int verify_peer; // 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;
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 = */
104       &(user_data_t){
105           .data = ups,
106           .free_func = free_nut_ups_t,
107       });
108
109   sfree(cb_name);
110
111   if (status == EINVAL) {
112     WARNING("nut plugin: UPS \"%s\" already added. "
113             "Please check your configuration.",
114             name);
115     return -1;
116   }
117
118   return 0;
119 } /* int nut_add_ups */
120
121 static int nut_force_ssl(const char *value) {
122   if (strcasecmp(value, "true") == 0)
123     force_ssl = 1;
124   else if (strcasecmp(value, "false") == 0)
125     force_ssl = 0; // Should already be set to 0 from initialization
126   else {
127     force_ssl = 0;
128     WARNING("nut plugin: nut_force_ssl: invalid FORCESSL value "
129             "found. Defaulting to false.");
130   }
131   return 0;
132 } /* int nut_parse_force_ssl */
133
134 static int nut_verify_peer(const char *value) {
135   if (strcasecmp(value, "true") == 0)
136     verify_peer = 1;
137   else if (strcasecmp(value, "false") == 0)
138     verify_peer = 0; // Should already be set to 0 from initialization
139   else {
140     verify_peer = 0;
141     WARNING("nut plugin: nut_verify_peer: invalid VERIFYPEER value "
142             "found. Defaulting to false.");
143   }
144   return 0;
145 } /* int nut_verify_peer */
146
147 static int nut_ca_path(const char *value) {
148   if (value != NULL && strcmp(value, "") != 0) {
149     ca_path = strdup(value);
150   } else {
151     ca_path = NULL; // Should alread be set to NULL from initialization
152   }
153   return 0;
154 } /* int nut_ca_path */
155
156 static int nut_set_connect_timeout(const char *value) {
157 #if HAVE_UPSCLI_TRYCONNECT
158   long ret;
159
160   errno = 0;
161   ret = strtol(value, /* endptr = */ NULL, /* base = */ 10);
162   if (errno == 0)
163     connect_timeout = ret;
164   else
165     WARNING("nut plugin: The ConnectTimeout option requires numeric argument. "
166             "Setting ignored.");
167 #else /* #if HAVE_UPSCLI_TRYCONNECT */
168   WARNING("nut plugin: Dependency libupsclient version insufficient (<2.6.2) "
169           "for ConnectTimeout option support. Setting ignored.");
170 #endif
171   return 0;
172 } /* int nut_set_connect_timeout */
173
174 static int nut_config(const char *key, const char *value) {
175   if (strcasecmp(key, "UPS") == 0)
176     return nut_add_ups(value);
177   else if (strcasecmp(key, "FORCESSL") == 0)
178     return nut_force_ssl(value);
179   else if (strcasecmp(key, "VERIFYPEER") == 0)
180     return nut_verify_peer(value);
181   else if (strcasecmp(key, "CAPATH") == 0)
182     return nut_ca_path(value);
183   else if (strcasecmp(key, "CONNECTTIMEOUT") == 0)
184     return nut_set_connect_timeout(value);
185   else
186     return -1;
187 } /* int nut_config */
188
189 static void nut_submit(nut_ups_t *ups, const char *type,
190                        const char *type_instance, gauge_t value) {
191   value_list_t vl = VALUE_LIST_INIT;
192
193   vl.values = &(value_t){.gauge = value};
194   vl.values_len = 1;
195   if (strcasecmp(ups->hostname, "localhost") != 0)
196     sstrncpy(vl.host, ups->hostname, sizeof(vl.host));
197   sstrncpy(vl.plugin, "nut", sizeof(vl.plugin));
198   sstrncpy(vl.plugin_instance, ups->upsname, sizeof(vl.plugin_instance));
199   sstrncpy(vl.type, type, sizeof(vl.type));
200   sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
201
202   plugin_dispatch_values(&vl);
203 } /* void nut_submit */
204
205 static int nut_connect(nut_ups_t *ups) {
206   int status, ssl_status;
207
208 #if HAVE_UPSCLI_TRYCONNECT
209   struct timeval tv;
210   tv.tv_sec = connect_timeout / 1000;
211   tv.tv_usec = connect_timeout % 1000;
212
213   status =
214       upscli_tryconnect(ups->conn, ups->hostname, ups->port, ssl_flags, &tv);
215 #else /* #if HAVE_UPSCLI_TRYCONNECT */
216   status = upscli_connect(ups->conn, ups->hostname, ups->port, ssl_flags);
217 #endif
218
219   if (status != 0) {
220     ERROR("nut plugin: nut_connect: upscli_connect (%s, %i) failed: %s",
221           ups->hostname, ups->port, upscli_strerror(ups->conn));
222     sfree(ups->conn);
223     return -1;
224   } /* if (status != 0) */
225
226   INFO("nut plugin: Connection to (%s, %i) established.", ups->hostname,
227        ups->port);
228
229   // Output INFO or WARNING based on SSL and VERIFICATION
230   ssl_status = upscli_ssl(ups->conn); // 1 for SSL, 0 for not, -1 for error
231   if (ssl_status == 1 && verify_peer == 1) {
232     INFO("nut plugin: Connection is secured with SSL and certificate "
233          "has been verified.");
234   } else if (ssl_status == 1) {
235     INFO("nut plugin: Connection is secured with SSL with no verification "
236          "of server SSL certificate.");
237   } else if (ssl_status == 0) {
238     WARNING("nut plugin: Connection is unsecured (no SSL).");
239   } else {
240     ERROR("nut plugin: nut_connect: upscli_ssl failed: %s",
241           upscli_strerror(ups->conn));
242     sfree(ups->conn);
243     return -1;
244   } /* if (ssl_status == 1 && verify_peer == 1) */
245   return 0;
246 }
247
248 static int nut_read(user_data_t *user_data) {
249   nut_ups_t *ups = user_data->data;
250   const char *query[3] = {"VAR", ups->upsname, NULL};
251   unsigned int query_num = 2;
252   char **answer;
253   unsigned int answer_num;
254   int status;
255
256   /* (Re-)Connect if we have no connection */
257   if (ups->conn == NULL) {
258     ups->conn = malloc(sizeof(*ups->conn));
259     if (ups->conn == NULL) {
260       ERROR("nut plugin: malloc failed.");
261       return -1;
262     }
263
264     status = nut_connect(ups);
265     if (status == -1)
266       return -1;
267
268   } /* if (ups->conn == NULL) */
269
270   /* nut plugin: nut_read_one: upscli_list_start (adpos) failed: Protocol
271    * error */
272   status = upscli_list_start(ups->conn, query_num, query);
273   if (status != 0) {
274     ERROR("nut plugin: nut_read: upscli_list_start (%s) failed: %s",
275           ups->upsname, upscli_strerror(ups->conn));
276     upscli_disconnect(ups->conn);
277     sfree(ups->conn);
278     return -1;
279   }
280
281   while ((status = upscli_list_next(ups->conn, query_num, query, &answer_num,
282                                     &answer)) == 1) {
283     char *key;
284     double value;
285
286     if (answer_num < 4)
287       continue;
288
289     key = answer[2];
290     value = atof(answer[3]);
291
292     if (strncmp("ambient.", key, 8) == 0) {
293       if (strcmp("ambient.humidity", key) == 0)
294         nut_submit(ups, "humidity", "ambient", value);
295       else if (strcmp("ambient.temperature", key) == 0)
296         nut_submit(ups, "temperature", "ambient", value);
297     } else if (strncmp("battery.", key, 8) == 0) {
298       if (strcmp("battery.charge", key) == 0)
299         nut_submit(ups, "percent", "charge", value);
300       else if (strcmp("battery.current", key) == 0)
301         nut_submit(ups, "current", "battery", value);
302       else if (strcmp("battery.runtime", key) == 0)
303         nut_submit(ups, "timeleft", "battery", value);
304       else if (strcmp("battery.temperature", key) == 0)
305         nut_submit(ups, "temperature", "battery", value);
306       else if (strcmp("battery.voltage", key) == 0)
307         nut_submit(ups, "voltage", "battery", value);
308     } else if (strncmp("input.", key, 6) == 0) {
309       if (strcmp("input.frequency", key) == 0)
310         nut_submit(ups, "frequency", "input", value);
311       else if (strcmp("input.voltage", key) == 0)
312         nut_submit(ups, "voltage", "input", value);
313     } else if (strncmp("output.", key, 7) == 0) {
314       if (strcmp("output.current", key) == 0)
315         nut_submit(ups, "current", "output", value);
316       else if (strcmp("output.frequency", key) == 0)
317         nut_submit(ups, "frequency", "output", value);
318       else if (strcmp("output.voltage", key) == 0)
319         nut_submit(ups, "voltage", "output", value);
320     } else if (strncmp("ups.", key, 4) == 0) {
321       if (strcmp("ups.load", key) == 0)
322         nut_submit(ups, "percent", "load", value);
323       else if (strcmp("ups.power", key) == 0)
324         nut_submit(ups, "power", "ups", value);
325       else if (strcmp("ups.temperature", key) == 0)
326         nut_submit(ups, "temperature", "ups", value);
327     }
328   } /* while (upscli_list_next) */
329
330   return 0;
331 } /* int nut_read */
332
333 static int nut_init(void) {
334 #if HAVE_UPSCLI_INIT
335   if (verify_peer == 1 && force_ssl == 0) {
336     WARNING("nut plugin: nut_connect: VerifyPeer true but ForceSSL "
337             "false. Setting ForceSSL to true.");
338     force_ssl = 1;
339   }
340
341   if (verify_peer == 1 && ca_path == NULL) {
342     ERROR("nut plugin: nut_connect: VerifyPeer true but missing "
343           "CAPath value.");
344     plugin_unregister_read_group("nut");
345     return -1;
346   }
347
348   if (verify_peer == 1 || force_ssl == 1) {
349     int status = upscli_init(verify_peer, ca_path, NULL, NULL);
350
351     if (status != 1) {
352       ERROR("nut plugin: upscli_init (%i, %s) failed", verify_peer, ca_path);
353       upscli_cleanup();
354       plugin_unregister_read_group("nut");
355       return -1;
356     }
357   } /* if (verify_peer == 1) */
358
359   if (verify_peer == 1)
360     ssl_flags = (UPSCLI_CONN_REQSSL | UPSCLI_CONN_CERTVERIF);
361   else if (force_ssl == 1)
362     ssl_flags = UPSCLI_CONN_REQSSL;
363
364 #else /* #if HAVE_UPSCLI_INIT */
365   if (verify_peer == 1 || ca_path != NULL) {
366     WARNING("nut plugin: nut_connect: Dependency libupsclient version "
367             "insufficient (<2.7) for VerifyPeer support. Ignoring VerifyPeer "
368             "and CAPath.");
369     verify_peer = 0;
370   }
371
372   if (force_ssl == 1)
373     ssl_flags = UPSCLI_CONN_REQSSL;
374 #endif
375
376   if (connect_timeout <= 0)
377     connect_timeout = (long)CDTIME_T_TO_MS(plugin_get_interval());
378
379   return 0;
380 } /* int nut_init */
381
382 static int nut_shutdown(void) {
383 #if HAVE_UPSCLI_INIT
384   upscli_cleanup();
385 #endif
386
387   return 0;
388 } /* int nut_shutdown */
389
390 void module_register(void) {
391   plugin_register_config("nut", nut_config, config_keys, config_keys_num);
392   plugin_register_init("nut", nut_init);
393   plugin_register_shutdown("nut", nut_shutdown);
394 } /* void module_register */