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