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