e1b0178492e7dfe5bc65852126b1da271b3730be
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, nread;
143 nleft = nbytes;
145 while (nleft > 0) {
146 do {
147 nread = read (fd, ptr, nleft);
148 } while (nread == -1 && (errno == EINTR || errno == EAGAIN));
150 if (nread <= 0) {
151 return (nread); /* error, or EOF */
152 }
154 nleft -= nread;
155 ptr += nread;
156 }
158 return (nbytes - nleft); /* return >= 0 */
159 }
161 /*
162 * Write nbytes to the network.
163 * It may require several writes.
164 */
165 static int write_nbytes (int fd, void *buf, int buflen)
166 {
167 int nleft;
168 int nwritten;
169 char *ptr;
171 ptr = (char *) buf;
173 nleft = buflen;
174 while (nleft > 0)
175 {
176 nwritten = write (fd, ptr, nleft);
178 if (nwritten <= 0)
179 {
180 syslog (LOG_ERR, "Writing to socket failed: %s", strerror (errno));
181 return (nwritten);
182 }
184 nleft -= nwritten;
185 ptr += nwritten;
186 }
188 /* If we get here, (nleft <= 0) is true */
189 return (buflen);
190 }
192 /* Close the network connection */
193 static void net_close (int sockfd)
194 {
195 short pktsiz = 0;
197 /* send EOF sentinel */
198 write_nbytes (sockfd, &pktsiz, sizeof (short));
199 close (sockfd);
200 }
203 /*
204 * Open a TCP connection to the UPS network server
205 * Returns -1 on error
206 * Returns socket file descriptor otherwise
207 */
208 static int net_open (char *host, char *service, int port)
209 {
210 int sd;
211 int status;
212 char port_str[8];
213 struct addrinfo ai_hints;
214 struct addrinfo *ai_return;
215 struct addrinfo *ai_list;
217 assert ((port > 0x00000000) && (port <= 0x0000FFFF));
219 /* Convert the port to a string */
220 snprintf (port_str, 8, "%i", port);
221 port_str[7] = '\0';
223 /* Resolve name */
224 memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
225 ai_hints.ai_family = AF_INET; /* XXX: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
226 ai_hints.ai_socktype = SOCK_STREAM;
228 status = getaddrinfo (host, port_str, &ai_hints, &ai_return);
229 if (status != 0)
230 {
231 DBG ("getaddrinfo failed: %s", status == EAI_SYSTEM ? strerror (errno) : gai_strerror (status));
232 return (-1);
233 }
235 /* Create socket */
236 sd = -1;
237 for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
238 {
239 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
240 if (sd >= 0)
241 break;
242 }
243 /* `ai_list' still holds the current description of the socket.. */
245 if (sd < 0)
246 {
247 DBG ("Unable to open a socket");
248 freeaddrinfo (ai_return);
249 return (-1);
250 }
252 status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
254 freeaddrinfo (ai_return);
256 if (status != 0) /* `connect(2)' failed */
257 {
258 DBG ("connect failed: %s", strerror (errno));
259 return (-1);
260 }
262 return (sd);
263 } /* int net_open (char *host, char *service, int port) */
265 /*
266 * Receive a message from the other end. Each message consists of
267 * two packets. The first is a header that contains the size
268 * of the data that follows in the second packet.
269 * Returns number of bytes read
270 * Returns 0 on end of file
271 * Returns -1 on hard end of file (i.e. network connection close)
272 * Returns -2 on error
273 */
274 static int net_recv (int sockfd, char *buf, int buflen)
275 {
276 int nbytes;
277 short pktsiz;
279 /* get data size -- in short */
280 if ((nbytes = read_nbytes (sockfd, (char *) &pktsiz, sizeof (short))) <= 0)
281 return (-1);
283 if (nbytes != sizeof (short))
284 return (-2);
286 pktsiz = ntohs (pktsiz);
287 if (pktsiz > buflen)
288 {
289 DBG ("record length too large");
290 return (-2);
291 }
293 if (pktsiz == 0)
294 return (0);
296 /* now read the actual data */
297 if ((nbytes = read_nbytes (sockfd, buf, pktsiz)) <= 0)
298 return (-2);
300 if (nbytes != pktsiz)
301 return (-2);
303 return (nbytes);
304 } /* static int net_recv (int sockfd, char *buf, int buflen) */
306 /*
307 * Send a message over the network. The send consists of
308 * two network packets. The first is sends a short containing
309 * the length of the data packet which follows.
310 * Returns zero on success
311 * Returns non-zero on error
312 */
313 static int net_send (int sockfd, char *buff, int len)
314 {
315 int rc;
316 short packet_size;
318 /* send short containing size of data packet */
319 packet_size = htons ((short) len);
321 rc = write_nbytes (sockfd, &packet_size, sizeof (packet_size));
322 if (rc != sizeof (packet_size))
323 return (-1);
325 /* send data packet */
326 rc = write_nbytes (sockfd, buff, len);
327 if (rc != len)
328 return (-1);
330 return (0);
331 }
333 /* Get and print status from apcupsd NIS server */
334 static int apc_query_server (char *host, int port,
335 struct apc_detail_s *apcups_detail)
336 {
337 int sockfd;
338 int n;
339 char recvline[1024];
340 char *tokptr;
341 char *key;
342 double value;
344 static int complain = 0;
346 #if APCMAIN
347 # define PRINT_VALUE(name, val) printf(" Found property: name = %s; value = %f;\n", name, val)
348 #else
349 # define PRINT_VALUE(name, val) /**/
350 #endif
352 /* TODO: Keep the socket open, if possible */
353 if ((sockfd = net_open (host, NULL, port)) < 0)
354 {
355 /* Complain once every six hours. */
356 int complain_step = 21600 / atoi (COLLECTD_STEP);
358 if ((complain % complain_step) == 0)
359 syslog (LOG_ERR, "apcups plugin: Connecting to the apcupsd failed.");
360 complain++;
362 return (-1);
363 }
364 complain = 0;
366 if (net_send (sockfd, "status", 6) < 0)
367 {
368 syslog (LOG_ERR, "apcups plugin: Writing to the socket failed.");
369 return (-1);
370 }
372 /* XXX: Do we read `n' or `n-1' bytes? */
373 while ((n = net_recv (sockfd, recvline, sizeof (recvline) - 1)) > 0)
374 {
375 assert (n < sizeof (recvline));
376 recvline[n] = '\0';
377 #if APCMAIN
378 printf ("net_recv = `%s';\n", recvline);
379 #endif /* if APCMAIN */
381 tokptr = strtok (recvline, ":");
382 while (tokptr != NULL)
383 {
384 key = tokptr;
385 if ((tokptr = strtok (NULL, " \t")) == NULL)
386 continue;
387 value = atof (tokptr);
388 PRINT_VALUE (key, value);
390 if (strcmp ("LINEV", key) == 0)
391 apcups_detail->linev = value;
392 else if (strcmp ("BATTV", tokptr) == 0)
393 apcups_detail->battv = value;
394 else if (strcmp ("ITEMP", tokptr) == 0)
395 apcups_detail->itemp = value;
396 else if (strcmp ("LOADPCT", tokptr) == 0)
397 apcups_detail->loadpct = value;
398 else if (strcmp ("BCHARGE", tokptr) == 0)
399 apcups_detail->bcharge = value;
400 else if (strcmp ("OUTPUTV", tokptr) == 0)
401 apcups_detail->outputv = value;
402 else if (strcmp ("LINEFREQ", tokptr) == 0)
403 apcups_detail->linefreq = value;
404 else if (strcmp ("TIMELEFT", tokptr) == 0)
405 apcups_detail->timeleft = value;
406 else
407 {
408 syslog (LOG_WARNING, "apcups plugin: Received unknown property from apcupsd: `%s' = %f",
409 key, value);
410 }
412 tokptr = strtok (NULL, ":");
413 } /* while (tokptr != NULL) */
414 }
416 net_close (sockfd);
418 if (n < 0)
419 {
420 syslog (LOG_WARNING, "apcups plugin: Error reading from socket");
421 return (-1);
422 }
424 return (0);
425 }
427 #if APCMAIN
428 /*
429 * This is used for testing apcups in a standalone mode.
430 * Usefull for debugging.
431 */
432 int main (int argc, char **argv)
433 {
434 /* we are not really going to use this */
435 struct apc_detail_s apcups_detail;
437 openlog ("apcups", LOG_PID | LOG_NDELAY | LOG_LOCAL1);
439 if (!*host || strcmp (host, "0.0.0.0") == 0)
440 host = "localhost";
442 if(do_apc_status (host, port, &apcups_detail) < 0)
443 {
444 printf("apcups: Failed...\n");
445 return(-1);
446 }
448 apc_query_server (global_host, global_port, &apcups_detail);
450 return 0;
451 }
452 #else
453 static int apcups_config (char *key, char *value)
454 {
455 if (strcasecmp (key, "host") == 0)
456 {
457 if (global_host != NULL)
458 {
459 free (global_host);
460 global_host = NULL;
461 }
462 if ((global_host = strdup (value)) == NULL)
463 return (1);
464 }
465 else if (strcasecmp (key, "Port") == 0)
466 {
467 int port_tmp = atoi (value);
468 if (port_tmp < 1 || port_tmp > 65535)
469 {
470 syslog (LOG_WARNING, "apcups plugin: Invalid port: %i", port_tmp);
471 return (1);
472 }
473 global_port = port_tmp;
474 }
475 else
476 {
477 return (-1);
478 }
479 return (0);
480 }
482 static void apcups_init (void)
483 {
484 return;
485 }
487 static void apc_write_voltage (char *host, char *inst, char *val)
488 {
489 char file[512];
490 int status;
492 status = snprintf (file, 512, bvolt_file_template, inst);
493 if ((status < 1) || (status >= 512))
494 return;
496 rrd_update_file (host, file, val, bvolt_ds_def, bvolt_ds_num);
497 }
499 static void apc_write_charge (char *host, char *inst, char *val)
500 {
501 rrd_update_file (host, charge_file_template, val, charge_ds_def, charge_ds_num);
502 }
504 static void apc_write_percent (char *host, char *inst, char *val)
505 {
506 rrd_update_file (host, load_file_template, val, load_ds_def, load_ds_num);
507 }
509 static void apc_write_timeleft (char *host, char *inst, char *val)
510 {
511 rrd_update_file (host, time_file_template, val, time_ds_def, time_ds_num);
512 }
514 static void apc_write_temperature (char *host, char *inst, char *val)
515 {
516 rrd_update_file (host, temp_file_template, val, temp_ds_def, temp_ds_num);
517 }
519 static void apc_write_frequency (char *host, char *inst, char *val)
520 {
521 char file[512];
522 int status;
524 status = snprintf (file, 512, freq_file_template, inst);
525 if ((status < 1) || (status >= 512))
526 return;
528 rrd_update_file (host, file, val, freq_ds_def, freq_ds_num);
529 }
531 static void apc_submit_generic (char *type, char *inst,
532 double value)
533 {
534 char buf[512];
535 int status;
537 status = snprintf (buf, 512, "%u:%f",
538 (unsigned int) curtime, value);
539 if ((status < 1) || (status >= 512))
540 return;
542 plugin_submit (type, inst, buf);
543 }
545 static void apc_submit (struct apc_detail_s *apcups_detail)
546 {
547 apc_submit_generic ("apcups_voltage", "input", apcups_detail->linev);
548 apc_submit_generic ("apcups_voltage", "output", apcups_detail->outputv);
549 apc_submit_generic ("apcups_voltage", "battery", apcups_detail->battv);
550 apc_submit_generic ("apcups_charge", "-", apcups_detail->bcharge);
551 apc_submit_generic ("apcups_charge_pct", "-", apcups_detail->loadpct);
552 apc_submit_generic ("apcups_timeleft", "-", apcups_detail->timeleft);
553 apc_submit_generic ("apcups_temp", "-", apcups_detail->itemp);
554 apc_submit_generic ("apcups_frequency", "input", apcups_detail->linefreq);
555 }
557 static void apcups_read (void)
558 {
559 struct apc_detail_s apcups_detail;
560 int status;
562 if (global_host == NULL)
563 return;
565 apcups_detail.linev = -1.0;
566 apcups_detail.outputv = -1.0;
567 apcups_detail.battv = -1.0;
568 apcups_detail.loadpct = -1.0;
569 apcups_detail.bcharge = -1.0;
570 apcups_detail.timeleft = -1.0;
571 apcups_detail.itemp = -300.0;
572 apcups_detail.linefreq = -1.0;
574 status = apc_query_server (global_host, global_port, &apcups_detail);
576 /*
577 * if we did not connect then do not bother submitting
578 * zeros. We want rrd files to have NAN.
579 */
580 if (status != 0)
581 return;
583 apc_submit (&apcups_detail);
584 } /* apcups_read */
586 void module_register (void)
587 {
588 plugin_register (MODULE_NAME, apcups_init, apcups_read, NULL);
589 plugin_register ("apcups_voltage", NULL, NULL, apc_write_voltage);
590 plugin_register ("apcups_charge", NULL, NULL, apc_write_charge);
591 plugin_register ("apcups_charge_pct", NULL, NULL, apc_write_percent);
592 plugin_register ("apcups_timeleft", NULL, NULL, apc_write_timeleft);
593 plugin_register ("apcups_temp", NULL, NULL, apc_write_temperature);
594 plugin_register ("apcups_frequency", NULL, NULL, apc_write_frequency);
595 cf_register (MODULE_NAME, apcups_config, config_keys, config_keys_num);
596 }
598 #endif /* if APCMAIN */
599 #undef MODULE_NAME