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