Merge branch 'collectd-4.10' into collectd-5.1
[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 verplant.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 struct apc_detail_s
56 {
57         double linev;
58         double loadpct;
59         double bcharge;
60         double timeleft;
61         double outputv;
62         double itemp;
63         double battv;
64         double linefreq;
65 };
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
74 static int global_sockfd = -1;
75
76 static int count_retries = 0;
77 static int count_iterations = 0;
78 static _Bool close_socket = 0;
79
80 static const char *config_keys[] =
81 {
82         "Host",
83         "Port",
84         NULL
85 };
86 static int config_keys_num = 2;
87
88 static int net_shutdown (int *fd)
89 {
90         uint16_t packet_size = 0;
91
92         if ((fd == NULL) || (*fd < 0))
93                 return (EINVAL);
94
95         swrite (*fd, (void *) &packet_size, sizeof (packet_size));
96         close (*fd);
97         *fd = -1;
98
99         return (0);
100 } /* int net_shutdown */
101
102 /* Close the network connection */
103 static int apcups_shutdown (void)
104 {
105         if (global_sockfd < 0)
106                 return (0);
107
108         net_shutdown (&global_sockfd);
109         return (0);
110 } /* int apcups_shutdown */
111
112 /*
113  * Open a TCP connection to the UPS network server
114  * Returns -1 on error
115  * Returns socket file descriptor otherwise
116  */
117 static int net_open (char *host, int port)
118 {
119         int              sd;
120         int              status;
121         char             port_str[8];
122         struct addrinfo  ai_hints;
123         struct addrinfo *ai_return;
124         struct addrinfo *ai_list;
125
126         assert ((port > 0x00000000) && (port <= 0x0000FFFF));
127
128         /* Convert the port to a string */
129         ssnprintf (port_str, sizeof (port_str), "%i", port);
130
131         /* Resolve name */
132         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
133         ai_hints.ai_family   = AF_INET; /* XXX: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
134         ai_hints.ai_socktype = SOCK_STREAM;
135
136         status = getaddrinfo (host, port_str, &ai_hints, &ai_return);
137         if (status != 0)
138         {
139                 char errbuf[1024];
140                 INFO ("getaddrinfo failed: %s",
141                                 (status == EAI_SYSTEM)
142                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
143                                 : gai_strerror (status));
144                 return (-1);
145         }
146
147         /* Create socket */
148         sd = -1;
149         for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
150         {
151                 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
152                 if (sd >= 0)
153                         break;
154         }
155         /* `ai_list' still holds the current description of the socket.. */
156
157         if (sd < 0)
158         {
159                 DEBUG ("Unable to open a socket");
160                 freeaddrinfo (ai_return);
161                 return (-1);
162         }
163
164         status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
165
166         freeaddrinfo (ai_return);
167
168         if (status != 0) /* `connect(2)' failed */
169         {
170                 char errbuf[1024];
171                 INFO ("connect failed: %s",
172                                 sstrerror (errno, errbuf, sizeof (errbuf)));
173                 close (sd);
174                 return (-1);
175         }
176
177         DEBUG ("Done opening a socket %i", sd);
178
179         return (sd);
180 } /* int net_open (char *host, char *service, int port) */
181
182 /*
183  * Receive a message from the other end. Each message consists of
184  * two packets. The first is a header that contains the size
185  * of the data that follows in the second packet.
186  * Returns number of bytes read
187  * Returns 0 on end of file
188  * Returns -1 on hard end of file (i.e. network connection close)
189  * Returns -2 on error
190  */
191 static int net_recv (int *sockfd, char *buf, int buflen)
192 {
193         uint16_t packet_size;
194
195         /* get data size -- in short */
196         if (sread (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
197         {
198                 close (*sockfd);
199                 *sockfd = -1;
200                 return (-1);
201         }
202
203         packet_size = ntohs (packet_size);
204         if (packet_size > buflen)
205         {
206                 ERROR ("apcups plugin: Received %"PRIu16" bytes of payload "
207                                 "but have only %i bytes of buffer available.",
208                                 packet_size, buflen);
209                 close (*sockfd);
210                 *sockfd = -1;
211                 return (-2);
212         }
213
214         if (packet_size == 0)
215                 return (0);
216
217         /* now read the actual data */
218         if (sread (*sockfd, (void *) buf, packet_size) != 0)
219         {
220                 close (*sockfd);
221                 *sockfd = -1;
222                 return (-1);
223         }
224
225         return ((int) packet_size);
226 } /* static int net_recv (int *sockfd, char *buf, int buflen) */
227
228 /*
229  * Send a message over the network. The send consists of
230  * two network packets. The first is sends a short containing
231  * the length of the data packet which follows.
232  * Returns zero on success
233  * Returns non-zero on error
234  */
235 static int net_send (int *sockfd, char *buff, int len)
236 {
237         uint16_t packet_size;
238
239         assert (len > 0);
240         assert (*sockfd >= 0);
241
242         /* send short containing size of data packet */
243         packet_size = htons ((uint16_t) len);
244
245         if (swrite (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
246         {
247                 close (*sockfd);
248                 *sockfd = -1;
249                 return (-1);
250         }
251
252         /* send data packet */
253         if (swrite (*sockfd, (void *) buff, len) != 0)
254         {
255                 close (*sockfd);
256                 *sockfd = -1;
257                 return (-2);
258         }
259
260         return (0);
261 }
262
263 /* Get and print status from apcupsd NIS server */
264 static int apc_query_server (char *host, int port,
265                 struct apc_detail_s *apcups_detail)
266 {
267         int     n;
268         char    recvline[1024];
269         char   *tokptr;
270         char   *toksaveptr;
271         char   *key;
272         double  value;
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                         key = tokptr;
342                         if ((tokptr = strtok_r (NULL, " :\t", &toksaveptr)) == NULL)
343                                 continue;
344                         value = atof (tokptr);
345
346                         PRINT_VALUE (key, value);
347
348                         if (strcmp ("LINEV", key) == 0)
349                                 apcups_detail->linev = value;
350                         else if (strcmp ("BATTV", key) == 0)
351                                 apcups_detail->battv = value;
352                         else if (strcmp ("ITEMP", key) == 0)
353                                 apcups_detail->itemp = value;
354                         else if (strcmp ("LOADPCT", key) == 0)
355                                 apcups_detail->loadpct = value;
356                         else if (strcmp ("BCHARGE", key) == 0)
357                                 apcups_detail->bcharge = value;
358                         else if (strcmp ("OUTPUTV", key) == 0)
359                                 apcups_detail->outputv = value;
360                         else if (strcmp ("LINEFREQ", key) == 0)
361                                 apcups_detail->linefreq = value;
362                         else if (strcmp ("TIMELEFT", key) == 0)
363                                 apcups_detail->timeleft = value;
364
365                         tokptr = strtok_r (NULL, ":", &toksaveptr);
366                 } /* while (tokptr != NULL) */
367         }
368         status = errno; /* save errno, net_shutdown() may re-set it. */
369
370         if (close_socket)
371                 net_shutdown (&global_sockfd);
372
373         if (n < 0)
374         {
375                 char errbuf[1024];
376                 ERROR ("apcups plugin: Reading from socket failed: %s",
377                                 sstrerror (status, errbuf, sizeof (errbuf)));
378                 return (-1);
379         }
380
381         return (0);
382 }
383
384 static int apcups_config (const char *key, const char *value)
385 {
386         if (strcasecmp (key, "host") == 0)
387         {
388                 if (conf_host != NULL)
389                 {
390                         free (conf_host);
391                         conf_host = NULL;
392                 }
393                 if ((conf_host = strdup (value)) == NULL)
394                         return (1);
395         }
396         else if (strcasecmp (key, "Port") == 0)
397         {
398                 int port_tmp = atoi (value);
399                 if (port_tmp < 1 || port_tmp > 65535)
400                 {
401                         WARNING ("apcups plugin: Invalid port: %i", port_tmp);
402                         return (1);
403                 }
404                 conf_port = port_tmp;
405         }
406         else
407         {
408                 return (-1);
409         }
410         return (0);
411 }
412
413 static void apc_submit_generic (char *type, char *type_inst, double value)
414 {
415         value_t values[1];
416         value_list_t vl = VALUE_LIST_INIT;
417
418         values[0].gauge = value;
419
420         vl.values = values;
421         vl.values_len = 1;
422         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
423         sstrncpy (vl.plugin, "apcups", sizeof (vl.plugin));
424         sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
425         sstrncpy (vl.type, type, sizeof (vl.type));
426         sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
427
428         plugin_dispatch_values (&vl);
429 }
430
431 static void apc_submit (struct apc_detail_s *apcups_detail)
432 {
433         apc_submit_generic ("voltage",    "input",   apcups_detail->linev);
434         apc_submit_generic ("voltage",    "output",  apcups_detail->outputv);
435         apc_submit_generic ("voltage",    "battery", apcups_detail->battv);
436         apc_submit_generic ("charge",     "",        apcups_detail->bcharge);
437         apc_submit_generic ("percent",    "load",    apcups_detail->loadpct);
438         apc_submit_generic ("timeleft",   "",        apcups_detail->timeleft);
439         apc_submit_generic ("temperature", "",       apcups_detail->itemp);
440         apc_submit_generic ("frequency",  "input",   apcups_detail->linefreq);
441 }
442
443 static int apcups_read (void)
444 {
445         struct apc_detail_s apcups_detail;
446         int status;
447
448         apcups_detail.linev    =   -1.0;
449         apcups_detail.outputv  =   -1.0;
450         apcups_detail.battv    =   -1.0;
451         apcups_detail.loadpct  =   -1.0;
452         apcups_detail.bcharge  =   -1.0;
453         apcups_detail.timeleft =    NAN;
454         apcups_detail.itemp    = -300.0;
455         apcups_detail.linefreq =   -1.0;
456
457         status = apc_query_server (conf_host == NULL
458                         ? APCUPS_DEFAULT_HOST
459                         : conf_host,
460                         conf_port, &apcups_detail);
461
462         /*
463          * if we did not connect then do not bother submitting
464          * zeros. We want rrd files to have NAN.
465          */
466         if (status != 0)
467         {
468                 DEBUG ("apc_query_server (%s, %i) = %i",
469                                 conf_host == NULL
470                                 ? APCUPS_DEFAULT_HOST
471                                 : conf_host,
472                                 conf_port, status);
473                 return (-1);
474         }
475
476         apc_submit (&apcups_detail);
477
478         return (0);
479 } /* apcups_read */
480
481 void module_register (void)
482 {
483         plugin_register_config ("apcups", apcups_config, config_keys,
484                         config_keys_num);
485         plugin_register_read ("apcups", apcups_read);
486         plugin_register_shutdown ("apcups", apcups_shutdown);
487 } /* void module_register */