Merge branch 'master' into collectd-4
[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
37 #if HAVE_SYS_TYPES_H
38 # include <sys/types.h>
39 #endif
40 #if HAVE_SYS_SOCKET_H
41 # include <sys/socket.h>
42 #endif
43 #if HAVE_NETDB_H
44 # include <netdb.h>
45 #endif
46
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 #define APCUPS_DEFAULT_HOST "localhost"
56
57 /*
58  * Private data types
59  */
60 struct apc_detail_s
61 {
62         double linev;
63         double loadpct;
64         double bcharge;
65         double timeleft;
66         double outputv;
67         double itemp;
68         double battv;
69         double linefreq;
70 };
71
72 /*
73  * Private variables
74  */
75 /* Default values for contacting daemon */
76 static char *conf_host = NULL;
77 static int   conf_port = NISPORT;
78
79 static int global_sockfd = -1;
80
81 /* 
82  * The following are only if not compiled to test the module with its own main.
83 */
84 static data_source_t data_source_voltage[1] =
85 {
86         {"value", DS_TYPE_GAUGE, NAN, NAN}
87 };
88
89 static data_set_t ds_voltage =
90 {
91         "voltage", 1, data_source_voltage
92 };
93
94 static data_source_t data_source_percent[1] =
95 {
96         {"percent", DS_TYPE_GAUGE, 0, 100.1}
97 };
98
99 static data_set_t ds_percent =
100 {
101         "percent", 1, data_source_percent
102 };
103
104 static data_source_t data_source_timeleft[1] =
105 {
106         {"timeleft", DS_TYPE_GAUGE, 0, 100.0}
107 };
108
109 static data_set_t ds_timeleft =
110 {
111         "timeleft", 1, data_source_timeleft
112 };
113
114 static data_source_t data_source_temperature[1] =
115 {
116         {"value", DS_TYPE_GAUGE, -273.15, NAN}
117 };
118
119 static data_set_t ds_temperature =
120 {
121         "temperature", 1, data_source_temperature
122 };
123
124 static data_source_t data_source_frequency[1] =
125 {
126         {"frequency", DS_TYPE_GAUGE, 0, NAN}
127 };
128
129 static data_set_t ds_frequency =
130 {
131         "frequency", 1, data_source_frequency
132 };
133
134 static const char *config_keys[] =
135 {
136         "Host",
137         "Port",
138         NULL
139 };
140 static int config_keys_num = 2;
141
142 /* Close the network connection */
143 static int apcups_shutdown (void)
144 {
145         uint16_t packet_size = 0;
146
147         if (global_sockfd < 0)
148                 return (0);
149
150         DEBUG ("Gracefully shutting down socket %i.", global_sockfd);
151
152         /* send EOF sentinel */
153         swrite (global_sockfd, (void *) &packet_size, sizeof (packet_size));
154
155         close (global_sockfd);
156         global_sockfd = -1;
157
158         return (0);
159 } /* int apcups_shutdown */
160
161 /*     
162  * Open a TCP connection to the UPS network server
163  * Returns -1 on error
164  * Returns socket file descriptor otherwise
165  */
166 static int net_open (char *host, char *service, int port)
167 {
168         int              sd;
169         int              status;
170         char             port_str[8];
171         struct addrinfo  ai_hints;
172         struct addrinfo *ai_return;
173         struct addrinfo *ai_list;
174
175         assert ((port > 0x00000000) && (port <= 0x0000FFFF));
176
177         /* Convert the port to a string */
178         snprintf (port_str, 8, "%i", port);
179         port_str[7] = '\0';
180
181         /* Resolve name */
182         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
183         ai_hints.ai_family   = AF_INET; /* XXX: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
184         ai_hints.ai_socktype = SOCK_STREAM;
185
186         status = getaddrinfo (host, port_str, &ai_hints, &ai_return);
187         if (status != 0)
188         {
189                 char errbuf[1024];
190                 DEBUG ("getaddrinfo failed: %s",
191                                 (status == EAI_SYSTEM)
192                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
193                                 : gai_strerror (status));
194                 return (-1);
195         }
196
197         /* Create socket */
198         sd = -1;
199         for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
200         {
201                 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
202                 if (sd >= 0)
203                         break;
204         }
205         /* `ai_list' still holds the current description of the socket.. */
206
207         if (sd < 0)
208         {
209                 DEBUG ("Unable to open a socket");
210                 freeaddrinfo (ai_return);
211                 return (-1);
212         }
213
214         status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
215
216         freeaddrinfo (ai_return);
217
218         if (status != 0) /* `connect(2)' failed */
219         {
220                 char errbuf[1024];
221                 DEBUG ("connect failed: %s",
222                                 sstrerror (errno, errbuf, sizeof (errbuf)));
223                 close (sd);
224                 return (-1);
225         }
226
227         DEBUG ("Done opening a socket %i", sd);
228
229         return (sd);
230 } /* int net_open (char *host, char *service, int port) */
231
232 /* 
233  * Receive a message from the other end. Each message consists of
234  * two packets. The first is a header that contains the size
235  * of the data that follows in the second packet.
236  * Returns number of bytes read
237  * Returns 0 on end of file
238  * Returns -1 on hard end of file (i.e. network connection close)
239  * Returns -2 on error
240  */
241 static int net_recv (int *sockfd, char *buf, int buflen)
242 {
243         uint16_t packet_size;
244
245         /* get data size -- in short */
246         if (sread (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
247         {
248                 *sockfd = -1;
249                 return (-1);
250         }
251
252         packet_size = ntohs (packet_size);
253         if (packet_size > buflen)
254         {
255                 DEBUG ("record length too large");
256                 return (-2);
257         }
258
259         if (packet_size == 0)
260                 return (0);
261
262         /* now read the actual data */
263         if (sread (*sockfd, (void *) buf, packet_size) != 0)
264         {
265                 *sockfd = -1;
266                 return (-1);
267         }
268
269         return ((int) packet_size);
270 } /* static int net_recv (int *sockfd, char *buf, int buflen) */
271
272 /*
273  * Send a message over the network. The send consists of
274  * two network packets. The first is sends a short containing
275  * the length of the data packet which follows.
276  * Returns zero on success
277  * Returns non-zero on error
278  */
279 static int net_send (int *sockfd, char *buff, int len)
280 {
281         uint16_t packet_size;
282
283         assert (len > 0);
284         assert (*sockfd >= 0);
285
286         /* send short containing size of data packet */
287         packet_size = htons ((uint16_t) len);
288
289         if (swrite (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
290         {
291                 *sockfd = -1;
292                 return (-1);
293         }
294
295         /* send data packet */
296         if (swrite (*sockfd, (void *) buff, len) != 0)
297         {
298                 *sockfd = -1;
299                 return (-2);
300         }
301
302         return (0);
303 }
304
305 /* Get and print status from apcupsd NIS server */
306 static int apc_query_server (char *host, int port,
307                 struct apc_detail_s *apcups_detail)
308 {
309         int     n;
310         char    recvline[1024];
311         char   *tokptr;
312         char   *toksaveptr;
313         char   *key;
314         double  value;
315
316         static complain_t compl;
317
318 #if APCMAIN
319 # define PRINT_VALUE(name, val) printf("  Found property: name = %s; value = %f;\n", name, val)
320 #else
321 # define PRINT_VALUE(name, val) /**/
322 #endif
323
324         if (global_sockfd < 0)
325         {
326                 if ((global_sockfd = net_open (host, NULL, port)) < 0)
327                 {
328                         plugin_complain (LOG_ERR, &compl, "apcups plugin: "
329                                         "Connecting to the apcupsd failed.");
330                         return (-1);
331                 }
332                 else
333                 {
334                         plugin_relief (LOG_NOTICE, &compl, "apcups plugin: "
335                                         "Connection re-established to the apcupsd.");
336                 }
337         }
338
339         if (net_send (&global_sockfd, "status", 6) < 0)
340         {
341                 ERROR ("apcups plugin: Writing to the socket failed.");
342                 return (-1);
343         }
344
345         while ((n = net_recv (&global_sockfd, recvline, sizeof (recvline) - 1)) > 0)
346         {
347                 assert (n < sizeof (recvline));
348                 recvline[n] = '\0';
349 #if APCMAIN
350                 printf ("net_recv = `%s';\n", recvline);
351 #endif /* if APCMAIN */
352
353                 toksaveptr = NULL;
354                 tokptr = strtok_r (recvline, " :\t", &toksaveptr);
355                 while (tokptr != NULL)
356                 {
357                         key = tokptr;
358                         if ((tokptr = strtok_r (NULL, " :\t", &toksaveptr)) == NULL)
359                                 continue;
360                         value = atof (tokptr);
361
362                         PRINT_VALUE (key, value);
363
364                         if (strcmp ("LINEV", key) == 0)
365                                 apcups_detail->linev = value;
366                         else if (strcmp ("BATTV", key) == 0) 
367                                 apcups_detail->battv = value;
368                         else if (strcmp ("ITEMP", key) == 0)
369                                 apcups_detail->itemp = value;
370                         else if (strcmp ("LOADPCT", key) == 0)
371                                 apcups_detail->loadpct = value;
372                         else if (strcmp ("BCHARGE", key) == 0)
373                                 apcups_detail->bcharge = value;
374                         else if (strcmp ("OUTPUTV", key) == 0)
375                                 apcups_detail->outputv = value;
376                         else if (strcmp ("LINEFREQ", key) == 0)
377                                 apcups_detail->linefreq = value;
378                         else if (strcmp ("TIMELEFT", key) == 0)
379                                 apcups_detail->timeleft = value;
380
381                         tokptr = strtok_r (NULL, ":", &toksaveptr);
382                 } /* while (tokptr != NULL) */
383         }
384         
385         if (n < 0)
386         {
387                 WARNING ("apcups plugin: Error reading from socket");
388                 return (-1);
389         }
390
391         return (0);
392 }
393
394 static int apcups_config (const char *key, const char *value)
395 {
396         if (strcasecmp (key, "host") == 0)
397         {
398                 if (conf_host != NULL)
399                 {
400                         free (conf_host);
401                         conf_host = NULL;
402                 }
403                 if ((conf_host = strdup (value)) == NULL)
404                         return (1);
405         }
406         else if (strcasecmp (key, "Port") == 0)
407         {
408                 int port_tmp = atoi (value);
409                 if (port_tmp < 1 || port_tmp > 65535)
410                 {
411                         WARNING ("apcups plugin: Invalid port: %i", port_tmp);
412                         return (1);
413                 }
414                 conf_port = port_tmp;
415         }
416         else
417         {
418                 return (-1);
419         }
420         return (0);
421 }
422
423 static void apc_submit_generic (char *type, char *type_inst, double value)
424 {
425         value_t values[1];
426         value_list_t vl = VALUE_LIST_INIT;
427
428         values[0].gauge = value;
429
430         vl.values = values;
431         vl.values_len = 1;
432         vl.time = time (NULL);
433         strcpy (vl.host, hostname_g);
434         strcpy (vl.plugin, "apcups");
435         strcpy (vl.plugin_instance, "");
436         strncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
437
438         plugin_dispatch_values (type, &vl);
439 }
440
441 static void apc_submit (struct apc_detail_s *apcups_detail)
442 {
443         apc_submit_generic ("apcups_voltage",    "input",   apcups_detail->linev);
444         apc_submit_generic ("apcups_voltage",    "output",  apcups_detail->outputv);
445         apc_submit_generic ("apcups_voltage",    "battery", apcups_detail->battv);
446         apc_submit_generic ("apcups_charge",     "",        apcups_detail->bcharge);
447         apc_submit_generic ("apcups_charge_pct", "",        apcups_detail->loadpct);
448         apc_submit_generic ("apcups_timeleft",   "",        apcups_detail->timeleft);
449         apc_submit_generic ("apcups_temp",       "",        apcups_detail->itemp);
450         apc_submit_generic ("apcups_frequency",  "input",   apcups_detail->linefreq);
451 }
452
453 static int apcups_read (void)
454 {
455         struct apc_detail_s apcups_detail;
456         int status;
457
458         apcups_detail.linev    =   -1.0;
459         apcups_detail.outputv  =   -1.0;
460         apcups_detail.battv    =   -1.0;
461         apcups_detail.loadpct  =   -1.0;
462         apcups_detail.bcharge  =   -1.0;
463         apcups_detail.timeleft =   -1.0;
464         apcups_detail.itemp    = -300.0;
465         apcups_detail.linefreq =   -1.0;
466   
467         status = apc_query_server (conf_host == NULL
468                         ? APCUPS_DEFAULT_HOST
469                         : conf_host,
470                         conf_port, &apcups_detail);
471  
472         /*
473          * if we did not connect then do not bother submitting
474          * zeros. We want rrd files to have NAN.
475          */
476         if (status != 0)
477         {
478                 DEBUG ("apc_query_server (%s, %i) = %i",
479                                 conf_host == NULL
480                                 ? APCUPS_DEFAULT_HOST
481                                 : conf_host,
482                                 conf_port, status);
483                 return (-1);
484         }
485
486         apc_submit (&apcups_detail);
487
488         return (0);
489 } /* apcups_read */
490
491 void module_register (modreg_e load)
492 {
493         if (load & MR_DATASETS)
494         {
495                 plugin_register_data_set (&ds_voltage);
496                 plugin_register_data_set (&ds_percent);
497                 plugin_register_data_set (&ds_timeleft);
498                 plugin_register_data_set (&ds_temperature);
499                 plugin_register_data_set (&ds_frequency);
500         }
501
502         if (load & MR_READ)
503         {
504                 plugin_register_config ("apcups", apcups_config, config_keys,
505                                 config_keys_num);
506                 plugin_register_read ("apcups", apcups_read);
507                 plugin_register_shutdown ("apcups", apcups_shutdown);
508         }
509 } /* void module_register */