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>
29 #include "common.h" /* rrd_update_file */
30 #include "plugin.h" /* plugin_register, plugin_submit */
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"
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;
77 static bool conf_persistent_conn = true;
79 static int global_sockfd = -1;
81 static int count_retries = 0;
82 static int count_iterations = 0;
84 static int net_shutdown(int *fd) {
85 uint16_t packet_size = 0;
87 if ((fd == NULL) || (*fd < 0))
90 (void)swrite(*fd, (void *)&packet_size, sizeof(packet_size));
95 } /* int net_shutdown */
97 /* Close the network connection */
98 static int apcups_shutdown(void) {
99 if (global_sockfd < 0)
102 net_shutdown(&global_sockfd);
104 } /* int apcups_shutdown */
107 * Open a TCP connection to the UPS network server
108 * Returns -1 on error
109 * Returns socket file descriptor otherwise
111 static int net_open(char const *node, char const *service) {
114 struct addrinfo *ai_return;
115 struct addrinfo *ai_list;
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};
120 status = getaddrinfo(node, service, &ai_hints, &ai_return);
122 INFO("apcups plugin: getaddrinfo failed: %s",
123 (status == EAI_SYSTEM) ? STRERRNO : gai_strerror(status));
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);
134 /* `ai_list' still holds the current description of the socket.. */
137 DEBUG("apcups plugin: Unable to open a socket");
138 freeaddrinfo(ai_return);
142 status = connect(sd, ai_list->ai_addr, ai_list->ai_addrlen);
144 freeaddrinfo(ai_return);
146 if (status != 0) /* `connect(2)' failed */
148 INFO("apcups plugin: connect failed: %s", STRERRNO);
153 DEBUG("apcups plugin: Done opening a socket %i", sd);
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
167 static int net_recv(int *sockfd, char *buf, int buflen) {
168 uint16_t packet_size;
170 /* get data size -- in short */
171 if (sread(*sockfd, (void *)&packet_size, sizeof(packet_size)) != 0) {
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);
187 if (packet_size == 0)
190 /* now read the actual data */
191 if (sread(*sockfd, (void *)buf, packet_size) != 0) {
197 return (int)packet_size;
198 } /* static int net_recv (int *sockfd, char *buf, int buflen) */
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
207 static int net_send(int *sockfd, const char *buff, int len) {
208 uint16_t packet_size;
211 assert(*sockfd >= 0);
213 /* send short containing size of data packet */
214 packet_size = htons((uint16_t)len);
216 if (swrite(*sockfd, (void *)&packet_size, sizeof(packet_size)) != 0) {
222 /* send data packet */
223 if (swrite(*sockfd, (void *)buff, len) != 0) {
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) {
244 #define PRINT_VALUE(name, val) \
245 printf(" Found property: name = %s; value = %f;\n", name, val)
247 #define PRINT_VALUE(name, val) /**/
251 if (global_sockfd < 0) {
252 global_sockfd = net_open(node, service);
253 if (global_sockfd < 0) {
254 ERROR("apcups plugin: Connecting to the "
260 status = net_send(&global_sockfd, "status", strlen("status"));
262 /* net_send closes the socket on error. */
263 assert(global_sockfd < 0);
271 ERROR("apcups plugin: Writing to the socket failed.");
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. */
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 = false;
291 while ((n = net_recv(&global_sockfd, recvline, sizeof(recvline) - 1)) > 0) {
292 assert((size_t)n < sizeof(recvline));
295 printf("net_recv = `%s';\n", recvline);
296 #endif /* if APCMAIN */
299 tokptr = strtok_r(recvline, " :\t", &toksaveptr);
300 while (tokptr != NULL) {
302 if ((tokptr = strtok_r(NULL, " :\t", &toksaveptr)) == NULL)
306 if (strtogauge(tokptr, &value) != 0)
309 PRINT_VALUE(key, value);
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
328 if (conf_report_seconds)
330 apcups_detail->timeleft = value;
333 tokptr = strtok_r(NULL, ":", &toksaveptr);
334 } /* while (tokptr != NULL) */
336 status = errno; /* save errno, net_shutdown() may re-set it. */
338 if (!conf_persistent_conn)
339 net_shutdown(&global_sockfd);
342 ERROR("apcups plugin: Reading from socket failed: %s", STRERROR(status));
349 static int apcups_config(oconfig_item_t *ci) {
350 bool persistent_conn_set = false;
352 for (int i = 0; i < ci->children_num; i++) {
353 oconfig_item_t *child = ci->children + i;
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 = true;
365 ERROR("apcups plugin: Unknown config option \"%s\".", child->key);
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 = false;
380 } /* int apcups_config */
382 static void apc_submit_generic(const char *type, const char *type_inst,
387 value_list_t vl = VALUE_LIST_INIT;
388 vl.values = &(value_t){.gauge = value};
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));
394 plugin_dispatch_values(&vl);
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);
408 static int apcups_read(void) {
409 apc_detail_t apcups_detail = {
420 int status = apc_query_server(conf_node, conf_service, &apcups_detail);
423 DEBUG("apcups plugin: apc_query_server (\"%s\", \"%s\") = %d", conf_node,
424 conf_service, status);
428 apc_submit(&apcups_detail);
433 static int apcups_init(void) {
434 if (conf_node == NULL)
435 conf_node = APCUPS_DEFAULT_NODE;
437 if (conf_service == NULL)
438 conf_service = APCUPS_DEFAULT_SERVICE;
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 */