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