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