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