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>
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 verplant.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>
36 # include <sys/socket.h>
43 # include <netinet/in.h>
48 #define MODULE_NAME "apcups"
50 #define APCUPS_DEFAULT_HOST "localhost"
70 /* Default values for contacting daemon */
71 static char *conf_host = NULL;
72 static int conf_port = NISPORT;
73 /* Defaults to false for backwards compatibility. */
74 static _Bool conf_report_seconds = 0;
76 static int global_sockfd = -1;
78 static int count_retries = 0;
79 static int count_iterations = 0;
80 static _Bool close_socket = 0;
82 static const char *config_keys[] =
88 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
90 static int net_shutdown (int *fd)
92 uint16_t packet_size = 0;
94 if ((fd == NULL) || (*fd < 0))
97 swrite (*fd, (void *) &packet_size, sizeof (packet_size));
102 } /* int net_shutdown */
104 /* Close the network connection */
105 static int apcups_shutdown (void)
107 if (global_sockfd < 0)
110 net_shutdown (&global_sockfd);
112 } /* int apcups_shutdown */
115 * Open a TCP connection to the UPS network server
116 * Returns -1 on error
117 * Returns socket file descriptor otherwise
119 static int net_open (char *host, int port)
124 struct addrinfo ai_hints;
125 struct addrinfo *ai_return;
126 struct addrinfo *ai_list;
128 assert ((port > 0x00000000) && (port <= 0x0000FFFF));
130 /* Convert the port to a string */
131 ssnprintf (port_str, sizeof (port_str), "%i", port);
134 memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
135 ai_hints.ai_family = AF_INET; /* XXX: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
136 ai_hints.ai_socktype = SOCK_STREAM;
138 status = getaddrinfo (host, port_str, &ai_hints, &ai_return);
142 INFO ("getaddrinfo failed: %s",
143 (status == EAI_SYSTEM)
144 ? sstrerror (errno, errbuf, sizeof (errbuf))
145 : gai_strerror (status));
151 for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
153 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
157 /* `ai_list' still holds the current description of the socket.. */
161 DEBUG ("Unable to open a socket");
162 freeaddrinfo (ai_return);
166 status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
168 freeaddrinfo (ai_return);
170 if (status != 0) /* `connect(2)' failed */
173 INFO ("connect failed: %s",
174 sstrerror (errno, errbuf, sizeof (errbuf)));
179 DEBUG ("Done opening a socket %i", sd);
182 } /* int net_open (char *host, char *service, int port) */
185 * Receive a message from the other end. Each message consists of
186 * two packets. The first is a header that contains the size
187 * of the data that follows in the second packet.
188 * Returns number of bytes read
189 * Returns 0 on end of file
190 * Returns -1 on hard end of file (i.e. network connection close)
191 * Returns -2 on error
193 static int net_recv (int *sockfd, char *buf, int buflen)
195 uint16_t packet_size;
197 /* get data size -- in short */
198 if (sread (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
205 packet_size = ntohs (packet_size);
206 if (packet_size > buflen)
208 ERROR ("apcups plugin: Received %"PRIu16" bytes of payload "
209 "but have only %i bytes of buffer available.",
210 packet_size, buflen);
216 if (packet_size == 0)
219 /* now read the actual data */
220 if (sread (*sockfd, (void *) buf, packet_size) != 0)
227 return ((int) packet_size);
228 } /* static int net_recv (int *sockfd, char *buf, int buflen) */
231 * Send a message over the network. The send consists of
232 * two network packets. The first is sends a short containing
233 * the length of the data packet which follows.
234 * Returns zero on success
235 * Returns non-zero on error
237 static int net_send (int *sockfd, char *buff, int len)
239 uint16_t packet_size;
242 assert (*sockfd >= 0);
244 /* send short containing size of data packet */
245 packet_size = htons ((uint16_t) len);
247 if (swrite (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
254 /* send data packet */
255 if (swrite (*sockfd, (void *) buff, len) != 0)
265 /* Get and print status from apcupsd NIS server */
266 static int apc_query_server (char *host, int port,
267 struct apc_detail_s *apcups_detail)
279 # define PRINT_VALUE(name, val) printf(" Found property: name = %s; value = %f;\n", name, val)
281 # define PRINT_VALUE(name, val) /**/
286 if (global_sockfd < 0)
288 global_sockfd = net_open (host, port);
289 if (global_sockfd < 0)
291 ERROR ("apcups plugin: Connecting to the "
298 status = net_send (&global_sockfd, "status", strlen ("status"));
301 /* net_send is closing the socket on error. */
302 assert (global_sockfd < 0);
310 ERROR ("apcups plugin: Writing to the socket failed.");
315 } /* while (retry) */
317 /* When collectd's collection interval is larger than apcupsd's
318 * timeout, we would have to retry / re-connect each iteration. Try to
319 * detect this situation and shut down the socket gracefully in that
320 * case. Otherwise, keep the socket open to avoid overhead. */
322 if ((count_iterations == 10) && (count_retries > 2))
324 NOTICE ("apcups plugin: There have been %i retries in the "
325 "first %i iterations. Will close the socket "
326 "in future iterations.",
327 count_retries, count_iterations);
331 while ((n = net_recv (&global_sockfd, recvline, sizeof (recvline) - 1)) > 0)
333 assert ((unsigned int)n < sizeof (recvline));
336 printf ("net_recv = `%s';\n", recvline);
337 #endif /* if APCMAIN */
340 tokptr = strtok_r (recvline, " :\t", &toksaveptr);
341 while (tokptr != NULL)
344 if ((tokptr = strtok_r (NULL, " :\t", &toksaveptr)) == NULL)
346 value = atof (tokptr);
348 PRINT_VALUE (key, value);
350 if (strcmp ("LINEV", key) == 0)
351 apcups_detail->linev = value;
352 else if (strcmp ("BATTV", key) == 0)
353 apcups_detail->battv = value;
354 else if (strcmp ("ITEMP", key) == 0)
355 apcups_detail->itemp = value;
356 else if (strcmp ("LOADPCT", key) == 0)
357 apcups_detail->loadpct = value;
358 else if (strcmp ("BCHARGE", key) == 0)
359 apcups_detail->bcharge = value;
360 else if (strcmp ("OUTPUTV", key) == 0)
361 apcups_detail->outputv = value;
362 else if (strcmp ("LINEFREQ", key) == 0)
363 apcups_detail->linefreq = value;
364 else if (strcmp ("TIMELEFT", key) == 0)
366 /* Convert minutes to seconds if requested by
368 if (conf_report_seconds)
370 apcups_detail->timeleft = value;
373 tokptr = strtok_r (NULL, ":", &toksaveptr);
374 } /* while (tokptr != NULL) */
376 status = errno; /* save errno, net_shutdown() may re-set it. */
379 net_shutdown (&global_sockfd);
384 ERROR ("apcups plugin: Reading from socket failed: %s",
385 sstrerror (status, errbuf, sizeof (errbuf)));
392 static int apcups_config (const char *key, const char *value)
394 if (strcasecmp (key, "host") == 0)
396 if (conf_host != NULL)
401 if ((conf_host = strdup (value)) == NULL)
404 else if (strcasecmp (key, "Port") == 0)
406 int port_tmp = atoi (value);
407 if (port_tmp < 1 || port_tmp > 65535)
409 WARNING ("apcups plugin: Invalid port: %i", port_tmp);
412 conf_port = port_tmp;
414 else if (strcasecmp (key, "ReportSeconds") == 0)
417 conf_report_seconds = 1;
419 conf_report_seconds = 0;
428 static void apc_submit_generic (char *type, char *type_inst, double value)
431 value_list_t vl = VALUE_LIST_INIT;
433 values[0].gauge = value;
437 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
438 sstrncpy (vl.plugin, "apcups", sizeof (vl.plugin));
439 sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
440 sstrncpy (vl.type, type, sizeof (vl.type));
441 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
443 plugin_dispatch_values (&vl);
446 static void apc_submit (struct apc_detail_s *apcups_detail)
448 apc_submit_generic ("voltage", "input", apcups_detail->linev);
449 apc_submit_generic ("voltage", "output", apcups_detail->outputv);
450 apc_submit_generic ("voltage", "battery", apcups_detail->battv);
451 apc_submit_generic ("charge", "", apcups_detail->bcharge);
452 apc_submit_generic ("percent", "load", apcups_detail->loadpct);
453 apc_submit_generic ("timeleft", "", apcups_detail->timeleft);
454 apc_submit_generic ("temperature", "", apcups_detail->itemp);
455 apc_submit_generic ("frequency", "input", apcups_detail->linefreq);
458 static int apcups_read (void)
460 struct apc_detail_s apcups_detail;
463 apcups_detail.linev = -1.0;
464 apcups_detail.outputv = -1.0;
465 apcups_detail.battv = -1.0;
466 apcups_detail.loadpct = -1.0;
467 apcups_detail.bcharge = -1.0;
468 apcups_detail.timeleft = NAN;
469 apcups_detail.itemp = -300.0;
470 apcups_detail.linefreq = -1.0;
472 status = apc_query_server (conf_host == NULL
473 ? APCUPS_DEFAULT_HOST
475 conf_port, &apcups_detail);
478 * if we did not connect then do not bother submitting
479 * zeros. We want rrd files to have NAN.
483 DEBUG ("apc_query_server (%s, %i) = %i",
485 ? APCUPS_DEFAULT_HOST
491 apc_submit (&apcups_detail);
496 void module_register (void)
498 plugin_register_config ("apcups", apcups_config, config_keys,
500 plugin_register_read ("apcups", apcups_read);
501 plugin_register_shutdown ("apcups", apcups_shutdown);
502 } /* void module_register */