cc2035787ea8fb1a595ad4a0ba9e2e52fabef50e
[collectd.git] / src / apcups.c
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  **/
26
27 #include "collectd.h"
28
29 #include "common.h"      /* rrd_update_file */
30 #include "plugin.h"      /* plugin_register, plugin_submit */
31 #include "configfile.h"  /* cf_register */
32
33 #if HAVE_SYS_TYPES_H
34 # include <sys/types.h>
35 #endif
36 #if HAVE_NETDB_H
37 # include <netdb.h>
38 #endif
39
40 #if HAVE_NETINET_IN_H
41 # include <netinet/in.h>
42 #endif
43
44 #ifndef APCUPS_SERVER_TIMEOUT
45 # define APCUPS_SERVER_TIMEOUT 15.0
46 #endif
47
48 #ifndef APCUPS_DEFAULT_NODE
49 # define APCUPS_DEFAULT_NODE "localhost"
50 #endif
51
52 #ifndef APCUPS_DEFAULT_SERVICE
53 # define APCUPS_DEFAULT_SERVICE "3551"
54 #endif
55
56 /*
57  * Private data types
58  */
59 struct apc_detail_s
60 {
61         double linev;
62         double loadpct;
63         double bcharge;
64         double timeleft;
65         double outputv;
66         double itemp;
67         double battv;
68         double linefreq;
69 };
70
71 /*
72  * Private variables
73  */
74 /* Default values for contacting daemon */
75 static char *conf_node = NULL;
76 static char *conf_service = NULL;
77 /* Defaults to false for backwards compatibility. */
78 static _Bool conf_report_seconds = 0;
79 static _Bool conf_persistent_conn = 1;
80
81 static int global_sockfd = -1;
82
83 static int count_retries = 0;
84 static int count_iterations = 0;
85
86 static int net_shutdown (int *fd)
87 {
88         uint16_t packet_size = 0;
89
90         if ((fd == NULL) || (*fd < 0))
91                 return (EINVAL);
92
93         (void)swrite (*fd, (void *) &packet_size, sizeof (packet_size));
94         close (*fd);
95         *fd = -1;
96
97         return (0);
98 } /* int net_shutdown */
99
100 /* Close the network connection */
101 static int apcups_shutdown (void)
102 {
103         if (global_sockfd < 0)
104                 return (0);
105
106         net_shutdown (&global_sockfd);
107         return (0);
108 } /* int apcups_shutdown */
109
110 /*
111  * Open a TCP connection to the UPS network server
112  * Returns -1 on error
113  * Returns socket file descriptor otherwise
114  */
115 static int net_open (char const *node, char const *service)
116 {
117         int              sd;
118         int              status;
119         struct addrinfo *ai_return;
120         struct addrinfo *ai_list;
121
122         /* TODO: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
123         struct addrinfo ai_hints = {
124                 .ai_family = AF_INET,
125                 .ai_socktype = SOCK_STREAM
126         };
127
128         status = getaddrinfo (node, service, &ai_hints, &ai_return);
129         if (status != 0)
130         {
131                 char errbuf[1024];
132                 INFO ("apcups plugin: getaddrinfo failed: %s",
133                                 (status == EAI_SYSTEM)
134                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
135                                 : gai_strerror (status));
136                 return (-1);
137         }
138
139         /* Create socket */
140         sd = -1;
141         for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
142         {
143                 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
144                 if (sd >= 0)
145                         break;
146         }
147         /* `ai_list' still holds the current description of the socket.. */
148
149         if (sd < 0)
150         {
151                 DEBUG ("apcups plugin: Unable to open a socket");
152                 freeaddrinfo (ai_return);
153                 return (-1);
154         }
155
156         status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
157
158         freeaddrinfo (ai_return);
159
160         if (status != 0) /* `connect(2)' failed */
161         {
162                 char errbuf[1024];
163                 INFO ("apcups plugin: connect failed: %s",
164                                 sstrerror (errno, errbuf, sizeof (errbuf)));
165                 close (sd);
166                 return (-1);
167         }
168
169         DEBUG ("apcups plugin: Done opening a socket %i", sd);
170
171         return (sd);
172 } /* int net_open */
173
174 /*
175  * Receive a message from the other end. Each message consists of
176  * two packets. The first is a header that contains the size
177  * of the data that follows in the second packet.
178  * Returns number of bytes read
179  * Returns 0 on end of file
180  * Returns -1 on hard end of file (i.e. network connection close)
181  * Returns -2 on error
182  */
183 static int net_recv (int *sockfd, char *buf, int buflen)
184 {
185         uint16_t packet_size;
186
187         /* get data size -- in short */
188         if (sread (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
189         {
190                 close (*sockfd);
191                 *sockfd = -1;
192                 return (-1);
193         }
194
195         packet_size = ntohs (packet_size);
196         if (packet_size > buflen)
197         {
198                 ERROR ("apcups plugin: Received %"PRIu16" bytes of payload "
199                                 "but have only %i bytes of buffer available.",
200                                 packet_size, buflen);
201                 close (*sockfd);
202                 *sockfd = -1;
203                 return (-2);
204         }
205
206         if (packet_size == 0)
207                 return (0);
208
209         /* now read the actual data */
210         if (sread (*sockfd, (void *) buf, packet_size) != 0)
211         {
212                 close (*sockfd);
213                 *sockfd = -1;
214                 return (-1);
215         }
216
217         return ((int) packet_size);
218 } /* static int net_recv (int *sockfd, char *buf, int buflen) */
219
220 /*
221  * Send a message over the network. The send consists of
222  * two network packets. The first is sends a short containing
223  * the length of the data packet which follows.
224  * Returns zero on success
225  * Returns non-zero on error
226  */
227 static int net_send (int *sockfd, const char *buff, int len)
228 {
229         uint16_t packet_size;
230
231         assert (len > 0);
232         assert (*sockfd >= 0);
233
234         /* send short containing size of data packet */
235         packet_size = htons ((uint16_t) len);
236
237         if (swrite (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
238         {
239                 close (*sockfd);
240                 *sockfd = -1;
241                 return (-1);
242         }
243
244         /* send data packet */
245         if (swrite (*sockfd, (void *) buff, len) != 0)
246         {
247                 close (*sockfd);
248                 *sockfd = -1;
249                 return (-2);
250         }
251
252         return (0);
253 }
254
255 /* Get and print status from apcupsd NIS server */
256 static int apc_query_server (char const *node, char const *service,
257                 struct apc_detail_s *apcups_detail)
258 {
259         int     n;
260         char    recvline[1024];
261         char   *tokptr;
262         char   *toksaveptr;
263         char   *key;
264         double  value;
265         _Bool retry = 1;
266         int status;
267
268 #if APCMAIN
269 # define PRINT_VALUE(name, val) printf("  Found property: name = %s; value = %f;\n", name, val)
270 #else
271 # define PRINT_VALUE(name, val) /**/
272 #endif
273
274         while (retry)
275         {
276                 if (global_sockfd < 0)
277                 {
278                         global_sockfd = net_open (node, service);
279                         if (global_sockfd < 0)
280                         {
281                                 ERROR ("apcups plugin: Connecting to the "
282                                                 "apcupsd failed.");
283                                 return (-1);
284                         }
285                 }
286
287
288                 status = net_send (&global_sockfd, "status", strlen ("status"));
289                 if (status != 0)
290                 {
291                         /* net_send is closing the socket on error. */
292                         assert (global_sockfd < 0);
293                         if (retry)
294                         {
295                                 retry = 0;
296                                 count_retries++;
297                                 continue;
298                         }
299
300                         ERROR ("apcups plugin: Writing to the socket failed.");
301                         return (-1);
302                 }
303
304                 break;
305         } /* while (retry) */
306
307         /* When collectd's collection interval is larger than apcupsd's
308          * timeout, we would have to retry / re-connect each iteration. Try to
309          * detect this situation and shut down the socket gracefully in that
310          * case. Otherwise, keep the socket open to avoid overhead. */
311         count_iterations++;
312         if ((count_iterations == 10) && (count_retries > 2))
313         {
314                 NOTICE ("apcups plugin: There have been %i retries in the "
315                                 "first %i iterations. Will close the socket "
316                                 "in future iterations.",
317                                 count_retries, count_iterations);
318                 conf_persistent_conn = 0;
319         }
320
321         while ((n = net_recv (&global_sockfd, recvline, sizeof (recvline) - 1)) > 0)
322         {
323                 assert ((size_t)n < sizeof (recvline));
324                 recvline[n] = 0;
325 #if APCMAIN
326                 printf ("net_recv = `%s';\n", recvline);
327 #endif /* if APCMAIN */
328
329                 toksaveptr = NULL;
330                 tokptr = strtok_r (recvline, " :\t", &toksaveptr);
331                 while (tokptr != NULL)
332                 {
333                         key = tokptr;
334                         if ((tokptr = strtok_r (NULL, " :\t", &toksaveptr)) == NULL)
335                                 continue;
336                         value = atof (tokptr);
337
338                         PRINT_VALUE (key, value);
339
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                         }
362
363                         tokptr = strtok_r (NULL, ":", &toksaveptr);
364                 } /* while (tokptr != NULL) */
365         }
366         status = errno; /* save errno, net_shutdown() may re-set it. */
367
368         if (!conf_persistent_conn)
369                 net_shutdown (&global_sockfd);
370
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         }
378
379         return (0);
380 }
381
382 static int apcups_config (oconfig_item_t *ci)
383 {
384         _Bool persistent_conn_set = 0;
385
386         for (int i = 0; i < ci->children_num; i++)
387         {
388                 oconfig_item_t *child = ci->children + i;
389
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         }
403
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         }
414
415         return (0);
416 } /* int apcups_config */
417
418 static void apc_submit_generic (const char *type, const char *type_inst, double value)
419 {
420         value_t values[1];
421         value_list_t vl = VALUE_LIST_INIT;
422
423         values[0].gauge = value;
424
425         vl.values = values;
426         vl.values_len = 1;
427         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
428         sstrncpy (vl.plugin, "apcups", sizeof (vl.plugin));
429         sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
430         sstrncpy (vl.type, type, sizeof (vl.type));
431         sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
432
433         plugin_dispatch_values (&vl);
434 }
435
436 static void apc_submit (struct apc_detail_s *apcups_detail)
437 {
438         apc_submit_generic ("voltage",    "input",   apcups_detail->linev);
439         apc_submit_generic ("voltage",    "output",  apcups_detail->outputv);
440         apc_submit_generic ("voltage",    "battery", apcups_detail->battv);
441         apc_submit_generic ("charge",     "",        apcups_detail->bcharge);
442         apc_submit_generic ("percent",    "load",    apcups_detail->loadpct);
443         apc_submit_generic ("timeleft",   "",        apcups_detail->timeleft);
444         apc_submit_generic ("temperature", "",       apcups_detail->itemp);
445         apc_submit_generic ("frequency",  "input",   apcups_detail->linefreq);
446 }
447
448 static int apcups_read (void)
449 {
450         struct apc_detail_s apcups_detail;
451         int status;
452
453         apcups_detail.linev    =   -1.0;
454         apcups_detail.outputv  =   -1.0;
455         apcups_detail.battv    =   -1.0;
456         apcups_detail.loadpct  =   -1.0;
457         apcups_detail.bcharge  =   -1.0;
458         apcups_detail.timeleft =    NAN;
459         apcups_detail.itemp    = -300.0;
460         apcups_detail.linefreq =   -1.0;
461
462         status = apc_query_server ((conf_node == NULL) ? APCUPS_DEFAULT_NODE : conf_node,
463                         (conf_service == NULL) ? APCUPS_DEFAULT_SERVICE : conf_service,
464                         &apcups_detail);
465
466         /*
467          * if we did not connect then do not bother submitting
468          * zeros. We want rrd files to have NAN.
469          */
470         if (status != 0)
471         {
472                 DEBUG ("apcups plugin: apc_query_server (%s, %s) = %i",
473                                 (conf_node == NULL) ? APCUPS_DEFAULT_NODE : conf_node,
474                                 (conf_service == NULL) ? APCUPS_DEFAULT_SERVICE : conf_service,
475                                 status);
476                 return (-1);
477         }
478
479         apc_submit (&apcups_detail);
480
481         return (0);
482 } /* apcups_read */
483
484 void module_register (void)
485 {
486         plugin_register_complex_config ("apcups", apcups_config);
487         plugin_register_read ("apcups", apcups_read);
488         plugin_register_shutdown ("apcups", apcups_shutdown);
489 } /* void module_register */