apcups plugin: Implement the "PersistentConnection" option.
[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 #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 #ifndef APCUPS_DEFAULT_NODE
47 # define APCUPS_DEFAULT_NODE "localhost"
48 #endif
49
50 #ifndef APCUPS_DEFAULT_SERVICE
51 # define APCUPS_DEFAULT_SERVICE "3551"
52 #endif
53
54 /*
55  * Private data types
56  */
57 struct apc_detail_s
58 {
59         double linev;
60         double loadpct;
61         double bcharge;
62         double timeleft;
63         double outputv;
64         double itemp;
65         double battv;
66         double linefreq;
67 };
68
69 /*
70  * Private variables
71  */
72 /* Default values for contacting daemon */
73 static char *conf_node = NULL;
74 static char *conf_service = NULL;
75 /* Defaults to false for backwards compatibility. */
76 static _Bool conf_report_seconds = 0;
77 static _Bool conf_persistent_conn = 1;
78
79 static int global_sockfd = -1;
80
81 static int count_retries = 0;
82 static int count_iterations = 0;
83
84 static int net_shutdown (int *fd)
85 {
86         uint16_t packet_size = 0;
87
88         if ((fd == NULL) || (*fd < 0))
89                 return (EINVAL);
90
91         swrite (*fd, (void *) &packet_size, sizeof (packet_size));
92         close (*fd);
93         *fd = -1;
94
95         return (0);
96 } /* int net_shutdown */
97
98 /* Close the network connection */
99 static int apcups_shutdown (void)
100 {
101         if (global_sockfd < 0)
102                 return (0);
103
104         net_shutdown (&global_sockfd);
105         return (0);
106 } /* int apcups_shutdown */
107
108 /*
109  * Open a TCP connection to the UPS network server
110  * Returns -1 on error
111  * Returns socket file descriptor otherwise
112  */
113 static int net_open (char const *node, char const *service)
114 {
115         int              sd;
116         int              status;
117         struct addrinfo  ai_hints;
118         struct addrinfo *ai_return;
119         struct addrinfo *ai_list;
120
121         /* Resolve name */
122         memset (&ai_hints, 0, sizeof (ai_hints));
123         /* TODO: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
124         ai_hints.ai_family   = AF_INET;
125         ai_hints.ai_socktype = SOCK_STREAM;
126
127         status = getaddrinfo (node, service, &ai_hints, &ai_return);
128         if (status != 0)
129         {
130                 char errbuf[1024];
131                 INFO ("getaddrinfo failed: %s",
132                                 (status == EAI_SYSTEM)
133                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
134                                 : gai_strerror (status));
135                 return (-1);
136         }
137
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.. */
147
148         if (sd < 0)
149         {
150                 DEBUG ("Unable to open a socket");
151                 freeaddrinfo (ai_return);
152                 return (-1);
153         }
154
155         status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
156
157         freeaddrinfo (ai_return);
158
159         if (status != 0) /* `connect(2)' failed */
160         {
161                 char errbuf[1024];
162                 INFO ("connect failed: %s",
163                                 sstrerror (errno, errbuf, sizeof (errbuf)));
164                 close (sd);
165                 return (-1);
166         }
167
168         DEBUG ("Done opening a socket %i", sd);
169
170         return (sd);
171 } /* int net_open */
172
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;
185
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         }
193
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         }
204
205         if (packet_size == 0)
206                 return (0);
207
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         }
215
216         return ((int) packet_size);
217 } /* static int net_recv (int *sockfd, char *buf, int buflen) */
218
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, char *buff, int len)
227 {
228         uint16_t packet_size;
229
230         assert (len > 0);
231         assert (*sockfd >= 0);
232
233         /* send short containing size of data packet */
234         packet_size = htons ((uint16_t) len);
235
236         if (swrite (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
237         {
238                 close (*sockfd);
239                 *sockfd = -1;
240                 return (-1);
241         }
242
243         /* send data packet */
244         if (swrite (*sockfd, (void *) buff, len) != 0)
245         {
246                 close (*sockfd);
247                 *sockfd = -1;
248                 return (-2);
249         }
250
251         return (0);
252 }
253
254 /* Get and print status from apcupsd NIS server */
255 static int apc_query_server (char const *node, char const *service,
256                 struct apc_detail_s *apcups_detail)
257 {
258         int     n;
259         char    recvline[1024];
260         char   *tokptr;
261         char   *toksaveptr;
262         char   *key;
263         double  value;
264         _Bool retry = 1;
265         int status;
266
267 #if APCMAIN
268 # define PRINT_VALUE(name, val) printf("  Found property: name = %s; value = %f;\n", name, val)
269 #else
270 # define PRINT_VALUE(name, val) /**/
271 #endif
272
273         while (retry)
274         {
275                 if (global_sockfd < 0)
276                 {
277                         global_sockfd = net_open (node, service);
278                         if (global_sockfd < 0)
279                         {
280                                 ERROR ("apcups plugin: Connecting to the "
281                                                 "apcupsd failed.");
282                                 return (-1);
283                         }
284                 }
285
286
287                 status = net_send (&global_sockfd, "status", strlen ("status"));
288                 if (status != 0)
289                 {
290                         /* net_send is closing the socket on error. */
291                         assert (global_sockfd < 0);
292                         if (retry)
293                         {
294                                 retry = 0;
295                                 count_retries++;
296                                 continue;
297                         }
298
299                         ERROR ("apcups plugin: Writing to the socket failed.");
300                         return (-1);
301                 }
302
303                 break;
304         } /* while (retry) */
305
306         /* When collectd's collection interval is larger than apcupsd's
307          * timeout, we would have to retry / re-connect each iteration. Try to
308          * detect this situation and shut down the socket gracefully in that
309          * case. Otherwise, keep the socket open to avoid overhead. */
310         count_iterations++;
311         if ((count_iterations == 10) && (count_retries > 2))
312         {
313                 NOTICE ("apcups plugin: There have been %i retries in the "
314                                 "first %i iterations. Will close the socket "
315                                 "in future iterations.",
316                                 count_retries, count_iterations);
317                 conf_persistent_conn = 0;
318         }
319
320         while ((n = net_recv (&global_sockfd, recvline, sizeof (recvline) - 1)) > 0)
321         {
322                 assert ((size_t)n < sizeof (recvline));
323                 recvline[n] = 0;
324 #if APCMAIN
325                 printf ("net_recv = `%s';\n", recvline);
326 #endif /* if APCMAIN */
327
328                 if (strncmp ("END APC", recvline, strlen ("END APC")) == 0)
329                         break;
330
331                 toksaveptr = NULL;
332                 tokptr = strtok_r (recvline, " :\t", &toksaveptr);
333                 while (tokptr != NULL)
334                 {
335                         key = tokptr;
336                         if ((tokptr = strtok_r (NULL, " :\t", &toksaveptr)) == NULL)
337                                 continue;
338                         value = atof (tokptr);
339
340                         PRINT_VALUE (key, value);
341
342                         if (strcmp ("LINEV", key) == 0)
343                                 apcups_detail->linev = value;
344                         else if (strcmp ("BATTV", key) == 0)
345                                 apcups_detail->battv = value;
346                         else if (strcmp ("ITEMP", key) == 0)
347                                 apcups_detail->itemp = value;
348                         else if (strcmp ("LOADPCT", key) == 0)
349                                 apcups_detail->loadpct = value;
350                         else if (strcmp ("BCHARGE", key) == 0)
351                                 apcups_detail->bcharge = value;
352                         else if (strcmp ("OUTPUTV", key) == 0)
353                                 apcups_detail->outputv = value;
354                         else if (strcmp ("LINEFREQ", key) == 0)
355                                 apcups_detail->linefreq = value;
356                         else if (strcmp ("TIMELEFT", key) == 0)
357                         {
358                                 /* Convert minutes to seconds if requested by
359                                  * the user. */
360                                 if (conf_report_seconds)
361                                         value *= 60.0;
362                                 apcups_detail->timeleft = value;
363                         }
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 (!conf_persistent_conn)
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 (oconfig_item_t *ci)
385 {
386         int i;
387
388         for (i = 0; i < ci->children_num; i++)
389         {
390                 oconfig_item_t *child = ci->children + i;
391
392                 if (strcasecmp (child->key, "Host") == 0)
393                         cf_util_get_string (child, &conf_node);
394                 else if (strcasecmp (child->key, "Port") == 0)
395                         cf_util_get_service (child, &conf_service);
396                 else if (strcasecmp (child->key, "ReportSeconds") == 0)
397                         cf_util_get_boolean (child, &conf_report_seconds);
398                 else if (strcasecmp (child->key, "PersistentConnection") == 0)
399                         cf_util_get_boolean (child, &conf_persistent_conn);
400                 else
401                         ERROR ("apcups plugin: Unknown config option \"%s\".", child->key);
402         }
403
404         return (0);
405 } /* int apcups_config */
406
407 static void apc_submit_generic (char *type, char *type_inst, double value)
408 {
409         value_t values[1];
410         value_list_t vl = VALUE_LIST_INIT;
411
412         values[0].gauge = value;
413
414         vl.values = values;
415         vl.values_len = 1;
416         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
417         sstrncpy (vl.plugin, "apcups", sizeof (vl.plugin));
418         sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
419         sstrncpy (vl.type, type, sizeof (vl.type));
420         sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
421
422         plugin_dispatch_values (&vl);
423 }
424
425 static void apc_submit (struct apc_detail_s *apcups_detail)
426 {
427         apc_submit_generic ("voltage",    "input",   apcups_detail->linev);
428         apc_submit_generic ("voltage",    "output",  apcups_detail->outputv);
429         apc_submit_generic ("voltage",    "battery", apcups_detail->battv);
430         apc_submit_generic ("charge",     "",        apcups_detail->bcharge);
431         apc_submit_generic ("percent",    "load",    apcups_detail->loadpct);
432         apc_submit_generic ("timeleft",   "",        apcups_detail->timeleft);
433         apc_submit_generic ("temperature", "",       apcups_detail->itemp);
434         apc_submit_generic ("frequency",  "input",   apcups_detail->linefreq);
435 }
436
437 static int apcups_read (void)
438 {
439         struct apc_detail_s apcups_detail;
440         int status;
441
442         apcups_detail.linev    =   -1.0;
443         apcups_detail.outputv  =   -1.0;
444         apcups_detail.battv    =   -1.0;
445         apcups_detail.loadpct  =   -1.0;
446         apcups_detail.bcharge  =   -1.0;
447         apcups_detail.timeleft =    NAN;
448         apcups_detail.itemp    = -300.0;
449         apcups_detail.linefreq =   -1.0;
450
451         status = apc_query_server ((conf_node == NULL) ? APCUPS_DEFAULT_NODE : conf_node,
452                         (conf_service == NULL) ? APCUPS_DEFAULT_SERVICE : conf_service,
453                         &apcups_detail);
454
455         /*
456          * if we did not connect then do not bother submitting
457          * zeros. We want rrd files to have NAN.
458          */
459         if (status != 0)
460         {
461                 DEBUG ("apc_query_server (%s, %s) = %i",
462                                 (conf_node == NULL) ? APCUPS_DEFAULT_NODE : conf_node,
463                                 (conf_service == NULL) ? APCUPS_DEFAULT_SERVICE : conf_service,
464                                 status);
465                 return (-1);
466         }
467
468         apc_submit (&apcups_detail);
469
470         return (0);
471 } /* apcups_read */
472
473 void module_register (void)
474 {
475         plugin_register_complex_config ("apcups", apcups_config);
476         plugin_register_read ("apcups", apcups_read);
477         plugin_register_shutdown ("apcups", apcups_shutdown);
478 } /* void module_register */