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