apcups.c:
[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 #include "collectd.h"
26 #include "common.h" /* rrd_update_file */
27 #include "plugin.h" /* plugin_register, plugin_submit */
28 #include "configfile.h" /* cf_register */
29
30 /* FIXME: Check defines before including anything! */
31 #include <stdarg.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <strings.h>
35 #include <signal.h>
36 #include <ctype.h>
37 #include <syslog.h>
38 #include <limits.h>
39 #include <pwd.h>
40 #include <time.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <setjmp.h>
44 #include <termios.h>
45 #include <netdb.h>
46 #include <sys/ioctl.h>
47 #include <sys/ipc.h>
48 #include <sys/sem.h>
49 #include <sys/shm.h>
50 #include <sys/socket.h>
51 #include <sys/types.h>
52 #include <sys/time.h>
53 #include <time.h>
54 #include <sys/wait.h>
55 #include <netinet/in.h>
56 #include <arpa/inet.h>
57
58 #define NISPORT 3551
59 #define _(String) (String)
60 #define N_(String) (String)
61 #define MAXSTRING               256
62 #define Error_abort0(fmd) generic_error_out(__FILE__, __LINE__, fmd)
63 #define MODULE_NAME "apcups"
64
65
66 /* Prototypes */
67 static void generic_error_out(const char *, int , const char *, ...);
68
69 /* Default values for contacting daemon */
70 static char *host = "localhost";
71 static int port = NISPORT;
72
73 static struct sockaddr_in tcp_serv_addr;  /* socket information */
74 static int net_errno = 0;                 /* error number -- not yet implemented */
75 static char *net_errmsg = NULL;           /* pointer to error message */
76 static char net_errbuf[256];              /* error message buffer for messages */
77
78 /* 
79  * The following are only if not compiled to test the module with its own main.
80 */
81 /* FIXME: Rename DSes to be more generic and follow established conventions. */
82 #ifndef APCMAIN
83 static char *volt_file_template = "apcups_volt-%s.rrd";
84 static char *volt_ds_def[] = 
85 {
86         "DS:linev:GAUGE:"COLLECTD_HEARTBEAT":0:250",
87         "DS:outputv:GAUGE:"COLLECTD_HEARTBEAT":0:250",
88         NULL
89 };
90 static int volt_ds_num = 2;
91
92 static char *bvolt_file_template = "apcups_bvolt-%s.rrd";
93 static char *bvolt_ds_def[] = 
94 {
95         "DS:battv:GAUGE:"COLLECTD_HEARTBEAT":0:100",
96 };
97 static int bvolt_ds_num = 1;
98
99 static char *load_file_template = "apcups_load-%s.rrd";
100 static char *load_ds_def[] = 
101 {
102         "DS:loadpct:GAUGE:"COLLECTD_HEARTBEAT":0:120",
103 };
104 static int load_ds_num = 1;
105
106 static char *charge_file_template = "apcups_charge-%s.rrd";
107 static char *charge_ds_def[] = 
108 {
109         "DS:bcharge:GAUGE:"COLLECTD_HEARTBEAT":0:100",
110 };
111 static int charge_ds_num = 1;
112
113 static char *time_file_template = "apcups_time-%s.rrd";
114 static char *time_ds_def[] = 
115 {
116         "DS:timeleft:GAUGE:"COLLECTD_HEARTBEAT":0:100",
117 };
118 static int time_ds_num = 1;
119
120 static char *temp_file_template = "apcups_temp-%s.rrd";
121 static char *temp_ds_def[] = 
122 {
123         "DS:itemp:GAUGE:"COLLECTD_HEARTBEAT":0:100",
124 };
125 static int temp_ds_num = 1;
126
127 static char *freq_file_template = "apcups_freq-%s.rrd";
128 static char *freq_ds_def[] = 
129 {
130         "DS:linefreq:GAUGE:"COLLECTD_HEARTBEAT":0:65",
131 };
132 static int freq_ds_num = 1;
133
134 static char *config_keys[] =
135 {
136         "Host",
137         "Port",
138         NULL
139 };
140 static int config_keys_num = 2;
141
142 #endif /* ifndef APCMAIN */
143
144 struct apc_detail_s
145 {
146         float linev;
147         float loadpct;
148         float bcharge;
149         float timeleft;
150         float outputv;
151         float itemp;
152         float battv;
153         float linefreq;
154 };
155
156 #define BIG_BUF 4096
157
158 /*
159  * Subroutine normally called by macro error_abort() to print
160  * FATAL ERROR message and supplied error message
161  */
162 static void generic_error_out(const char *file, int line, const char *fmt, ...)
163 {
164         char buf[256];
165         va_list arg_ptr;
166         int i;
167
168         snprintf(buf, sizeof(buf), _("FATAL ERROR in %s at line %d\n"), file, line);
169         i = strlen(buf);
170         va_start(arg_ptr, fmt);
171         vsnprintf((char *)&buf[i], sizeof(buf) - i, (char *)fmt, arg_ptr);
172         va_end(arg_ptr);
173         fprintf(stdout, "%s", buf);
174
175         exit(1);
176 }
177
178 /*
179  * Read nbytes from the network.
180  * It is possible that the total bytes require in several
181  * read requests
182  */
183 static int read_nbytes(int fd, char *ptr, int nbytes)
184 {
185         int nleft, nread;
186
187         nleft = nbytes;
188
189         while (nleft > 0) {
190                 do {
191                         nread = read(fd, ptr, nleft);
192                 } while (nread == -1 && (errno == EINTR || errno == EAGAIN));
193
194                 if (nread <= 0) {
195                         net_errno = errno;
196                         return (nread);           /* error, or EOF */
197                 }
198
199                 nleft -= nread;
200                 ptr += nread;
201         }
202
203         return (nbytes - nleft);        /* return >= 0 */
204 }
205
206 /*
207  * Write nbytes to the network.
208  * It may require several writes.
209  */
210 static int write_nbytes(int fd, char *ptr, int nbytes)
211 {
212         int nleft, nwritten;
213
214         nleft = nbytes;
215         while (nleft > 0) {
216                 nwritten = write(fd, ptr, nleft);
217
218                 if (nwritten <= 0) {
219                         net_errno = errno;
220                         return (nwritten);        /* error */
221                 }
222
223                 nleft -= nwritten;
224                 ptr += nwritten;
225         }
226
227         return (nbytes - nleft);
228 }
229
230 /* Close the network connection */
231 static void net_close (int sockfd)
232 {
233         short pktsiz = 0;
234
235         /* send EOF sentinel */
236         write_nbytes(sockfd, (char *) &pktsiz, sizeof(short));
237         close (sockfd);
238 }
239
240
241 /*     
242  * Open a TCP connection to the UPS network server
243  * Returns -1 on error
244  * Returns socket file descriptor otherwise
245  */
246 static int net_open(char *host, char *service, int port)
247 {
248         int sockfd;
249         struct hostent *hp;
250         unsigned int inaddr; /* Careful here to use unsigned int for */
251                              /* compatibility with Alpha */
252
253         /* 
254          * Fill in the structure serv_addr with the address of the server that
255          * we want to connect with.
256          */
257         memset((char *)&tcp_serv_addr, 0, sizeof(tcp_serv_addr));
258         tcp_serv_addr.sin_family = AF_INET;
259         tcp_serv_addr.sin_port = htons(port);
260
261         if ((inaddr = inet_addr(host)) != INADDR_NONE) {
262                 tcp_serv_addr.sin_addr.s_addr = inaddr;
263         } else {
264                 if ((hp = gethostbyname(host)) == NULL) {
265                         net_errmsg = "tcp_open: hostname error\n";
266                         return -1;
267                 }
268
269                 if (hp->h_length != sizeof(inaddr) || hp->h_addrtype != AF_INET) {
270                         net_errmsg = "tcp_open: funny gethostbyname value\n";
271                         return -1;
272                 }
273
274                 tcp_serv_addr.sin_addr.s_addr = *(unsigned int *)hp->h_addr;
275         }
276
277         /* Open a TCP socket */
278         if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
279                 net_errmsg = "tcp_open: cannot open stream socket\n";
280                 return -1;
281         }
282
283         /* connect to server */
284 #if defined HAVE_OPENBSD_OS || defined HAVE_FREEBSD_OS
285         /* 
286          * Work around a bug in OpenBSD & FreeBSD userspace pthreads
287          * implementations. Rationale is the same as described above.
288          */
289         fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL));
290 #endif
291
292         if (connect(sockfd, (struct sockaddr *)&tcp_serv_addr, sizeof(tcp_serv_addr)) < 0) {
293                 snprintf(net_errbuf, sizeof(net_errbuf),
294                                 _("tcp_open: cannot connect to server %s on port %d.\n"
295                                         "ERR=%s\n"), host, port, strerror(errno));
296                 net_errmsg = net_errbuf;
297                 close(sockfd);
298                 return -1;
299         }
300
301         return sockfd;
302 } /* int net_open(char *host, char *service, int port) */
303
304 /* 
305  * Receive a message from the other end. Each message consists of
306  * two packets. The first is a header that contains the size
307  * of the data that follows in the second packet.
308  * Returns number of bytes read
309  * Returns 0 on end of file
310  * Returns -1 on hard end of file (i.e. network connection close)
311  * Returns -2 on error
312  */
313 static int net_recv(int sockfd, char *buff, int maxlen)
314 {
315         int nbytes;
316         short pktsiz;
317
318         /* get data size -- in short */
319         if ((nbytes = read_nbytes(sockfd, (char *)&pktsiz, sizeof(short))) <= 0) {
320                 /* probably pipe broken because client died */
321                 return -1;                   /* assume hard EOF received */
322         }
323         if (nbytes != sizeof(short))
324                 return -2;
325
326         pktsiz = ntohs(pktsiz);         /* decode no. of bytes that follow */
327         if (pktsiz > maxlen) {
328                 net_errmsg = "net_recv: record length too large\n";
329                 return -2;
330         }
331         if (pktsiz == 0)
332                 return 0;                    /* soft EOF */
333
334         /* now read the actual data */
335         if ((nbytes = read_nbytes(sockfd, buff, pktsiz)) <= 0) {
336                 net_errmsg = "net_recv: read_nbytes error\n";
337                 return -2;
338         }
339         if (nbytes != pktsiz) {
340                 net_errmsg = "net_recv: error in read_nbytes\n";
341                 return -2;
342         }
343
344         return (nbytes);                /* return actual length of message */
345 }
346
347 /*
348  * Send a message over the network. The send consists of
349  * two network packets. The first is sends a short containing
350  * the length of the data packet which follows.
351  * Returns number of bytes sent
352  * Returns -1 on error
353  */
354 static int net_send(int sockfd, char *buff, int len)
355 {
356         int rc;
357         short pktsiz;
358
359         /* send short containing size of data packet */
360         pktsiz = htons((short)len);
361         rc = write_nbytes(sockfd, (char *)&pktsiz, sizeof(short));
362         if (rc != sizeof(short)) {
363                 net_errmsg = "net_send: write_nbytes error of length prefix\n";
364                 return -1;
365         }
366
367         /* send data packet */
368         rc = write_nbytes(sockfd, buff, len);
369         if (rc != len) {
370                 net_errmsg = "net_send: write_nbytes error\n";
371                 return -1;
372         }
373
374         return rc;
375 }
376
377
378 /* Get and print status from apcupsd NIS server */
379 static int do_pthreads_status(char *host, int port, struct apc_detail_s *apcups_detail)
380 {
381         int     sockfd;
382         int     n;
383         char    recvline[MAXSTRING + 1];
384         char   *tokptr;
385         char   *key;
386         double  value;
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         /* TODO: Keep the socket open, if possible */
394         if ((sockfd = net_open (host, NULL, port)) < 0)
395         {
396                 syslog (LOG_ERR, "apcups plugin: Connecting to the apcupsd failed.");
397                 return (-1);
398         }
399
400         net_send (sockfd, "status", 6);
401
402         while ((n = net_recv (sockfd, recvline, sizeof (recvline))) > 0)
403         {
404                 recvline[n] = '\0';
405 #if APCMAIN
406                 printf ("net_recv = `%s';\n", recvline);
407 #endif /* if APCMAIN */
408
409                 tokptr = strtok (recvline, ":");
410                 while (tokptr != NULL)
411                 {
412                         key = tokptr;
413                         if ((tokptr = strtok (NULL, " \t")) == NULL)
414                                 continue;
415                         value = atof (tokptr);
416                         PRINT_VALUE (key, value);
417
418                         if (strcmp ("LINEV", key) == 0)
419                                 apcups_detail->linev = value;
420                         else if (strcmp ("BATTV", tokptr) == 0)
421                                 apcups_detail->battv = value;
422                         else if (strcmp ("ITEMP", tokptr) == 0)
423                                 apcups_detail->itemp = value;
424                         else if (strcmp ("LOADPCT", tokptr) == 0)
425                                 apcups_detail->loadpct = value;
426                         else if (strcmp ("BCHARGE", tokptr) == 0)
427                                 apcups_detail->bcharge = value;
428                         else if (strcmp ("OUTPUTV", tokptr) == 0)
429                                 apcups_detail->outputv = value;
430                         else if (strcmp ("LINEFREQ", tokptr) == 0)
431                                 apcups_detail->linefreq = value;
432                         else if (strcmp ("TIMELEFT", tokptr) == 0)
433                                 apcups_detail->timeleft = value;
434                         else
435                         {
436                                 syslog (LOG_WARNING, "apcups plugin: Received unknown property from apcupsd: `%s' = %f",
437                                                 key, value);
438                         }
439
440                         tokptr = strtok (NULL, ":");
441                 } /* while (tokptr != NULL) */
442         }
443
444         if (n < 0)
445                 Error_abort0(net_errmsg);
446
447         net_close(sockfd);
448
449         return (0);
450 }
451
452 #ifdef APCMAIN
453 int main(int argc, char **argv)
454 {
455         /* we are not really going to use this */
456         struct apc_detail_s apcups_detail;
457
458         if (!*host || strcmp(host, "0.0.0.0") == 0)
459                 host = "localhost";
460
461         do_pthreads_status(host, port, &apcups_detail);
462
463         return 0;
464 }
465 #else
466 static void apcups_init (void)
467 {
468         return;
469 }
470
471 static int apcups_config (char *key, char *value)
472 {
473   static char lhost[126];
474   
475   if (strcasecmp (key, "host") == 0)
476     {
477       lhost[0] = '\0';
478       strcpy(lhost,key);
479       host = lhost;
480     }
481   else if (strcasecmp (key, "Port") == 0)
482     {
483       int port_tmp = atoi (value);
484       if(port_tmp < 1 || port_tmp > 65535) {
485         syslog (LOG_WARNING, "apcups: `port' failed: %s",
486                 value);
487         return (1);
488       } else {
489         port = port_tmp;
490       }
491     }
492   else
493     {
494       return (-1);
495     }
496   return(0);
497 }
498
499 #define BUFSIZE 256
500 static void apcups_submit (char *host,
501                            struct apc_detail_s *apcups_detail)
502 {
503         char buf[BUFSIZE];
504
505         if (snprintf (buf, BUFSIZE, "%u:%f:%f",
506                       (unsigned int) curtime,
507                       apcups_detail->linev,
508                       apcups_detail->outputv) >= BUFSIZE)
509           return;
510         
511         plugin_submit (MODULE_NAME, host, buf);
512 }
513
514 static void apc_bvolt_submit (char *host,
515                            struct apc_detail_s *apcups_detail)
516 {
517         char buf[BUFSIZE];
518
519         if (snprintf (buf, BUFSIZE, "%u:%f",
520                       (unsigned int) curtime,
521                       apcups_detail->battv) >= BUFSIZE)
522           return;
523         
524         plugin_submit ("apcups_bvolt", host, buf);
525 }
526
527 static void apc_load_submit (char *host,
528                            struct apc_detail_s *apcups_detail)
529 {
530         char buf[BUFSIZE];
531
532         if (snprintf (buf, BUFSIZE, "%u:%f",
533                       (unsigned int) curtime,
534                       apcups_detail->loadpct) >= BUFSIZE)
535           return;
536         
537         plugin_submit ("apcups_load", host, buf);
538 }
539
540 static void apc_charge_submit (char *host,
541                            struct apc_detail_s *apcups_detail)
542 {
543         char buf[BUFSIZE];
544
545         if (snprintf (buf, BUFSIZE, "%u:%f",
546                       (unsigned int) curtime,
547                       apcups_detail->bcharge) >= BUFSIZE)
548           return;
549         
550         plugin_submit ("apcups_charge", host, buf);
551 }
552
553 static void apc_temp_submit (char *host,
554                            struct apc_detail_s *apcups_detail)
555 {
556         char buf[BUFSIZE];
557
558         if (snprintf (buf, BUFSIZE, "%u:%f",
559                       (unsigned int) curtime,
560                       apcups_detail->itemp) >= BUFSIZE)
561           return;
562         
563         plugin_submit ("apcups_temp", host, buf);
564 }
565
566 static void apc_time_submit (char *host,
567                            struct apc_detail_s *apcups_detail)
568 {
569         char buf[BUFSIZE];
570
571         if (snprintf (buf, BUFSIZE, "%u:%f",
572                       (unsigned int) curtime,
573                       apcups_detail->timeleft) >= BUFSIZE)
574           return;
575         
576         plugin_submit ("apcups_time", host, buf);
577 }
578
579 static void apc_freq_submit (char *host,
580                            struct apc_detail_s *apcups_detail)
581 {
582         char buf[BUFSIZE];
583
584         if (snprintf (buf, BUFSIZE, "%u:%f",
585                       (unsigned int) curtime,
586                       apcups_detail->linefreq) >= BUFSIZE)
587           return;
588         
589         plugin_submit ("apcups_freq", host, buf);
590 }
591 #undef BUFSIZE
592
593 static void apcups_read (void)
594 {
595   struct apc_detail_s apcups_detail;
596         
597   apcups_detail.linev = 0.0;
598   apcups_detail.loadpct = 0.0;
599   apcups_detail.bcharge = 0.0;
600   apcups_detail.timeleft = 0.0;
601   apcups_detail.outputv = 0.0;
602   apcups_detail.itemp = 0.0;
603   apcups_detail.battv = 0.0;
604   apcups_detail.linefreq = 0.0;
605
606   
607   if (!*host || strcmp(host, "0.0.0.0") == 0)
608     host = "localhost";
609   
610   do_pthreads_status(host, port, &apcups_detail);
611  
612   apcups_submit (host, &apcups_detail);
613   apc_bvolt_submit (host, &apcups_detail);
614   apc_load_submit (host, &apcups_detail);
615   apc_charge_submit (host, &apcups_detail);
616   apc_temp_submit (host, &apcups_detail);
617   apc_time_submit (host, &apcups_detail);
618   apc_freq_submit (host, &apcups_detail);
619 }
620
621
622 static void apcups_write (char *host, char *inst, char *val)
623 {
624   char file[512];
625   int status;
626   
627   status = snprintf (file, 512, volt_file_template, inst);
628   if (status < 1)
629     return;
630   else if (status >= 512)
631     return;
632   
633   rrd_update_file (host, file, val, volt_ds_def, volt_ds_num);
634 }
635
636 static void apc_bvolt_write (char *host, char *inst, char *val)
637 {
638   char file[512];
639   int status;
640   
641   status = snprintf (file, 512, bvolt_file_template, inst);
642   if (status < 1)
643     return;
644   else if (status >= 512)
645     return;
646   
647   rrd_update_file (host, file, val, bvolt_ds_def, bvolt_ds_num);
648 }
649
650 static void apc_load_write (char *host, char *inst, char *val)
651 {
652   char file[512];
653   int status;
654   
655   status = snprintf (file, 512, load_file_template, inst);
656   if (status < 1)
657     return;
658   else if (status >= 512)
659     return;
660   
661   rrd_update_file (host, file, val, load_ds_def, load_ds_num);
662 }
663
664 static void apc_charge_write (char *host, char *inst, char *val)
665 {
666   char file[512];
667   int status;
668   
669   status = snprintf (file, 512, charge_file_template, inst);
670   if (status < 1)
671     return;
672   else if (status >= 512)
673     return;
674   
675   rrd_update_file (host, file, val, charge_ds_def, charge_ds_num);
676 }
677
678 static void apc_temp_write (char *host, char *inst, char *val)
679 {
680   char file[512];
681   int status;
682   
683   status = snprintf (file, 512, temp_file_template, inst);
684   if (status < 1)
685     return;
686   else if (status >= 512)
687     return;
688   
689   rrd_update_file (host, file, val, temp_ds_def, temp_ds_num);
690 }
691
692 static void apc_time_write (char *host, char *inst, char *val)
693 {
694   char file[512];
695   int status;
696   
697   status = snprintf (file, 512, time_file_template, inst);
698   if (status < 1)
699     return;
700   else if (status >= 512)
701     return;
702   
703   rrd_update_file (host, file, val, time_ds_def, time_ds_num);
704 }
705
706 static void apc_freq_write (char *host, char *inst, char *val)
707 {
708   char file[512];
709   int status;
710   
711   status = snprintf (file, 512, freq_file_template, inst);
712   if (status < 1)
713     return;
714   else if (status >= 512)
715     return;
716   
717   rrd_update_file (host, file, val, freq_ds_def, freq_ds_num);
718 }
719
720 void module_register (void)
721 {
722         plugin_register (MODULE_NAME, apcups_init, apcups_read, apcups_write);
723         plugin_register ("apcups_bvolt", NULL, NULL, apc_bvolt_write);
724         plugin_register ("apcups_load", NULL, NULL, apc_load_write);
725         plugin_register ("apcups_charge", NULL, NULL, apc_charge_write);
726         plugin_register ("apcups_temp", NULL, NULL, apc_temp_write);
727         plugin_register ("apcups_time", NULL, NULL, apc_time_write);
728         plugin_register ("apcups_freq", NULL, NULL, apc_freq_write);
729         cf_register (MODULE_NAME, apcups_config, config_keys, config_keys_num);
730 }
731
732 #endif /* ifdef APCMAIN */
733 #undef MODULE_NAME