1 /*
2 * collectd - src/apcups.c
3 * Copyright (C) 2006-2015 Florian octo Forster
4 * Copyright (C) 2006 Anthony Gialluca <tonyabg at charter.net>
5 * Copyright (C) 2000-2004 Kern Sibbald
6 * Copyright (C) 1996-1999 Andre M. Hedrick <andre at suse.com>
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of version 2 of the GNU General
10 * Public License as published by the Free Software Foundation.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public
18 * License along with this program; if not, write to the Free
19 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20 * MA 02111-1307, USA.
21 *
22 * Authors:
23 * Anthony Gialluca <tonyabg at charter.net>
24 * Florian octo Forster <octo at collectd.org>
25 **/
27 #include "collectd.h"
29 #include "common.h" /* rrd_update_file */
30 #include "plugin.h" /* plugin_register, plugin_submit */
32 #if HAVE_SYS_TYPES_H
33 # include <sys/types.h>
34 #endif
35 #if HAVE_NETDB_H
36 # include <netdb.h>
37 #endif
39 #if HAVE_NETINET_IN_H
40 # include <netinet/in.h>
41 #endif
43 #ifndef APCUPS_SERVER_TIMEOUT
44 # define APCUPS_SERVER_TIMEOUT 15.0
45 #endif
47 #ifndef APCUPS_DEFAULT_NODE
48 # define APCUPS_DEFAULT_NODE "localhost"
49 #endif
51 #ifndef APCUPS_DEFAULT_SERVICE
52 # define APCUPS_DEFAULT_SERVICE "3551"
53 #endif
55 /*
56 * Private data types
57 */
58 typedef struct
59 {
60 gauge_t linev;
61 gauge_t loadpct;
62 gauge_t bcharge;
63 gauge_t timeleft;
64 gauge_t outputv;
65 gauge_t itemp;
66 gauge_t battv;
67 gauge_t linefreq;
68 } apc_detail_t;
70 /*
71 * Private variables
72 */
73 /* Default values for contacting daemon */
74 static char *conf_node = NULL;
75 static char *conf_service = NULL;
76 /* Defaults to false for backwards compatibility. */
77 static _Bool conf_report_seconds = 0;
78 static _Bool conf_persistent_conn = 1;
80 static int global_sockfd = -1;
82 static int count_retries = 0;
83 static int count_iterations = 0;
85 static int net_shutdown (int *fd)
86 {
87 uint16_t packet_size = 0;
89 if ((fd == NULL) || (*fd < 0))
90 return (EINVAL);
92 (void)swrite (*fd, (void *) &packet_size, sizeof (packet_size));
93 close (*fd);
94 *fd = -1;
96 return (0);
97 } /* int net_shutdown */
99 /* Close the network connection */
100 static int apcups_shutdown (void)
101 {
102 if (global_sockfd < 0)
103 return (0);
105 net_shutdown (&global_sockfd);
106 return (0);
107 } /* int apcups_shutdown */
109 /*
110 * Open a TCP connection to the UPS network server
111 * Returns -1 on error
112 * Returns socket file descriptor otherwise
113 */
114 static int net_open (char const *node, char const *service)
115 {
116 int sd;
117 int status;
118 struct addrinfo *ai_return;
119 struct addrinfo *ai_list;
121 /* TODO: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
122 struct addrinfo ai_hints = {
123 .ai_family = AF_INET,
124 .ai_socktype = SOCK_STREAM
125 };
127 status = getaddrinfo (node, service, &ai_hints, &ai_return);
128 if (status != 0)
129 {
130 char errbuf[1024];
131 INFO ("apcups plugin: getaddrinfo failed: %s",
132 (status == EAI_SYSTEM)
133 ? sstrerror (errno, errbuf, sizeof (errbuf))
134 : gai_strerror (status));
135 return (-1);
136 }
138 /* Create socket */
139 sd = -1;
140 for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
141 {
142 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
143 if (sd >= 0)
144 break;
145 }
146 /* `ai_list' still holds the current description of the socket.. */
148 if (sd < 0)
149 {
150 DEBUG ("apcups plugin: Unable to open a socket");
151 freeaddrinfo (ai_return);
152 return (-1);
153 }
155 status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
157 freeaddrinfo (ai_return);
159 if (status != 0) /* `connect(2)' failed */
160 {
161 char errbuf[1024];
162 INFO ("apcups plugin: connect failed: %s",
163 sstrerror (errno, errbuf, sizeof (errbuf)));
164 close (sd);
165 return (-1);
166 }
168 DEBUG ("apcups plugin: Done opening a socket %i", sd);
170 return (sd);
171 } /* int net_open */
173 /*
174 * Receive a message from the other end. Each message consists of
175 * two packets. The first is a header that contains the size
176 * of the data that follows in the second packet.
177 * Returns number of bytes read
178 * Returns 0 on end of file
179 * Returns -1 on hard end of file (i.e. network connection close)
180 * Returns -2 on error
181 */
182 static int net_recv (int *sockfd, char *buf, int buflen)
183 {
184 uint16_t packet_size;
186 /* get data size -- in short */
187 if (sread (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
188 {
189 close (*sockfd);
190 *sockfd = -1;
191 return (-1);
192 }
194 packet_size = ntohs (packet_size);
195 if (packet_size > buflen)
196 {
197 ERROR ("apcups plugin: Received %"PRIu16" bytes of payload "
198 "but have only %i bytes of buffer available.",
199 packet_size, buflen);
200 close (*sockfd);
201 *sockfd = -1;
202 return (-2);
203 }
205 if (packet_size == 0)
206 return (0);
208 /* now read the actual data */
209 if (sread (*sockfd, (void *) buf, packet_size) != 0)
210 {
211 close (*sockfd);
212 *sockfd = -1;
213 return (-1);
214 }
216 return ((int) packet_size);
217 } /* static int net_recv (int *sockfd, char *buf, int buflen) */
219 /*
220 * Send a message over the network. The send consists of
221 * two network packets. The first is sends a short containing
222 * the length of the data packet which follows.
223 * Returns zero on success
224 * Returns non-zero on error
225 */
226 static int net_send (int *sockfd, const char *buff, int len)
227 {
228 uint16_t packet_size;
230 assert (len > 0);
231 assert (*sockfd >= 0);
233 /* send short containing size of data packet */
234 packet_size = htons ((uint16_t) len);
236 if (swrite (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
237 {
238 close (*sockfd);
239 *sockfd = -1;
240 return (-1);
241 }
243 /* send data packet */
244 if (swrite (*sockfd, (void *) buff, len) != 0)
245 {
246 close (*sockfd);
247 *sockfd = -1;
248 return (-2);
249 }
251 return (0);
252 }
254 /* Get and print status from apcupsd NIS server */
255 static int apc_query_server (char const *node, char const *service,
256 apc_detail_t *apcups_detail)
257 {
258 int n;
259 char recvline[1024];
260 char *tokptr;
261 char *toksaveptr;
262 _Bool retry = 1;
263 int status;
265 #if APCMAIN
266 # define PRINT_VALUE(name, val) printf(" Found property: name = %s; value = %f;\n", name, val)
267 #else
268 # define PRINT_VALUE(name, val) /**/
269 #endif
271 while (retry)
272 {
273 if (global_sockfd < 0)
274 {
275 global_sockfd = net_open (node, service);
276 if (global_sockfd < 0)
277 {
278 ERROR ("apcups plugin: Connecting to the "
279 "apcupsd failed.");
280 return (-1);
281 }
282 }
285 status = net_send (&global_sockfd, "status", strlen ("status"));
286 if (status != 0)
287 {
288 /* net_send is closing the socket on error. */
289 assert (global_sockfd < 0);
290 if (retry)
291 {
292 retry = 0;
293 count_retries++;
294 continue;
295 }
297 ERROR ("apcups plugin: Writing to the socket failed.");
298 return (-1);
299 }
301 break;
302 } /* while (retry) */
304 /* When collectd's collection interval is larger than apcupsd's
305 * timeout, we would have to retry / re-connect each iteration. Try to
306 * detect this situation and shut down the socket gracefully in that
307 * case. Otherwise, keep the socket open to avoid overhead. */
308 count_iterations++;
309 if ((count_iterations == 10) && (count_retries > 2))
310 {
311 NOTICE ("apcups plugin: There have been %i retries in the "
312 "first %i iterations. Will close the socket "
313 "in future iterations.",
314 count_retries, count_iterations);
315 conf_persistent_conn = 0;
316 }
318 while ((n = net_recv (&global_sockfd, recvline, sizeof (recvline) - 1)) > 0)
319 {
320 assert ((size_t)n < sizeof (recvline));
321 recvline[n] = 0;
322 #if APCMAIN
323 printf ("net_recv = `%s';\n", recvline);
324 #endif /* if APCMAIN */
326 toksaveptr = NULL;
327 tokptr = strtok_r (recvline, " :\t", &toksaveptr);
328 while (tokptr != NULL)
329 {
330 char *key = tokptr;
331 if ((tokptr = strtok_r (NULL, " :\t", &toksaveptr)) == NULL)
332 continue;
334 gauge_t value;
335 if (strtogauge (tokptr, &value) != 0)
336 continue;
338 PRINT_VALUE (key, value);
340 if (strcmp ("LINEV", key) == 0)
341 apcups_detail->linev = value;
342 else if (strcmp ("BATTV", key) == 0)
343 apcups_detail->battv = value;
344 else if (strcmp ("ITEMP", key) == 0)
345 apcups_detail->itemp = value;
346 else if (strcmp ("LOADPCT", key) == 0)
347 apcups_detail->loadpct = value;
348 else if (strcmp ("BCHARGE", key) == 0)
349 apcups_detail->bcharge = value;
350 else if (strcmp ("OUTPUTV", key) == 0)
351 apcups_detail->outputv = value;
352 else if (strcmp ("LINEFREQ", key) == 0)
353 apcups_detail->linefreq = value;
354 else if (strcmp ("TIMELEFT", key) == 0)
355 {
356 /* Convert minutes to seconds if requested by
357 * the user. */
358 if (conf_report_seconds)
359 value *= 60.0;
360 apcups_detail->timeleft = value;
361 }
363 tokptr = strtok_r (NULL, ":", &toksaveptr);
364 } /* while (tokptr != NULL) */
365 }
366 status = errno; /* save errno, net_shutdown() may re-set it. */
368 if (!conf_persistent_conn)
369 net_shutdown (&global_sockfd);
371 if (n < 0)
372 {
373 char errbuf[1024];
374 ERROR ("apcups plugin: Reading from socket failed: %s",
375 sstrerror (status, errbuf, sizeof (errbuf)));
376 return (-1);
377 }
379 return (0);
380 }
382 static int apcups_config (oconfig_item_t *ci)
383 {
384 _Bool persistent_conn_set = 0;
386 for (int i = 0; i < ci->children_num; i++)
387 {
388 oconfig_item_t *child = ci->children + i;
390 if (strcasecmp (child->key, "Host") == 0)
391 cf_util_get_string (child, &conf_node);
392 else if (strcasecmp (child->key, "Port") == 0)
393 cf_util_get_service (child, &conf_service);
394 else if (strcasecmp (child->key, "ReportSeconds") == 0)
395 cf_util_get_boolean (child, &conf_report_seconds);
396 else if (strcasecmp (child->key, "PersistentConnection") == 0) {
397 cf_util_get_boolean (child, &conf_persistent_conn);
398 persistent_conn_set = 1;
399 }
400 else
401 ERROR ("apcups plugin: Unknown config option \"%s\".", child->key);
402 }
404 if (!persistent_conn_set) {
405 double interval = CDTIME_T_TO_DOUBLE(plugin_get_interval());
406 if (interval > APCUPS_SERVER_TIMEOUT) {
407 NOTICE ("apcups plugin: Plugin poll interval set to %.3f seconds. "
408 "Apcupsd NIS socket timeout is %.3f seconds, "
409 "PersistentConnection disabled by default.",
410 interval, APCUPS_SERVER_TIMEOUT);
411 conf_persistent_conn = 0;
412 }
413 }
415 return (0);
416 } /* int apcups_config */
418 static void apc_submit_generic (const char *type, const char *type_inst, gauge_t value)
419 {
420 if (isnan (value))
421 return;
423 value_list_t vl = VALUE_LIST_INIT;
424 vl.values = &(value_t) { .gauge = value };
425 vl.values_len = 1;
426 sstrncpy (vl.plugin, "apcups", sizeof (vl.plugin));
427 sstrncpy (vl.type, type, sizeof (vl.type));
428 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
430 plugin_dispatch_values (&vl);
431 }
433 static void apc_submit (apc_detail_t const *apcups_detail)
434 {
435 apc_submit_generic ("voltage", "input", apcups_detail->linev);
436 apc_submit_generic ("voltage", "output", apcups_detail->outputv);
437 apc_submit_generic ("voltage", "battery", apcups_detail->battv);
438 apc_submit_generic ("charge", "", apcups_detail->bcharge);
439 apc_submit_generic ("percent", "load", apcups_detail->loadpct);
440 apc_submit_generic ("timeleft", "", apcups_detail->timeleft);
441 apc_submit_generic ("temperature", "", apcups_detail->itemp);
442 apc_submit_generic ("frequency", "input", apcups_detail->linefreq);
443 }
445 static int apcups_read (void)
446 {
447 apc_detail_t apcups_detail = {
448 .linev = NAN,
449 .outputv = NAN,
450 .battv = NAN,
451 .loadpct = NAN,
452 .bcharge = NAN,
453 .timeleft = NAN,
454 .itemp = NAN,
455 .linefreq = NAN,
456 };
458 int status = apc_query_server (conf_node == NULL
459 ? APCUPS_DEFAULT_NODE
460 : conf_node,
461 conf_service, &apcups_detail);
462 if (status != 0)
463 {
464 DEBUG ("apcups plugin: apc_query_server (\"%s\", \"%s\") = %d",
465 conf_node == NULL ? APCUPS_DEFAULT_NODE : conf_node,
466 conf_service, status);
467 return (status);
468 }
470 apc_submit (&apcups_detail);
472 return (0);
473 } /* apcups_read */
475 void module_register (void)
476 {
477 plugin_register_complex_config ("apcups", apcups_config);
478 plugin_register_read ("apcups", apcups_read);
479 plugin_register_shutdown ("apcups", apcups_shutdown);
480 } /* void module_register */