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>
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.
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.
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,
23 * Anthony Gialluca <tonyabg at charter.net>
24 * Florian octo Forster <octo at collectd.org>
28 #include "common.h" /* rrd_update_file */
29 #include "plugin.h" /* plugin_register, plugin_submit */
30 #include "configfile.h" /* cf_register */
33 # include <sys/types.h>
40 # include <netinet/in.h>
43 #ifndef APCUPS_SERVER_TIMEOUT
44 # define APCUPS_SERVER_TIMEOUT 15.0
47 #ifndef APCUPS_DEFAULT_NODE
48 # define APCUPS_DEFAULT_NODE "localhost"
51 #ifndef APCUPS_DEFAULT_SERVICE
52 # define APCUPS_DEFAULT_SERVICE "3551"
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;
80 static int global_sockfd = -1;
82 static int count_retries = 0;
83 static int count_iterations = 0;
85 static int net_shutdown (int *fd)
87 uint16_t packet_size = 0;
89 if ((fd == NULL) || (*fd < 0))
92 (void)swrite (*fd, (void *) &packet_size, sizeof (packet_size));
97 } /* int net_shutdown */
99 /* Close the network connection */
100 static int apcups_shutdown (void)
102 if (global_sockfd < 0)
105 net_shutdown (&global_sockfd);
107 } /* int apcups_shutdown */
110 * Open a TCP connection to the UPS network server
111 * Returns -1 on error
112 * Returns socket file descriptor otherwise
114 static int net_open (char const *node, char const *service)
118 struct addrinfo ai_hints;
119 struct addrinfo *ai_return;
120 struct addrinfo *ai_list;
123 memset (&ai_hints, 0, sizeof (ai_hints));
124 /* TODO: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
125 ai_hints.ai_family = AF_INET;
126 ai_hints.ai_socktype = SOCK_STREAM;
128 status = getaddrinfo (node, service, &ai_hints, &ai_return);
132 INFO ("apcups plugin: getaddrinfo failed: %s",
133 (status == EAI_SYSTEM)
134 ? sstrerror (errno, errbuf, sizeof (errbuf))
135 : gai_strerror (status));
141 for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
143 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
147 /* `ai_list' still holds the current description of the socket.. */
151 DEBUG ("apcups plugin: Unable to open a socket");
152 freeaddrinfo (ai_return);
156 status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
158 freeaddrinfo (ai_return);
160 if (status != 0) /* `connect(2)' failed */
163 INFO ("apcups plugin: connect failed: %s",
164 sstrerror (errno, errbuf, sizeof (errbuf)));
169 DEBUG ("apcups plugin: Done opening a socket %i", sd);
175 * Receive a message from the other end. Each message consists of
176 * two packets. The first is a header that contains the size
177 * of the data that follows in the second packet.
178 * Returns number of bytes read
179 * Returns 0 on end of file
180 * Returns -1 on hard end of file (i.e. network connection close)
181 * Returns -2 on error
183 static int net_recv (int *sockfd, char *buf, int buflen)
185 uint16_t packet_size;
187 /* get data size -- in short */
188 if (sread (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
195 packet_size = ntohs (packet_size);
196 if (packet_size > buflen)
198 ERROR ("apcups plugin: Received %"PRIu16" bytes of payload "
199 "but have only %i bytes of buffer available.",
200 packet_size, buflen);
206 if (packet_size == 0)
209 /* now read the actual data */
210 if (sread (*sockfd, (void *) buf, packet_size) != 0)
217 return ((int) packet_size);
218 } /* static int net_recv (int *sockfd, char *buf, int buflen) */
221 * Send a message over the network. The send consists of
222 * two network packets. The first is sends a short containing
223 * the length of the data packet which follows.
224 * Returns zero on success
225 * Returns non-zero on error
227 static int net_send (int *sockfd, const char *buff, int len)
229 uint16_t packet_size;
232 assert (*sockfd >= 0);
234 /* send short containing size of data packet */
235 packet_size = htons ((uint16_t) len);
237 if (swrite (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
244 /* send data packet */
245 if (swrite (*sockfd, (void *) buff, len) != 0)
255 /* Get and print status from apcupsd NIS server */
256 static int apc_query_server (char const *node, char const *service,
257 struct apc_detail_s *apcups_detail)
269 # define PRINT_VALUE(name, val) printf(" Found property: name = %s; value = %f;\n", name, val)
271 # define PRINT_VALUE(name, val) /**/
276 if (global_sockfd < 0)
278 global_sockfd = net_open (node, service);
279 if (global_sockfd < 0)
281 ERROR ("apcups plugin: Connecting to the "
288 status = net_send (&global_sockfd, "status", strlen ("status"));
291 /* net_send is closing the socket on error. */
292 assert (global_sockfd < 0);
300 ERROR ("apcups plugin: Writing to the socket failed.");
305 } /* while (retry) */
307 /* When collectd's collection interval is larger than apcupsd's
308 * timeout, we would have to retry / re-connect each iteration. Try to
309 * detect this situation and shut down the socket gracefully in that
310 * case. Otherwise, keep the socket open to avoid overhead. */
312 if ((count_iterations == 10) && (count_retries > 2))
314 NOTICE ("apcups plugin: There have been %i retries in the "
315 "first %i iterations. Will close the socket "
316 "in future iterations.",
317 count_retries, count_iterations);
318 conf_persistent_conn = 0;
321 while ((n = net_recv (&global_sockfd, recvline, sizeof (recvline) - 1)) > 0)
323 assert ((size_t)n < sizeof (recvline));
326 printf ("net_recv = `%s';\n", recvline);
327 #endif /* if APCMAIN */
330 tokptr = strtok_r (recvline, " :\t", &toksaveptr);
331 while (tokptr != NULL)
334 if ((tokptr = strtok_r (NULL, " :\t", &toksaveptr)) == NULL)
336 value = atof (tokptr);
338 PRINT_VALUE (key, value);
340 if (strcmp ("LINEV", key) == 0)
341 apcups_detail->linev = value;
342 else if (strcmp ("BATTV", key) == 0)
343 apcups_detail->battv = value;
344 else if (strcmp ("ITEMP", key) == 0)
345 apcups_detail->itemp = value;
346 else if (strcmp ("LOADPCT", key) == 0)
347 apcups_detail->loadpct = value;
348 else if (strcmp ("BCHARGE", key) == 0)
349 apcups_detail->bcharge = value;
350 else if (strcmp ("OUTPUTV", key) == 0)
351 apcups_detail->outputv = value;
352 else if (strcmp ("LINEFREQ", key) == 0)
353 apcups_detail->linefreq = value;
354 else if (strcmp ("TIMELEFT", key) == 0)
356 /* Convert minutes to seconds if requested by
358 if (conf_report_seconds)
360 apcups_detail->timeleft = value;
363 tokptr = strtok_r (NULL, ":", &toksaveptr);
364 } /* while (tokptr != NULL) */
366 status = errno; /* save errno, net_shutdown() may re-set it. */
368 if (!conf_persistent_conn)
369 net_shutdown (&global_sockfd);
374 ERROR ("apcups plugin: Reading from socket failed: %s",
375 sstrerror (status, errbuf, sizeof (errbuf)));
382 static int apcups_config (oconfig_item_t *ci)
385 _Bool persistent_conn_set = 0;
387 for (i = 0; i < ci->children_num; i++)
389 oconfig_item_t *child = ci->children + i;
391 if (strcasecmp (child->key, "Host") == 0)
392 cf_util_get_string (child, &conf_node);
393 else if (strcasecmp (child->key, "Port") == 0)
394 cf_util_get_service (child, &conf_service);
395 else if (strcasecmp (child->key, "ReportSeconds") == 0)
396 cf_util_get_boolean (child, &conf_report_seconds);
397 else if (strcasecmp (child->key, "PersistentConnection") == 0) {
398 cf_util_get_boolean (child, &conf_persistent_conn);
399 persistent_conn_set = 1;
402 ERROR ("apcups plugin: Unknown config option \"%s\".", child->key);
405 if (!persistent_conn_set) {
406 double interval = CDTIME_T_TO_DOUBLE(plugin_get_interval());
407 if (interval > APCUPS_SERVER_TIMEOUT) {
408 NOTICE ("apcups plugin: Plugin poll interval set to %.3f seconds. "
409 "Apcupsd NIS socket timeout is %.3f seconds, "
410 "PersistentConnection disabled by default.",
411 interval, APCUPS_SERVER_TIMEOUT);
412 conf_persistent_conn = 0;
417 } /* int apcups_config */
419 static void apc_submit_generic (const char *type, const char *type_inst, double value)
422 value_list_t vl = VALUE_LIST_INIT;
424 values[0].gauge = value;
428 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
429 sstrncpy (vl.plugin, "apcups", sizeof (vl.plugin));
430 sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
431 sstrncpy (vl.type, type, sizeof (vl.type));
432 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
434 plugin_dispatch_values (&vl);
437 static void apc_submit (struct apc_detail_s *apcups_detail)
439 apc_submit_generic ("voltage", "input", apcups_detail->linev);
440 apc_submit_generic ("voltage", "output", apcups_detail->outputv);
441 apc_submit_generic ("voltage", "battery", apcups_detail->battv);
442 apc_submit_generic ("charge", "", apcups_detail->bcharge);
443 apc_submit_generic ("percent", "load", apcups_detail->loadpct);
444 apc_submit_generic ("timeleft", "", apcups_detail->timeleft);
445 apc_submit_generic ("temperature", "", apcups_detail->itemp);
446 apc_submit_generic ("frequency", "input", apcups_detail->linefreq);
449 static int apcups_read (void)
451 struct apc_detail_s apcups_detail;
454 apcups_detail.linev = -1.0;
455 apcups_detail.outputv = -1.0;
456 apcups_detail.battv = -1.0;
457 apcups_detail.loadpct = -1.0;
458 apcups_detail.bcharge = -1.0;
459 apcups_detail.timeleft = NAN;
460 apcups_detail.itemp = -300.0;
461 apcups_detail.linefreq = -1.0;
463 status = apc_query_server ((conf_node == NULL) ? APCUPS_DEFAULT_NODE : conf_node,
464 (conf_service == NULL) ? APCUPS_DEFAULT_SERVICE : conf_service,
468 * if we did not connect then do not bother submitting
469 * zeros. We want rrd files to have NAN.
473 DEBUG ("apcups plugin: apc_query_server (%s, %s) = %i",
474 (conf_node == NULL) ? APCUPS_DEFAULT_NODE : conf_node,
475 (conf_service == NULL) ? APCUPS_DEFAULT_SERVICE : conf_service,
480 apc_submit (&apcups_detail);
485 void module_register (void)
487 plugin_register_complex_config ("apcups", apcups_config);
488 plugin_register_read ("apcups", apcups_read);
489 plugin_register_shutdown ("apcups", apcups_shutdown);
490 } /* void module_register */