Code

Changed the network code to use `getaddrinfo' rather than the old style name resolution.
[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  **/
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 #include "utils_debug.h"
31 #if HAVE_SYS_TYPES_H
32 # include <sys/types.h>
33 #endif
34 #if HAVE_SYS_SOCKET_H
35 # include <sys/socket.h>
36 #endif
37 #if HAVE_NETDB_H
38 # include <netdb.h>
39 #endif
40 #if HAVE_NETINET_IN_H
41 # include <netinet/in.h>
42 #endif
43 #if HAVE_ARPA_INET_H
44 # include <arpa/inet.h> /* inet_addr */
45 #endif
47 #if 0
48 #include <pwd.h>
49 #include <setjmp.h> /* FIXME: Is this really neccessary? */
50 #include <termios.h> /* FIXME: Is this really neccessary? */
51 #include <sys/ioctl.h> /* FIXME: Is this really neccessary? */
52 #include <sys/ipc.h> /* FIXME: Is this really neccessary? */
53 #include <sys/sem.h> /* FIXME: Is this really neccessary? */
54 #include <sys/shm.h> /* FIXME: Is this really neccessary? */
55 #endif
57 #define NISPORT 3551
58 #define _(String) (String)
59 #define N_(String) (String)
60 #define MAXSTRING               256
61 #define MODULE_NAME "apcups"
63 /* Default values for contacting daemon */
64 static char *host = "localhost";
65 static int   port = NISPORT;
67 /* 
68  * The following are only if not compiled to test the module with its own main.
69 */
70 /* FIXME: Rename DSes to be more generic and follow established conventions. */
71 #ifndef APCMAIN
72 static char *volt_file_template = "apcups_volt-%s.rrd";
73 static char *volt_ds_def[] = 
74 {
75         "DS:linev:GAUGE:"COLLECTD_HEARTBEAT":0:250",
76         "DS:outputv:GAUGE:"COLLECTD_HEARTBEAT":0:250",
77         NULL
78 };
79 static int volt_ds_num = 2;
81 static char *bvolt_file_template = "apcups_bvolt-%s.rrd";
82 static char *bvolt_ds_def[] = 
83 {
84         "DS:battv:GAUGE:"COLLECTD_HEARTBEAT":0:100",
85 };
86 static int bvolt_ds_num = 1;
88 static char *load_file_template = "apcups_load-%s.rrd";
89 static char *load_ds_def[] = 
90 {
91         "DS:loadpct:GAUGE:"COLLECTD_HEARTBEAT":0:120",
92 };
93 static int load_ds_num = 1;
95 static char *charge_file_template = "apcups_charge-%s.rrd";
96 static char *charge_ds_def[] = 
97 {
98         "DS:bcharge:GAUGE:"COLLECTD_HEARTBEAT":0:100",
99 };
100 static int charge_ds_num = 1;
102 static char *time_file_template = "apcups_time-%s.rrd";
103 static char *time_ds_def[] = 
105         "DS:timeleft:GAUGE:"COLLECTD_HEARTBEAT":0:100",
106 };
107 static int time_ds_num = 1;
109 static char *temp_file_template = "apcups_temp-%s.rrd";
110 static char *temp_ds_def[] = 
112         "DS:itemp:GAUGE:"COLLECTD_HEARTBEAT":0:100",
113 };
114 static int temp_ds_num = 1;
116 static char *freq_file_template = "apcups_freq-%s.rrd";
117 static char *freq_ds_def[] = 
119         "DS:linefreq:GAUGE:"COLLECTD_HEARTBEAT":0:65",
120 };
121 static int freq_ds_num = 1;
123 static char *config_keys[] =
125         "Host",
126         "Port",
127         NULL
128 };
129 static int config_keys_num = 2;
131 #endif /* ifndef APCMAIN */
133 struct apc_detail_s
135         float linev;
136         float loadpct;
137         float bcharge;
138         float timeleft;
139         float outputv;
140         float itemp;
141         float battv;
142         float linefreq;
143 };
145 #define BIG_BUF 4096
147 /*
148  * Read nbytes from the network.
149  * It is possible that the total bytes require in several
150  * read requests
151  */
152 static int read_nbytes(int fd, char *ptr, int nbytes)
154         int nleft, nread;
156         nleft = nbytes;
158         while (nleft > 0) {
159                 do {
160                         nread = read(fd, ptr, nleft);
161                 } while (nread == -1 && (errno == EINTR || errno == EAGAIN));
163                 if (nread <= 0) {
164                         return (nread);           /* error, or EOF */
165                 }
167                 nleft -= nread;
168                 ptr += nread;
169         }
171         return (nbytes - nleft);        /* return >= 0 */
174 /*
175  * Write nbytes to the network.
176  * It may require several writes.
177  */
178 static int write_nbytes(int fd, void *buf, int buflen)
180         int nleft;
181         int nwritten;
182         char *ptr;
184         ptr = (char *) buf;
186         nleft = buflen;
187         while (nleft > 0)
188         {
189                 nwritten = write(fd, ptr, nleft);
191                 if (nwritten <= 0)
192                 {
193                         syslog (LOG_ERR, "Writing to socket failed: %s", strerror (errno));
194                         return (nwritten);
195                 }
197                 nleft -= nwritten;
198                 ptr += nwritten;
199         }
201         /* If we get here, (nleft <= 0) is true */
202         return (buflen);
205 /* Close the network connection */
206 static void net_close (int sockfd)
208         short pktsiz = 0;
210         /* send EOF sentinel */
211         write_nbytes (sockfd, &pktsiz, sizeof (short));
212         close (sockfd);
216 /*     
217  * Open a TCP connection to the UPS network server
218  * Returns -1 on error
219  * Returns socket file descriptor otherwise
220  */
221 static int net_open (char *host, char *service, int port)
223         int              sd;
224         int              status;
225         char             port_str[8];
226         struct addrinfo  ai_hints;
227         struct addrinfo *ai_return;
228         struct addrinfo *ai_list;
230         assert ((port > 0x00000000) && (port <= 0x0000FFFF));
232         /* Convert the port to a string */
233         snprintf (port_str, 8, "%i", port);
234         port_str[7] = '\0';
236         /* Resolve name */
237         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
238         ai_hints.ai_family   = AF_INET; /* XXX: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
239         ai_hints.ai_socktype = SOCK_STREAM;
241         status = getaddrinfo (host, port_str, &ai_hints, &ai_return);
242         if (status != 0)
243         {
244                 DBG ("getaddrinfo failed: %s", status == EAI_SYSTEM ? strerror (errno) : gai_strerror (status));
245                 return (-1);
246         }
248         /* Create socket */
249         sd = -1;
250         for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
251         {
252                 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
253                 if (sd >= 0)
254                         break;
255         }
256         /* `ai_list' still holds the current description of the socket.. */
258         if (sd < 0)
259         {
260                 DBG ("Unable to open a socket");
261                 freeaddrinfo (ai_return);
262                 return (-1);
263         }
265         status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
267         freeaddrinfo (ai_return);
269         if (status != 0) /* `connect(2)' failed */
270         {
271                 DBG ("connect failed: %s", strerror (errno));
272                 return (-1);
273         }
275         return (sd);
276 } /* int net_open(char *host, char *service, int port) */
278 /* 
279  * Receive a message from the other end. Each message consists of
280  * two packets. The first is a header that contains the size
281  * of the data that follows in the second packet.
282  * Returns number of bytes read
283  * Returns 0 on end of file
284  * Returns -1 on hard end of file (i.e. network connection close)
285  * Returns -2 on error
286  */
287 static int net_recv (int sockfd, char *buf, int buflen)
289         int   nbytes;
290         short pktsiz;
292         /* get data size -- in short */
293         if ((nbytes = read_nbytes (sockfd, (char *) &pktsiz, sizeof (short))) <= 0)
294                 return (-1);
296         if (nbytes != sizeof (short))
297                 return (-2);
299         pktsiz = ntohs(pktsiz);
300         if (pktsiz > buflen)
301         {
302                 DBG ("record length too large");
303                 return (-2);
304         }
306         if (pktsiz == 0)
307                 return (0);
309         /* now read the actual data */
310         if ((nbytes = read_nbytes (sockfd, buf, pktsiz)) <= 0)
311                 return (-2);
313         if (nbytes != pktsiz)
314                 return (-2);
316         return (nbytes);
317 } /* static int net_recv (int sockfd, char *buf, int buflen) */
319 /*
320  * Send a message over the network. The send consists of
321  * two network packets. The first is sends a short containing
322  * the length of the data packet which follows.
323  * Returns zero on success
324  * Returns non-zero on error
325  */
326 static int net_send (int sockfd, char *buff, int len)
328         int rc;
329         short packet_size;
331         /* send short containing size of data packet */
332         packet_size = htons ((short) len);
334         rc = write_nbytes(sockfd, &packet_size, sizeof (packet_size));
335         if (rc != sizeof(packet_size))
336                 return (-1);
338         /* send data packet */
339         rc = write_nbytes (sockfd, buff, len);
340         if (rc != len)
341                 return (-1);
343         return (0);
346 /* Get and print status from apcupsd NIS server */
347 static int do_pthreads_status (char *host, int port,
348                 struct apc_detail_s *apcups_detail)
350         int     sockfd;
351         int     n;
352         char    recvline[MAXSTRING + 1];
353         char   *tokptr;
354         char   *key;
355         double  value;
356 #if APCMAIN
357 # define PRINT_VALUE(name, val) printf("  Found property: name = %s; value = %f;\n", name, val)
358 #else
359 # define PRINT_VALUE(name, val) /**/
360 #endif
362         /* TODO: Keep the socket open, if possible */
363         if ((sockfd = net_open (host, NULL, port)) < 0)
364         {
365                 syslog (LOG_ERR, "apcups plugin: Connecting to the apcupsd failed.");
366                 return (-1);
367         }
369         net_send (sockfd, "status", 6);
371         while ((n = net_recv (sockfd, recvline, sizeof (recvline))) > 0)
372         {
373                 recvline[n] = '\0';
374 #if APCMAIN
375                 printf ("net_recv = `%s';\n", recvline);
376 #endif /* if APCMAIN */
378                 tokptr = strtok (recvline, ":");
379                 while (tokptr != NULL)
380                 {
381                         key = tokptr;
382                         if ((tokptr = strtok (NULL, " \t")) == NULL)
383                                 continue;
384                         value = atof (tokptr);
385                         PRINT_VALUE (key, value);
387                         if (strcmp ("LINEV", key) == 0)
388                                 apcups_detail->linev = value;
389                         else if (strcmp ("BATTV", tokptr) == 0)
390                                 apcups_detail->battv = value;
391                         else if (strcmp ("ITEMP", tokptr) == 0)
392                                 apcups_detail->itemp = value;
393                         else if (strcmp ("LOADPCT", tokptr) == 0)
394                                 apcups_detail->loadpct = value;
395                         else if (strcmp ("BCHARGE", tokptr) == 0)
396                                 apcups_detail->bcharge = value;
397                         else if (strcmp ("OUTPUTV", tokptr) == 0)
398                                 apcups_detail->outputv = value;
399                         else if (strcmp ("LINEFREQ", tokptr) == 0)
400                                 apcups_detail->linefreq = value;
401                         else if (strcmp ("TIMELEFT", tokptr) == 0)
402                                 apcups_detail->timeleft = value;
403                         else
404                         {
405                                 syslog (LOG_WARNING, "apcups plugin: Received unknown property from apcupsd: `%s' = %f",
406                                                 key, value);
407                         }
409                         tokptr = strtok (NULL, ":");
410                 } /* while (tokptr != NULL) */
411         }
413         net_close (sockfd);
415         if (n < 0)
416         {
417                 syslog (LOG_WARNING, "apcups plugin: Error reading from socket");
418                 return (-1);
419         }
421         return (0);
424 #ifdef APCMAIN
425 int main(int argc, char **argv)
427         /* we are not really going to use this */
428         struct apc_detail_s apcups_detail;
430         if (!*host || strcmp(host, "0.0.0.0") == 0)
431                 host = "localhost";
433         do_pthreads_status(host, port, &apcups_detail);
435         return 0;
437 #else
438 static void apcups_init (void)
440         return;
443 static int apcups_config (char *key, char *value)
445   static char lhost[126];
446   
447   if (strcasecmp (key, "host") == 0)
448     {
449       lhost[0] = '\0';
450       strcpy(lhost,key);
451       host = lhost;
452     }
453   else if (strcasecmp (key, "Port") == 0)
454     {
455       int port_tmp = atoi (value);
456       if(port_tmp < 1 || port_tmp > 65535) {
457         syslog (LOG_WARNING, "apcups: `port' failed: %s",
458                 value);
459         return (1);
460       } else {
461         port = port_tmp;
462       }
463     }
464   else
465     {
466       return (-1);
467     }
468   return(0);
471 #define BUFSIZE 256
472 static void apcups_submit (char *host,
473                            struct apc_detail_s *apcups_detail)
475         char buf[BUFSIZE];
477         if (snprintf (buf, BUFSIZE, "%u:%f:%f",
478                       (unsigned int) curtime,
479                       apcups_detail->linev,
480                       apcups_detail->outputv) >= BUFSIZE)
481           return;
482         
483         plugin_submit (MODULE_NAME, host, buf);
486 static void apc_bvolt_submit (char *host,
487                            struct apc_detail_s *apcups_detail)
489         char buf[BUFSIZE];
491         if (snprintf (buf, BUFSIZE, "%u:%f",
492                       (unsigned int) curtime,
493                       apcups_detail->battv) >= BUFSIZE)
494           return;
495         
496         plugin_submit ("apcups_bvolt", host, buf);
499 static void apc_load_submit (char *host,
500                            struct apc_detail_s *apcups_detail)
502         char buf[BUFSIZE];
504         if (snprintf (buf, BUFSIZE, "%u:%f",
505                       (unsigned int) curtime,
506                       apcups_detail->loadpct) >= BUFSIZE)
507           return;
508         
509         plugin_submit ("apcups_load", host, buf);
512 static void apc_charge_submit (char *host,
513                            struct apc_detail_s *apcups_detail)
515         char buf[BUFSIZE];
517         if (snprintf (buf, BUFSIZE, "%u:%f",
518                       (unsigned int) curtime,
519                       apcups_detail->bcharge) >= BUFSIZE)
520           return;
521         
522         plugin_submit ("apcups_charge", host, buf);
525 static void apc_temp_submit (char *host,
526                            struct apc_detail_s *apcups_detail)
528         char buf[BUFSIZE];
530         if (snprintf (buf, BUFSIZE, "%u:%f",
531                       (unsigned int) curtime,
532                       apcups_detail->itemp) >= BUFSIZE)
533           return;
534         
535         plugin_submit ("apcups_temp", host, buf);
538 static void apc_time_submit (char *host,
539                            struct apc_detail_s *apcups_detail)
541         char buf[BUFSIZE];
543         if (snprintf (buf, BUFSIZE, "%u:%f",
544                       (unsigned int) curtime,
545                       apcups_detail->timeleft) >= BUFSIZE)
546           return;
547         
548         plugin_submit ("apcups_time", host, buf);
551 static void apc_freq_submit (char *host,
552                            struct apc_detail_s *apcups_detail)
554         char buf[BUFSIZE];
556         if (snprintf (buf, BUFSIZE, "%u:%f",
557                       (unsigned int) curtime,
558                       apcups_detail->linefreq) >= BUFSIZE)
559           return;
560         
561         plugin_submit ("apcups_freq", host, buf);
563 #undef BUFSIZE
565 static void apcups_read (void)
567   struct apc_detail_s apcups_detail;
568   int status;
569         
570   apcups_detail.linev = 0.0;
571   apcups_detail.loadpct = 0.0;
572   apcups_detail.bcharge = 0.0;
573   apcups_detail.timeleft = 0.0;
574   apcups_detail.outputv = 0.0;
575   apcups_detail.itemp = 0.0;
576   apcups_detail.battv = 0.0;
577   apcups_detail.linefreq = 0.0;
579   
580   if (!*host || strcmp(host, "0.0.0.0") == 0)
581     host = "localhost";
582   
583   status = do_pthreads_status(host, port, &apcups_detail);
584  
585   /*
586    * if we did not connect then do not bother submitting
587    * zeros. We want rrd files to have NAN.
588   */
589   if (status != 0)
590           return;
592   apcups_submit (host, &apcups_detail);
593   apc_bvolt_submit (host, &apcups_detail);
594   apc_load_submit (host, &apcups_detail);
595   apc_charge_submit (host, &apcups_detail);
596   apc_temp_submit (host, &apcups_detail);
597   apc_time_submit (host, &apcups_detail);
598   apc_freq_submit (host, &apcups_detail);
602 static void apcups_write (char *host, char *inst, char *val)
604   char file[512];
605   int status;
606   
607   status = snprintf (file, 512, volt_file_template, inst);
608   if (status < 1)
609     return;
610   else if (status >= 512)
611     return;
612   
613   rrd_update_file (host, file, val, volt_ds_def, volt_ds_num);
616 static void apc_bvolt_write (char *host, char *inst, char *val)
618   char file[512];
619   int status;
620   
621   status = snprintf (file, 512, bvolt_file_template, inst);
622   if (status < 1)
623     return;
624   else if (status >= 512)
625     return;
626   
627   rrd_update_file (host, file, val, bvolt_ds_def, bvolt_ds_num);
630 static void apc_load_write (char *host, char *inst, char *val)
632   char file[512];
633   int status;
634   
635   status = snprintf (file, 512, load_file_template, inst);
636   if (status < 1)
637     return;
638   else if (status >= 512)
639     return;
640   
641   rrd_update_file (host, file, val, load_ds_def, load_ds_num);
644 static void apc_charge_write (char *host, char *inst, char *val)
646   char file[512];
647   int status;
648   
649   status = snprintf (file, 512, charge_file_template, inst);
650   if (status < 1)
651     return;
652   else if (status >= 512)
653     return;
654   
655   rrd_update_file (host, file, val, charge_ds_def, charge_ds_num);
658 static void apc_temp_write (char *host, char *inst, char *val)
660   char file[512];
661   int status;
662   
663   status = snprintf (file, 512, temp_file_template, inst);
664   if (status < 1)
665     return;
666   else if (status >= 512)
667     return;
668   
669   rrd_update_file (host, file, val, temp_ds_def, temp_ds_num);
672 static void apc_time_write (char *host, char *inst, char *val)
674   char file[512];
675   int status;
676   
677   status = snprintf (file, 512, time_file_template, inst);
678   if (status < 1)
679     return;
680   else if (status >= 512)
681     return;
682   
683   rrd_update_file (host, file, val, time_ds_def, time_ds_num);
686 static void apc_freq_write (char *host, char *inst, char *val)
688   char file[512];
689   int status;
690   
691   status = snprintf (file, 512, freq_file_template, inst);
692   if (status < 1)
693     return;
694   else if (status >= 512)
695     return;
696   
697   rrd_update_file (host, file, val, freq_ds_def, freq_ds_num);
700 void module_register (void)
702         plugin_register (MODULE_NAME, apcups_init, apcups_read, apcups_write);
703         plugin_register ("apcups_bvolt", NULL, NULL, apc_bvolt_write);
704         plugin_register ("apcups_load", NULL, NULL, apc_load_write);
705         plugin_register ("apcups_charge", NULL, NULL, apc_charge_write);
706         plugin_register ("apcups_temp", NULL, NULL, apc_temp_write);
707         plugin_register ("apcups_time", NULL, NULL, apc_time_write);
708         plugin_register ("apcups_freq", NULL, NULL, apc_freq_write);
709         cf_register (MODULE_NAME, apcups_config, config_keys, config_keys_num);
712 #endif /* ifdef APCMAIN */
713 #undef MODULE_NAME