octo@casella:~/collectd $ svn merge -r784:HEAD branches/apcups trunk
[collectd.git] / src / apcups.c
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  **/
24
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>
31
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"
37
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
48 #if HAVE_NETINET_IN_H
49 # include <netinet/in.h>
50 #endif
51
52 #ifndef APCMAIN
53 # define APCMAIN 0
54 #endif
55
56 #define NISPORT 3551
57 #define MAXSTRING               256
58 #define MODULE_NAME "apcups"
59
60 #define APCUPS_DEFAULT_HOST "localhost"
61
62 /* Default values for contacting daemon */
63 static char *global_host = NULL;
64 static int   global_port = NISPORT;
65
66 /* 
67  * The following are only if not compiled to test the module with its own main.
68 */
69 #if !APCMAIN
70 static char *bvolt_file_template = "apcups/voltage-%s.rrd";
71 static char *bvolt_ds_def[] = 
72 {
73         "DS:voltage:GAUGE:"COLLECTD_HEARTBEAT":0:U",
74 };
75 static int bvolt_ds_num = 1;
76
77 static char *load_file_template = "apcups/load_percent.rrd";
78 static char *load_ds_def[] = 
79 {
80         "DS:percent:GAUGE:"COLLECTD_HEARTBEAT":0:110",
81 };
82 static int load_ds_num = 1;
83
84 static char *charge_file_template = "apcups/charge_percent.rrd";
85 static char *charge_ds_def[] = 
86 {
87         "DS:percent:GAUGE:"COLLECTD_HEARTBEAT":0:110",
88 };
89 static int charge_ds_num = 1;
90
91 static char *time_file_template = "apcups/timeleft.rrd";
92 static char *time_ds_def[] = 
93 {
94         "DS:timeleft:GAUGE:"COLLECTD_HEARTBEAT":0:100",
95 };
96 static int time_ds_num = 1;
97
98 static char *temp_file_template = "apcups/temperature.rrd";
99 static char *temp_ds_def[] = 
100 {
101         /* -273.15 is absolute zero */
102         "DS:value:GAUGE:"COLLECTD_HEARTBEAT":-274:U",
103 };
104 static int temp_ds_num = 1;
105
106 static char *freq_file_template = "apcups/frequency-%s.rrd";
107 static char *freq_ds_def[] = 
108 {
109         "DS:frequency:GAUGE:"COLLECTD_HEARTBEAT":0:U",
110 };
111 static int freq_ds_num = 1;
112
113 static char *config_keys[] =
114 {
115         "Host",
116         "Port",
117         NULL
118 };
119 static int config_keys_num = 2;
120
121 #endif /* if APCMAIN */
122
123 struct apc_detail_s
124 {
125         double linev;
126         double loadpct;
127         double bcharge;
128         double timeleft;
129         double outputv;
130         double itemp;
131         double battv;
132         double linefreq;
133 };
134
135 #define BIG_BUF 4096
136
137 /*
138  * Read nbytes from the network.
139  * It is possible that the total bytes require in several
140  * read requests
141  */
142 static int read_nbytes (int *fd, char *ptr, int nbytes)
143 {
144         int nleft;
145         int nread;
146
147         nleft = nbytes;
148         nread = -1;
149
150         assert (*fd >= 0);
151
152         while ((nleft > 0) && (nread != 0))
153         {
154                 nread = read (*fd, ptr, nleft);
155
156                 if ((nread < 0) && (errno == EINTR || errno == EAGAIN))
157                         continue;
158
159                 if (nread < 0)
160                 {
161                         *fd = -1;
162                         DBG ("Reading from socket failed failed: %s; *fd = -1;", strerror (errno));
163                         syslog (LOG_ERR, "apcups plugin: Reading from socket failed failed: %s", strerror (errno));
164                         return (-1);
165                 }
166
167                 if (nread == 0)
168                 {
169                         DBG ("Received EOF. Closing socket %i.", *fd);
170                         close (*fd);
171                         *fd = -1;
172                         return (nbytes - nleft);
173                 }
174
175                 nleft -= nread;
176                 ptr += nread;
177         }
178
179         return (nbytes - nleft);
180 }
181
182 /*
183  * Write nbytes to the network.
184  * It may require several writes.
185  */
186 static int write_nbytes (int *fd, void *buf, int buflen)
187 {
188         int nleft;
189         int nwritten;
190         char *ptr;
191
192         assert (buflen > 0);
193         assert (*fd >= 0);
194
195         ptr = (char *) buf;
196
197         nleft = buflen;
198         while (nleft > 0)
199         {
200                 nwritten = write (*fd, ptr, nleft);
201
202                 if ((nwritten < 0) && ((errno == EAGAIN) || (errno == EINTR)))
203                         continue;
204
205                 if (nwritten < 0)
206                 {
207                         *fd = -1;
208                         DBG ("Writing to socket failed: %s; *fd = -1;", strerror (errno));
209                         syslog (LOG_ERR, "apcups plugin: Writing to socket failed: %s", strerror (errno));
210                         return (-1);
211                 }
212
213                 nleft -= nwritten;
214                 ptr += nwritten;
215         }
216
217         /* If we get here, (nleft <= 0) is true */
218         return (buflen);
219 }
220
221 #if APCMAIN
222 /* Close the network connection */
223 static void net_close (int *fd)
224 {
225         short pktsiz = 0;
226
227         assert (*fd >= 0);
228
229         DBG ("Gracefully shutting down socket %i.", *fd);
230
231         /* send EOF sentinel */
232         write_nbytes (fd, &pktsiz, sizeof (short));
233
234         close (*fd);
235         *fd = -1;
236 }
237 #endif /* APCMAIN */
238
239 /*     
240  * Open a TCP connection to the UPS network server
241  * Returns -1 on error
242  * Returns socket file descriptor otherwise
243  */
244 static int net_open (char *host, char *service, int port)
245 {
246         int              sd;
247         int              status;
248         char             port_str[8];
249         struct addrinfo  ai_hints;
250         struct addrinfo *ai_return;
251         struct addrinfo *ai_list;
252
253         assert ((port > 0x00000000) && (port <= 0x0000FFFF));
254
255         /* Convert the port to a string */
256         snprintf (port_str, 8, "%i", port);
257         port_str[7] = '\0';
258
259         /* Resolve name */
260         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
261         ai_hints.ai_family   = AF_INET; /* XXX: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
262         ai_hints.ai_socktype = SOCK_STREAM;
263
264         status = getaddrinfo (host, port_str, &ai_hints, &ai_return);
265         if (status != 0)
266         {
267                 DBG ("getaddrinfo failed: %s", status == EAI_SYSTEM ? strerror (errno) : gai_strerror (status));
268                 return (-1);
269         }
270
271         /* Create socket */
272         sd = -1;
273         for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
274         {
275                 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
276                 if (sd >= 0)
277                         break;
278         }
279         /* `ai_list' still holds the current description of the socket.. */
280
281         if (sd < 0)
282         {
283                 DBG ("Unable to open a socket");
284                 freeaddrinfo (ai_return);
285                 return (-1);
286         }
287
288         status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
289
290         freeaddrinfo (ai_return);
291
292         if (status != 0) /* `connect(2)' failed */
293         {
294                 DBG ("connect failed: %s", strerror (errno));
295                 return (-1);
296         }
297
298         DBG ("Done opening a socket %i", sd);
299
300         return (sd);
301 } /* int net_open (char *host, char *service, int port) */
302
303 /* 
304  * Receive a message from the other end. Each message consists of
305  * two packets. The first is a header that contains the size
306  * of the data that follows in the second packet.
307  * Returns number of bytes read
308  * Returns 0 on end of file
309  * Returns -1 on hard end of file (i.e. network connection close)
310  * Returns -2 on error
311  */
312 static int net_recv (int *sockfd, char *buf, int buflen)
313 {
314         int   nbytes;
315         short pktsiz;
316
317         /* get data size -- in short */
318         if ((nbytes = read_nbytes (sockfd, (char *) &pktsiz, sizeof (short))) <= 0)
319                 return (-1);
320
321         if (nbytes != sizeof (short))
322                 return (-2);
323
324         pktsiz = ntohs (pktsiz);
325         if (pktsiz > buflen)
326         {
327                 DBG ("record length too large");
328                 return (-2);
329         }
330
331         if (pktsiz == 0)
332                 return (0);
333
334         /* now read the actual data */
335         if ((nbytes = read_nbytes (sockfd, buf, pktsiz)) <= 0)
336                 return (-2);
337
338         if (nbytes != pktsiz)
339                 return (-2);
340
341         return (nbytes);
342 } /* static int net_recv (int sockfd, char *buf, int buflen) */
343
344 /*
345  * Send a message over the network. The send consists of
346  * two network packets. The first is sends a short containing
347  * the length of the data packet which follows.
348  * Returns zero on success
349  * Returns non-zero on error
350  */
351 static int net_send (int *sockfd, char *buff, int len)
352 {
353         int rc;
354         short packet_size;
355
356         assert (len > 0);
357         assert (*sockfd >= 0);
358
359         /* send short containing size of data packet */
360         packet_size = htons ((short) len);
361
362         rc = write_nbytes (sockfd, &packet_size, sizeof (packet_size));
363         if (rc != sizeof (packet_size))
364                 return (-1);
365
366         /* send data packet */
367         rc = write_nbytes (sockfd, buff, len);
368         if (rc != len)
369                 return (-1);
370
371         return (0);
372 }
373
374 /* Get and print status from apcupsd NIS server */
375 static int apc_query_server (char *host, int port,
376                 struct apc_detail_s *apcups_detail)
377 {
378         int     n;
379         char    recvline[1024];
380         char   *tokptr;
381         char   *key;
382         double  value;
383
384         static int sockfd   = -1;
385         static unsigned int complain = 0;
386
387 #if APCMAIN
388 # define PRINT_VALUE(name, val) printf("  Found property: name = %s; value = %f;\n", name, val)
389 #else
390 # define PRINT_VALUE(name, val) /**/
391 #endif
392
393         if (sockfd < 0)
394         {
395                 if ((sockfd = net_open (host, NULL, port)) < 0)
396                 {
397                         /* Complain once every six hours. */
398                         int complain_step = 21600 / atoi (COLLECTD_STEP);
399
400                         if ((complain % complain_step) == 0)
401                                 syslog (LOG_ERR, "apcups plugin: Connecting to the apcupsd failed.");
402                         complain++;
403
404                         return (-1);
405                 }
406                 else if (complain > 1)
407                 {
408                         syslog (LOG_NOTICE, "apcups plugin: Connection re-established to the apcupsd.");
409                         complain = 0;
410                 }
411         }
412
413         if (net_send (&sockfd, "status", 6) < 0)
414         {
415                 syslog (LOG_ERR, "apcups plugin: Writing to the socket failed.");
416                 return (-1);
417         }
418
419         while ((n = net_recv (&sockfd, recvline, sizeof (recvline) - 1)) > 0)
420         {
421                 assert (n < sizeof (recvline));
422                 recvline[n] = '\0';
423 #if APCMAIN
424                 printf ("net_recv = `%s';\n", recvline);
425 #endif /* if APCMAIN */
426
427                 tokptr = strtok (recvline, " :\t");
428                 while (tokptr != NULL)
429                 {
430                         key = tokptr;
431                         if ((tokptr = strtok (NULL, " :\t")) == NULL)
432                                 continue;
433                         value = atof (tokptr);
434
435                         PRINT_VALUE (key, value);
436
437                         if (strcmp ("LINEV", key) == 0)
438                                 apcups_detail->linev = value;
439                         else if (strcmp ("BATTV", key) == 0) 
440                                 apcups_detail->battv = value;
441                         else if (strcmp ("ITEMP", key) == 0)
442                                 apcups_detail->itemp = value;
443                         else if (strcmp ("LOADPCT", key) == 0)
444                                 apcups_detail->loadpct = value;
445                         else if (strcmp ("BCHARGE", key) == 0)
446                                 apcups_detail->bcharge = value;
447                         else if (strcmp ("OUTPUTV", key) == 0)
448                                 apcups_detail->outputv = value;
449                         else if (strcmp ("LINEFREQ", key) == 0)
450                                 apcups_detail->linefreq = value;
451                         else if (strcmp ("TIMELEFT", key) == 0)
452                                 apcups_detail->timeleft = value;
453
454                         tokptr = strtok (NULL, ":");
455                 } /* while (tokptr != NULL) */
456         }
457         
458         if (n < 0)
459         {
460                 syslog (LOG_WARNING, "apcups plugin: Error reading from socket");
461                 return (-1);
462         }
463 #if APCMAIN
464         else
465         {
466                 /* close the opened socket */
467                 net_close (&sockfd);
468         }
469 #endif /* APCMAIN */
470
471         return (0);
472 }
473
474 #if APCMAIN
475 /*
476  * This is used for testing apcups in a standalone mode.
477  * Usefull for debugging.
478  */
479 int main (int argc, char **argv)
480 {
481         /* we are not really going to use this */
482         struct apc_detail_s apcups_detail;
483
484         openlog ("apcups", LOG_PID | LOG_NDELAY | LOG_LOCAL1, LOG_USER);
485
486         if (global_host == NULL || strcmp (global_host, "0.0.0.0") == 0)
487                 global_host = "localhost";
488
489         if(apc_query_server (global_host, global_port, &apcups_detail) < 0)
490         {
491                 printf("apcups: Failed...\n");
492                 return(-1);
493         }
494
495         return 0;
496 }
497 #else
498 static int apcups_config (char *key, char *value)
499 {
500         if (strcasecmp (key, "host") == 0)
501         {
502                 if (global_host != NULL)
503                 {
504                         free (global_host);
505                         global_host = NULL;
506                 }
507                 if ((global_host = strdup (value)) == NULL)
508                         return (1);
509         }
510         else if (strcasecmp (key, "Port") == 0)
511         {
512                 int port_tmp = atoi (value);
513                 if (port_tmp < 1 || port_tmp > 65535)
514                 {
515                         syslog (LOG_WARNING, "apcups plugin: Invalid port: %i", port_tmp);
516                         return (1);
517                 }
518                 global_port = port_tmp;
519         }
520         else
521         {
522                 return (-1);
523         }
524         return (0);
525 }
526
527 static void apcups_init (void)
528 {
529         return;
530 }
531
532 static void apc_write_voltage (char *host, char *inst, char *val)
533 {
534         char file[512];
535         int  status;
536
537         status = snprintf (file, 512, bvolt_file_template, inst);
538         if ((status < 1) || (status >= 512))
539                 return;
540
541         rrd_update_file (host, file, val, bvolt_ds_def, bvolt_ds_num);
542 }
543
544 static void apc_write_charge (char *host, char *inst, char *val)
545 {
546         rrd_update_file (host, charge_file_template, val, charge_ds_def, charge_ds_num);
547 }
548
549 static void apc_write_percent (char *host, char *inst, char *val)
550 {
551         rrd_update_file (host, load_file_template, val, load_ds_def, load_ds_num);
552 }
553
554 static void apc_write_timeleft (char *host, char *inst, char *val)
555 {
556         rrd_update_file (host, time_file_template, val, time_ds_def, time_ds_num);
557 }
558
559 static void apc_write_temperature (char *host, char *inst, char *val)
560 {
561         rrd_update_file (host, temp_file_template, val, temp_ds_def, temp_ds_num);
562 }
563
564 static void apc_write_frequency (char *host, char *inst, char *val)
565 {
566         char file[512];
567         int  status;
568
569         status = snprintf (file, 512, freq_file_template, inst);
570         if ((status < 1) || (status >= 512))
571                 return;
572
573         rrd_update_file (host, file, val, freq_ds_def, freq_ds_num);
574 }
575
576 static void apc_submit_generic (char *type, char *inst,
577                 double value)
578 {
579         char buf[512];
580         int  status;
581
582         status = snprintf (buf, 512, "%u:%f",
583                         (unsigned int) curtime, value);
584         if ((status < 1) || (status >= 512))
585                 return;
586
587         DBG ("plugin_submit (%s, %s, %s);", type, inst, buf);
588         plugin_submit (type, inst, buf);
589 }
590
591 static void apc_submit (struct apc_detail_s *apcups_detail)
592 {
593         apc_submit_generic ("apcups_voltage",    "input",   apcups_detail->linev);
594         apc_submit_generic ("apcups_voltage",    "output",  apcups_detail->outputv);
595         apc_submit_generic ("apcups_voltage",    "battery", apcups_detail->battv);
596         apc_submit_generic ("apcups_charge",     "-",       apcups_detail->bcharge);
597         apc_submit_generic ("apcups_charge_pct", "-",       apcups_detail->loadpct);
598         apc_submit_generic ("apcups_timeleft",   "-",       apcups_detail->timeleft);
599         apc_submit_generic ("apcups_temp",       "-",       apcups_detail->itemp);
600         apc_submit_generic ("apcups_frequency",  "input",   apcups_detail->linefreq);
601 }
602
603 static void apcups_read (void)
604 {
605         struct apc_detail_s apcups_detail;
606         int status;
607
608         apcups_detail.linev    =   -1.0;
609         apcups_detail.outputv  =   -1.0;
610         apcups_detail.battv    =   -1.0;
611         apcups_detail.loadpct  =   -1.0;
612         apcups_detail.bcharge  =   -1.0;
613         apcups_detail.timeleft =   -1.0;
614         apcups_detail.itemp    = -300.0;
615         apcups_detail.linefreq =   -1.0;
616   
617         status = apc_query_server (global_host == NULL
618                         ? APCUPS_DEFAULT_HOST
619                         : global_host,
620                         global_port, &apcups_detail);
621  
622         /*
623          * if we did not connect then do not bother submitting
624          * zeros. We want rrd files to have NAN.
625          */
626         if (status != 0)
627         {
628                 DBG ("apc_query_server (%s, %i) = %i",
629                                 global_host == NULL
630                                 ? APCUPS_DEFAULT_HOST
631                                 : global_host,
632                                 global_port, status);
633                 return;
634         }
635
636         apc_submit (&apcups_detail);
637 } /* apcups_read */
638
639 void module_register (void)
640 {
641         plugin_register (MODULE_NAME, apcups_init, apcups_read, NULL);
642         plugin_register ("apcups_voltage",    NULL, NULL, apc_write_voltage);
643         plugin_register ("apcups_charge",     NULL, NULL, apc_write_charge);
644         plugin_register ("apcups_charge_pct", NULL, NULL, apc_write_percent);
645         plugin_register ("apcups_timeleft",   NULL, NULL, apc_write_timeleft);
646         plugin_register ("apcups_temp",       NULL, NULL, apc_write_temperature);
647         plugin_register ("apcups_frequency",  NULL, NULL, apc_write_frequency);
648         cf_register (MODULE_NAME, apcups_config, config_keys, config_keys_num);
649 }
650
651 #endif /* if APCMAIN */
652 #undef MODULE_NAME