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