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