Merge branch 'collectd-4.0' into collectd-4.1
[collectd.git] / src / apcups.c
1 /*
2  * collectd - src/apcups.c
3  * Copyright (C) 2007 Florian octo Forster
4  * Copyright (C) 2006 Anthony Gialluca <tonyabg at charter.net>
5  * Copyright (C) 2000-2004 Kern Sibbald
6  * Copyright (C) 1996-99 Andre M. Hedrick <andre at suse.com>
7  *
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of version 2 of the GNU General
11  * Public License as published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public
19  * License along with this program; if not, write to the Free
20  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
21  * MA 02111-1307, USA.
22  *
23  * Authors:
24  *   Anthony Gialluca <tonyabg at charter.net>
25  **/
26
27 /*
28  * FIXME: Don't know why but without this here atof() was not returning
29  * correct values for me. This is behavior that I don't understand and
30  * should be examined in closer detail.
31  */
32 #include <stdlib.h>
33
34 #include "collectd.h"
35 #include "common.h"      /* rrd_update_file */
36 #include "plugin.h"      /* plugin_register, plugin_submit */
37 #include "configfile.h"  /* cf_register */
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 #define NISPORT 3551
54 #define MAXSTRING               256
55 #define MODULE_NAME "apcups"
56
57 #define APCUPS_DEFAULT_HOST "localhost"
58
59 /*
60  * Private data types
61  */
62 struct apc_detail_s
63 {
64         double linev;
65         double loadpct;
66         double bcharge;
67         double timeleft;
68         double outputv;
69         double itemp;
70         double battv;
71         double linefreq;
72 };
73
74 /*
75  * Private variables
76  */
77 /* Default values for contacting daemon */
78 static char *conf_host = NULL;
79 static int   conf_port = NISPORT;
80
81 static int global_sockfd = -1;
82
83 static const char *config_keys[] =
84 {
85         "Host",
86         "Port",
87         NULL
88 };
89 static int config_keys_num = 2;
90
91 /* Close the network connection */
92 static int apcups_shutdown (void)
93 {
94         uint16_t packet_size = 0;
95
96         if (global_sockfd < 0)
97                 return (0);
98
99         DEBUG ("Gracefully shutting down socket %i.", global_sockfd);
100
101         /* send EOF sentinel */
102         swrite (global_sockfd, (void *) &packet_size, sizeof (packet_size));
103
104         close (global_sockfd);
105         global_sockfd = -1;
106
107         return (0);
108 } /* int apcups_shutdown */
109
110 /*     
111  * Open a TCP connection to the UPS network server
112  * Returns -1 on error
113  * Returns socket file descriptor otherwise
114  */
115 static int net_open (char *host, char *service, int port)
116 {
117         int              sd;
118         int              status;
119         char             port_str[8];
120         struct addrinfo  ai_hints;
121         struct addrinfo *ai_return;
122         struct addrinfo *ai_list;
123
124         assert ((port > 0x00000000) && (port <= 0x0000FFFF));
125
126         /* Convert the port to a string */
127         snprintf (port_str, 8, "%i", port);
128         port_str[7] = '\0';
129
130         /* Resolve name */
131         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
132         ai_hints.ai_family   = AF_INET; /* XXX: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
133         ai_hints.ai_socktype = SOCK_STREAM;
134
135         status = getaddrinfo (host, port_str, &ai_hints, &ai_return);
136         if (status != 0)
137         {
138                 char errbuf[1024];
139                 DEBUG ("getaddrinfo failed: %s",
140                                 (status == EAI_SYSTEM)
141                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
142                                 : gai_strerror (status));
143                 return (-1);
144         }
145
146         /* Create socket */
147         sd = -1;
148         for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
149         {
150                 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
151                 if (sd >= 0)
152                         break;
153         }
154         /* `ai_list' still holds the current description of the socket.. */
155
156         if (sd < 0)
157         {
158                 DEBUG ("Unable to open a socket");
159                 freeaddrinfo (ai_return);
160                 return (-1);
161         }
162
163         status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
164
165         freeaddrinfo (ai_return);
166
167         if (status != 0) /* `connect(2)' failed */
168         {
169                 char errbuf[1024];
170                 DEBUG ("connect failed: %s",
171                                 sstrerror (errno, errbuf, sizeof (errbuf)));
172                 close (sd);
173                 return (-1);
174         }
175
176         DEBUG ("Done opening a socket %i", sd);
177
178         return (sd);
179 } /* int net_open (char *host, char *service, int port) */
180
181 /* 
182  * Receive a message from the other end. Each message consists of
183  * two packets. The first is a header that contains the size
184  * of the data that follows in the second packet.
185  * Returns number of bytes read
186  * Returns 0 on end of file
187  * Returns -1 on hard end of file (i.e. network connection close)
188  * Returns -2 on error
189  */
190 static int net_recv (int *sockfd, char *buf, int buflen)
191 {
192         uint16_t packet_size;
193
194         /* get data size -- in short */
195         if (sread (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
196         {
197                 *sockfd = -1;
198                 return (-1);
199         }
200
201         packet_size = ntohs (packet_size);
202         if (packet_size > buflen)
203         {
204                 DEBUG ("record length too large");
205                 return (-2);
206         }
207
208         if (packet_size == 0)
209                 return (0);
210
211         /* now read the actual data */
212         if (sread (*sockfd, (void *) buf, packet_size) != 0)
213         {
214                 *sockfd = -1;
215                 return (-1);
216         }
217
218         return ((int) packet_size);
219 } /* static int net_recv (int *sockfd, char *buf, int buflen) */
220
221 /*
222  * Send a message over the network. The send consists of
223  * two network packets. The first is sends a short containing
224  * the length of the data packet which follows.
225  * Returns zero on success
226  * Returns non-zero on error
227  */
228 static int net_send (int *sockfd, char *buff, int len)
229 {
230         uint16_t packet_size;
231
232         assert (len > 0);
233         assert (*sockfd >= 0);
234
235         /* send short containing size of data packet */
236         packet_size = htons ((uint16_t) len);
237
238         if (swrite (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
239         {
240                 *sockfd = -1;
241                 return (-1);
242         }
243
244         /* send data packet */
245         if (swrite (*sockfd, (void *) buff, len) != 0)
246         {
247                 *sockfd = -1;
248                 return (-2);
249         }
250
251         return (0);
252 }
253
254 /* Get and print status from apcupsd NIS server */
255 static int apc_query_server (char *host, int port,
256                 struct apc_detail_s *apcups_detail)
257 {
258         int     n;
259         char    recvline[1024];
260         char   *tokptr;
261         char   *toksaveptr;
262         char   *key;
263         double  value;
264
265         static complain_t compl;
266
267 #if APCMAIN
268 # define PRINT_VALUE(name, val) printf("  Found property: name = %s; value = %f;\n", name, val)
269 #else
270 # define PRINT_VALUE(name, val) /**/
271 #endif
272
273         if (global_sockfd < 0)
274         {
275                 if ((global_sockfd = net_open (host, NULL, port)) < 0)
276                 {
277                         plugin_complain (LOG_ERR, &compl, "apcups plugin: "
278                                         "Connecting to the apcupsd failed.");
279                         return (-1);
280                 }
281                 else
282                 {
283                         plugin_relief (LOG_NOTICE, &compl, "apcups plugin: "
284                                         "Connection re-established to the apcupsd.");
285                 }
286         }
287
288         if (net_send (&global_sockfd, "status", 6) < 0)
289         {
290                 ERROR ("apcups plugin: Writing to the socket failed.");
291                 return (-1);
292         }
293
294         while ((n = net_recv (&global_sockfd, recvline, sizeof (recvline) - 1)) > 0)
295         {
296                 assert (n < sizeof (recvline));
297                 recvline[n] = '\0';
298 #if APCMAIN
299                 printf ("net_recv = `%s';\n", recvline);
300 #endif /* if APCMAIN */
301
302                 toksaveptr = NULL;
303                 tokptr = strtok_r (recvline, " :\t", &toksaveptr);
304                 while (tokptr != NULL)
305                 {
306                         key = tokptr;
307                         if ((tokptr = strtok_r (NULL, " :\t", &toksaveptr)) == NULL)
308                                 continue;
309                         value = atof (tokptr);
310
311                         PRINT_VALUE (key, value);
312
313                         if (strcmp ("LINEV", key) == 0)
314                                 apcups_detail->linev = value;
315                         else if (strcmp ("BATTV", key) == 0) 
316                                 apcups_detail->battv = value;
317                         else if (strcmp ("ITEMP", key) == 0)
318                                 apcups_detail->itemp = value;
319                         else if (strcmp ("LOADPCT", key) == 0)
320                                 apcups_detail->loadpct = value;
321                         else if (strcmp ("BCHARGE", key) == 0)
322                                 apcups_detail->bcharge = value;
323                         else if (strcmp ("OUTPUTV", key) == 0)
324                                 apcups_detail->outputv = value;
325                         else if (strcmp ("LINEFREQ", key) == 0)
326                                 apcups_detail->linefreq = value;
327                         else if (strcmp ("TIMELEFT", key) == 0)
328                                 apcups_detail->timeleft = value;
329
330                         tokptr = strtok_r (NULL, ":", &toksaveptr);
331                 } /* while (tokptr != NULL) */
332         }
333         
334         if (n < 0)
335         {
336                 WARNING ("apcups plugin: Error reading from socket");
337                 return (-1);
338         }
339
340         return (0);
341 }
342
343 static int apcups_config (const char *key, const char *value)
344 {
345         if (strcasecmp (key, "host") == 0)
346         {
347                 if (conf_host != NULL)
348                 {
349                         free (conf_host);
350                         conf_host = NULL;
351                 }
352                 if ((conf_host = strdup (value)) == NULL)
353                         return (1);
354         }
355         else if (strcasecmp (key, "Port") == 0)
356         {
357                 int port_tmp = atoi (value);
358                 if (port_tmp < 1 || port_tmp > 65535)
359                 {
360                         WARNING ("apcups plugin: Invalid port: %i", port_tmp);
361                         return (1);
362                 }
363                 conf_port = port_tmp;
364         }
365         else
366         {
367                 return (-1);
368         }
369         return (0);
370 }
371
372 static void apc_submit_generic (char *type, char *type_inst, double value)
373 {
374         value_t values[1];
375         value_list_t vl = VALUE_LIST_INIT;
376
377         values[0].gauge = value;
378
379         vl.values = values;
380         vl.values_len = 1;
381         vl.time = time (NULL);
382         strcpy (vl.host, hostname_g);
383         strcpy (vl.plugin, "apcups");
384         strcpy (vl.plugin_instance, "");
385         strncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
386
387         plugin_dispatch_values (type, &vl);
388 }
389
390 static void apc_submit (struct apc_detail_s *apcups_detail)
391 {
392         apc_submit_generic ("voltage",    "input",   apcups_detail->linev);
393         apc_submit_generic ("voltage",    "output",  apcups_detail->outputv);
394         apc_submit_generic ("voltage",    "battery", apcups_detail->battv);
395         apc_submit_generic ("charge",     "",        apcups_detail->bcharge);
396         apc_submit_generic ("percent",    "load",    apcups_detail->loadpct);
397         apc_submit_generic ("timeleft",   "",        apcups_detail->timeleft);
398         apc_submit_generic ("temperature", "",       apcups_detail->itemp);
399         apc_submit_generic ("frequency",  "input",   apcups_detail->linefreq);
400 }
401
402 static int apcups_read (void)
403 {
404         struct apc_detail_s apcups_detail;
405         int status;
406
407         apcups_detail.linev    =   -1.0;
408         apcups_detail.outputv  =   -1.0;
409         apcups_detail.battv    =   -1.0;
410         apcups_detail.loadpct  =   -1.0;
411         apcups_detail.bcharge  =   -1.0;
412         apcups_detail.timeleft =   -1.0;
413         apcups_detail.itemp    = -300.0;
414         apcups_detail.linefreq =   -1.0;
415   
416         status = apc_query_server (conf_host == NULL
417                         ? APCUPS_DEFAULT_HOST
418                         : conf_host,
419                         conf_port, &apcups_detail);
420  
421         /*
422          * if we did not connect then do not bother submitting
423          * zeros. We want rrd files to have NAN.
424          */
425         if (status != 0)
426         {
427                 DEBUG ("apc_query_server (%s, %i) = %i",
428                                 conf_host == NULL
429                                 ? APCUPS_DEFAULT_HOST
430                                 : conf_host,
431                                 conf_port, status);
432                 return (-1);
433         }
434
435         apc_submit (&apcups_detail);
436
437         return (0);
438 } /* apcups_read */
439
440 void module_register (void)
441 {
442         plugin_register_config ("apcups", apcups_config, config_keys,
443                         config_keys_num);
444         plugin_register_read ("apcups", apcups_read);
445         plugin_register_shutdown ("apcups", apcups_shutdown);
446 } /* void module_register */