1 /*
2 * collectd - src/apcups.c
3 * Copyright (C) 2006 Anthony Gialluca <tonyabg at charter.net>
4 * Copyright (C) 2000-2004 Kern Sibbald
5 * Copyright (C) 1996-99 Andre M. Hedrick <andre at suse.com>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of version 2 of the GNU General
9 * Public License as published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public
17 * License along with this program; if not, write to the Free
18 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
19 * MA 02111-1307, USA.
20 *
21 * Authors:
22 * Anthony Gialluca <tonyabg at charter.net>
23 **/
25 /*
26 * FIXME: Don't know why but without this here atof() was not returning
27 * correct values for me. This is behavior that I don't understand and
28 * should be examined in closer detail.
29 */
30 #include <stdlib.h>
32 #include "collectd.h"
33 #include "common.h" /* rrd_update_file */
34 #include "plugin.h" /* plugin_register, plugin_submit */
35 #include "configfile.h" /* cf_register */
36 #include "utils_debug.h"
38 #if HAVE_SYS_TYPES_H
39 # include <sys/types.h>
40 #endif
41 #if HAVE_SYS_SOCKET_H
42 # include <sys/socket.h>
43 #endif
44 #if HAVE_NETDB_H
45 # include <netdb.h>
46 #endif
47 #if HAVE_NETINET_IN_H
48 # include <netinet/in.h>
49 #endif
51 #ifndef APCMAIN
52 # define APCMAIN 0
53 #endif
55 #define NISPORT 3551
56 #define MAXSTRING 256
57 #define MODULE_NAME "apcups"
59 /* Default values for contacting daemon */
60 static char *global_host = NULL;
61 static int global_port = NISPORT;
63 /*
64 * The following are only if not compiled to test the module with its own main.
65 */
66 #if !APCMAIN
67 static char *bvolt_file_template = "apcups/voltage-%s.rrd";
68 static char *bvolt_ds_def[] =
69 {
70 "DS:voltage:GAUGE:"COLLECTD_HEARTBEAT":0:U",
71 };
72 static int bvolt_ds_num = 1;
74 static char *load_file_template = "apcups/charge_percent.rrd";
75 static char *load_ds_def[] =
76 {
77 "DS:percent:GAUGE:"COLLECTD_HEARTBEAT":0:100",
78 };
79 static int load_ds_num = 1;
81 static char *charge_file_template = "apcups/charge.rrd";
82 static char *charge_ds_def[] =
83 {
84 "DS:charge:GAUGE:"COLLECTD_HEARTBEAT":0:U",
85 };
86 static int charge_ds_num = 1;
88 static char *time_file_template = "apcups/time.rrd";
89 static char *time_ds_def[] =
90 {
91 "DS:timeleft:GAUGE:"COLLECTD_HEARTBEAT":0:100",
92 };
93 static int time_ds_num = 1;
95 static char *temp_file_template = "apcups/temperature.rrd";
96 static char *temp_ds_def[] =
97 {
98 /* -273.15 is absolute zero */
99 "DS:temperature:GAUGE:"COLLECTD_HEARTBEAT":-274:U",
100 };
101 static int temp_ds_num = 1;
103 static char *freq_file_template = "apcups/frequency-%s.rrd";
104 static char *freq_ds_def[] =
105 {
106 "DS:frequency:GAUGE:"COLLECTD_HEARTBEAT":0:U",
107 };
108 static int freq_ds_num = 1;
110 static char *config_keys[] =
111 {
112 "Host",
113 "Port",
114 NULL
115 };
116 static int config_keys_num = 2;
118 #endif /* if APCMAIN */
120 struct apc_detail_s
121 {
122 double linev;
123 double loadpct;
124 double bcharge;
125 double timeleft;
126 double outputv;
127 double itemp;
128 double battv;
129 double linefreq;
130 };
132 #define BIG_BUF 4096
134 /*
135 * Read nbytes from the network.
136 * It is possible that the total bytes require in several
137 * read requests
138 */
139 static int read_nbytes (int *fd, char *ptr, int nbytes)
140 {
141 int nleft;
142 int nread;
144 nleft = nbytes;
145 nread = -1;
147 assert (*fd >= 0);
149 while ((nleft > 0) && (nread != 0))
150 {
151 nread = read (*fd, ptr, nleft);
153 if (nread == -1 && (errno == EINTR || errno == EAGAIN))
154 continue;
156 if (nread == -1)
157 {
158 *fd = -1;
159 syslog (LOG_ERR, "apcups plugin: write failed: %s", strerror (errno));
160 return (-1);
161 }
163 nleft -= nread;
164 ptr += nread;
165 }
167 return (nbytes - nleft);
168 }
170 /*
171 * Write nbytes to the network.
172 * It may require several writes.
173 */
174 static int write_nbytes (int *fd, void *buf, int buflen)
175 {
176 int nleft;
177 int nwritten;
178 char *ptr;
180 assert (buflen > 0);
181 assert (*fd >= 0);
183 ptr = (char *) buf;
185 nleft = buflen;
186 while (nleft > 0)
187 {
188 nwritten = write (*fd, ptr, nleft);
190 if ((nwritten == -1) && ((errno == EAGAIN) || (errno == EINTR)))
191 continue;
193 if (nwritten == -1)
194 {
195 syslog (LOG_ERR, "Writing to socket failed: %s", strerror (errno));
196 *fd = -1;
197 return (-1);
198 }
200 nleft -= nwritten;
201 ptr += nwritten;
202 }
204 /* If we get here, (nleft <= 0) is true */
205 return (buflen);
206 }
208 #if 0
209 /* Close the network connection */
210 static void net_close (int *fd)
211 {
212 short pktsiz = 0;
214 assert (*fd >= 0);
216 /* send EOF sentinel */
217 write_nbytes (fd, &pktsiz, sizeof (short));
219 close (*fd);
220 *fd = -1;
221 }
222 #endif
225 /*
226 * Open a TCP connection to the UPS network server
227 * Returns -1 on error
228 * Returns socket file descriptor otherwise
229 */
230 static int net_open (char *host, char *service, int port)
231 {
232 int sd;
233 int status;
234 char port_str[8];
235 struct addrinfo ai_hints;
236 struct addrinfo *ai_return;
237 struct addrinfo *ai_list;
239 assert ((port > 0x00000000) && (port <= 0x0000FFFF));
241 /* Convert the port to a string */
242 snprintf (port_str, 8, "%i", port);
243 port_str[7] = '\0';
245 /* Resolve name */
246 memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
247 ai_hints.ai_family = AF_INET; /* XXX: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
248 ai_hints.ai_socktype = SOCK_STREAM;
250 status = getaddrinfo (host, port_str, &ai_hints, &ai_return);
251 if (status != 0)
252 {
253 DBG ("getaddrinfo failed: %s", status == EAI_SYSTEM ? strerror (errno) : gai_strerror (status));
254 return (-1);
255 }
257 /* Create socket */
258 sd = -1;
259 for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
260 {
261 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
262 if (sd >= 0)
263 break;
264 }
265 /* `ai_list' still holds the current description of the socket.. */
267 if (sd < 0)
268 {
269 DBG ("Unable to open a socket");
270 freeaddrinfo (ai_return);
271 return (-1);
272 }
274 status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
276 freeaddrinfo (ai_return);
278 if (status != 0) /* `connect(2)' failed */
279 {
280 DBG ("connect failed: %s", strerror (errno));
281 return (-1);
282 }
284 return (sd);
285 } /* int net_open (char *host, char *service, int port) */
287 /*
288 * Receive a message from the other end. Each message consists of
289 * two packets. The first is a header that contains the size
290 * of the data that follows in the second packet.
291 * Returns number of bytes read
292 * Returns 0 on end of file
293 * Returns -1 on hard end of file (i.e. network connection close)
294 * Returns -2 on error
295 */
296 static int net_recv (int *sockfd, char *buf, int buflen)
297 {
298 int nbytes;
299 short pktsiz;
301 /* get data size -- in short */
302 if ((nbytes = read_nbytes (sockfd, (char *) &pktsiz, sizeof (short))) <= 0)
303 return (-1);
305 if (nbytes != sizeof (short))
306 return (-2);
308 pktsiz = ntohs (pktsiz);
309 if (pktsiz > buflen)
310 {
311 DBG ("record length too large");
312 return (-2);
313 }
315 if (pktsiz == 0)
316 return (0);
318 /* now read the actual data */
319 if ((nbytes = read_nbytes (sockfd, buf, pktsiz)) <= 0)
320 return (-2);
322 if (nbytes != pktsiz)
323 return (-2);
325 return (nbytes);
326 } /* static int net_recv (int sockfd, char *buf, int buflen) */
328 /*
329 * Send a message over the network. The send consists of
330 * two network packets. The first is sends a short containing
331 * the length of the data packet which follows.
332 * Returns zero on success
333 * Returns non-zero on error
334 */
335 static int net_send (int *sockfd, char *buff, int len)
336 {
337 int rc;
338 short packet_size;
340 assert (len > 0);
342 /* send short containing size of data packet */
343 packet_size = htons ((short) len);
345 rc = write_nbytes (sockfd, &packet_size, sizeof (packet_size));
346 if (rc != sizeof (packet_size))
347 return (-1);
349 /* send data packet */
350 rc = write_nbytes (sockfd, buff, len);
351 if (rc != len)
352 return (-1);
354 return (0);
355 }
357 /* Get and print status from apcupsd NIS server */
358 static int apc_query_server (char *host, int port,
359 struct apc_detail_s *apcups_detail)
360 {
361 int n;
362 char recvline[1024];
363 char *tokptr;
364 char *key;
365 double value;
367 static int sockfd = -1;
368 static int complain = 0;
370 #if APCMAIN
371 # define PRINT_VALUE(name, val) printf(" Found property: name = %s; value = %f;\n", name, val)
372 #else
373 # define PRINT_VALUE(name, val) /**/
374 #endif
376 if (sockfd < 0)
377 {
378 if ((sockfd = net_open (host, NULL, port)) < 0)
379 {
380 /* Complain once every six hours. */
381 int complain_step = 21600 / atoi (COLLECTD_STEP);
383 if ((complain % complain_step) == 0)
384 syslog (LOG_ERR, "apcups plugin: Connecting to the apcupsd failed.");
385 complain++;
387 return (-1);
388 }
389 complain = 0;
390 }
392 if (net_send (&sockfd, "status", 6) < 0)
393 {
394 syslog (LOG_ERR, "apcups plugin: Writing to the socket failed.");
395 return (-1);
396 }
398 /* XXX: Do we read `n' or `n-1' bytes? */
399 while ((n = net_recv (&sockfd, recvline, sizeof (recvline) - 1)) > 0)
400 {
401 assert (n < sizeof (recvline));
402 recvline[n] = '\0';
403 #if APCMAIN
404 printf ("net_recv = `%s';\n", recvline);
405 #endif /* if APCMAIN */
407 tokptr = strtok (recvline, ":");
408 while (tokptr != NULL)
409 {
410 key = tokptr;
411 if ((tokptr = strtok (NULL, " \t")) == NULL)
412 continue;
413 value = atof (tokptr);
414 PRINT_VALUE (key, value);
416 if (strcmp ("LINEV", key) == 0)
417 apcups_detail->linev = value;
418 else if (strcmp ("BATTV", tokptr) == 0)
419 apcups_detail->battv = value;
420 else if (strcmp ("ITEMP", tokptr) == 0)
421 apcups_detail->itemp = value;
422 else if (strcmp ("LOADPCT", tokptr) == 0)
423 apcups_detail->loadpct = value;
424 else if (strcmp ("BCHARGE", tokptr) == 0)
425 apcups_detail->bcharge = value;
426 else if (strcmp ("OUTPUTV", tokptr) == 0)
427 apcups_detail->outputv = value;
428 else if (strcmp ("LINEFREQ", tokptr) == 0)
429 apcups_detail->linefreq = value;
430 else if (strcmp ("TIMELEFT", tokptr) == 0)
431 apcups_detail->timeleft = value;
432 else
433 {
434 syslog (LOG_WARNING, "apcups plugin: Received unknown property from apcupsd: `%s' = %f",
435 key, value);
436 }
438 tokptr = strtok (NULL, ":");
439 } /* while (tokptr != NULL) */
440 }
442 if (n < 0)
443 {
444 syslog (LOG_WARNING, "apcups plugin: Error reading from socket");
445 return (-1);
446 }
448 return (0);
449 }
451 #if APCMAIN
452 /*
453 * This is used for testing apcups in a standalone mode.
454 * Usefull for debugging.
455 */
456 int main (int argc, char **argv)
457 {
458 /* we are not really going to use this */
459 struct apc_detail_s apcups_detail;
461 openlog ("apcups", LOG_PID | LOG_NDELAY | LOG_LOCAL1);
463 if (!*host || strcmp (host, "0.0.0.0") == 0)
464 host = "localhost";
466 if(do_apc_status (host, port, &apcups_detail) < 0)
467 {
468 printf("apcups: Failed...\n");
469 return(-1);
470 }
472 apc_query_server (global_host, global_port, &apcups_detail);
474 return 0;
475 }
476 #else
477 static int apcups_config (char *key, char *value)
478 {
479 if (strcasecmp (key, "host") == 0)
480 {
481 if (global_host != NULL)
482 {
483 free (global_host);
484 global_host = NULL;
485 }
486 if ((global_host = strdup (value)) == NULL)
487 return (1);
488 }
489 else if (strcasecmp (key, "Port") == 0)
490 {
491 int port_tmp = atoi (value);
492 if (port_tmp < 1 || port_tmp > 65535)
493 {
494 syslog (LOG_WARNING, "apcups plugin: Invalid port: %i", port_tmp);
495 return (1);
496 }
497 global_port = port_tmp;
498 }
499 else
500 {
501 return (-1);
502 }
503 return (0);
504 }
506 static void apcups_init (void)
507 {
508 return;
509 }
511 static void apc_write_voltage (char *host, char *inst, char *val)
512 {
513 char file[512];
514 int status;
516 status = snprintf (file, 512, bvolt_file_template, inst);
517 if ((status < 1) || (status >= 512))
518 return;
520 rrd_update_file (host, file, val, bvolt_ds_def, bvolt_ds_num);
521 }
523 static void apc_write_charge (char *host, char *inst, char *val)
524 {
525 rrd_update_file (host, charge_file_template, val, charge_ds_def, charge_ds_num);
526 }
528 static void apc_write_percent (char *host, char *inst, char *val)
529 {
530 rrd_update_file (host, load_file_template, val, load_ds_def, load_ds_num);
531 }
533 static void apc_write_timeleft (char *host, char *inst, char *val)
534 {
535 rrd_update_file (host, time_file_template, val, time_ds_def, time_ds_num);
536 }
538 static void apc_write_temperature (char *host, char *inst, char *val)
539 {
540 rrd_update_file (host, temp_file_template, val, temp_ds_def, temp_ds_num);
541 }
543 static void apc_write_frequency (char *host, char *inst, char *val)
544 {
545 char file[512];
546 int status;
548 status = snprintf (file, 512, freq_file_template, inst);
549 if ((status < 1) || (status >= 512))
550 return;
552 rrd_update_file (host, file, val, freq_ds_def, freq_ds_num);
553 }
555 static void apc_submit_generic (char *type, char *inst,
556 double value)
557 {
558 char buf[512];
559 int status;
561 status = snprintf (buf, 512, "%u:%f",
562 (unsigned int) curtime, value);
563 if ((status < 1) || (status >= 512))
564 return;
566 plugin_submit (type, inst, buf);
567 }
569 static void apc_submit (struct apc_detail_s *apcups_detail)
570 {
571 apc_submit_generic ("apcups_voltage", "input", apcups_detail->linev);
572 apc_submit_generic ("apcups_voltage", "output", apcups_detail->outputv);
573 apc_submit_generic ("apcups_voltage", "battery", apcups_detail->battv);
574 apc_submit_generic ("apcups_charge", "-", apcups_detail->bcharge);
575 apc_submit_generic ("apcups_charge_pct", "-", apcups_detail->loadpct);
576 apc_submit_generic ("apcups_timeleft", "-", apcups_detail->timeleft);
577 apc_submit_generic ("apcups_temp", "-", apcups_detail->itemp);
578 apc_submit_generic ("apcups_frequency", "input", apcups_detail->linefreq);
579 }
581 static void apcups_read (void)
582 {
583 struct apc_detail_s apcups_detail;
584 int status;
586 if (global_host == NULL)
587 return;
589 apcups_detail.linev = -1.0;
590 apcups_detail.outputv = -1.0;
591 apcups_detail.battv = -1.0;
592 apcups_detail.loadpct = -1.0;
593 apcups_detail.bcharge = -1.0;
594 apcups_detail.timeleft = -1.0;
595 apcups_detail.itemp = -300.0;
596 apcups_detail.linefreq = -1.0;
598 status = apc_query_server (global_host, global_port, &apcups_detail);
600 /*
601 * if we did not connect then do not bother submitting
602 * zeros. We want rrd files to have NAN.
603 */
604 if (status != 0)
605 return;
607 apc_submit (&apcups_detail);
608 } /* apcups_read */
610 void module_register (void)
611 {
612 plugin_register (MODULE_NAME, apcups_init, apcups_read, NULL);
613 plugin_register ("apcups_voltage", NULL, NULL, apc_write_voltage);
614 plugin_register ("apcups_charge", NULL, NULL, apc_write_charge);
615 plugin_register ("apcups_charge_pct", NULL, NULL, apc_write_percent);
616 plugin_register ("apcups_timeleft", NULL, NULL, apc_write_timeleft);
617 plugin_register ("apcups_temp", NULL, NULL, apc_write_temperature);
618 plugin_register ("apcups_frequency", NULL, NULL, apc_write_frequency);
619 cf_register (MODULE_NAME, apcups_config, config_keys, config_keys_num);
620 }
622 #endif /* if APCMAIN */
623 #undef MODULE_NAME