tcpconns plugin: Fix an endianness problem under *BSD.
[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 #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 /* Close the network connection */
85 static int apcups_shutdown (void)
86 {
87         uint16_t packet_size = 0;
88
89         if (global_sockfd < 0)
90                 return (0);
91
92         DEBUG ("Gracefully shutting down socket %i.", global_sockfd);
93
94         /* send EOF sentinel */
95         swrite (global_sockfd, (void *) &packet_size, sizeof (packet_size));
96
97         close (global_sockfd);
98         global_sockfd = -1;
99
100         return (0);
101 } /* int apcups_shutdown */
102
103 /*     
104  * Open a TCP connection to the UPS network server
105  * Returns -1 on error
106  * Returns socket file descriptor otherwise
107  */
108 static int net_open (char *host, int port)
109 {
110         int              sd;
111         int              status;
112         char             port_str[8];
113         struct addrinfo  ai_hints;
114         struct addrinfo *ai_return;
115         struct addrinfo *ai_list;
116
117         assert ((port > 0x00000000) && (port <= 0x0000FFFF));
118
119         /* Convert the port to a string */
120         snprintf (port_str, 8, "%i", port);
121         port_str[7] = '\0';
122
123         /* Resolve name */
124         memset ((void *) &ai_hints, '\0', sizeof (ai_hints));
125         ai_hints.ai_family   = AF_INET; /* XXX: Change this to `AF_UNSPEC' if apcupsd can handle IPv6 */
126         ai_hints.ai_socktype = SOCK_STREAM;
127
128         status = getaddrinfo (host, port_str, &ai_hints, &ai_return);
129         if (status != 0)
130         {
131                 char errbuf[1024];
132                 INFO ("getaddrinfo failed: %s",
133                                 (status == EAI_SYSTEM)
134                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
135                                 : gai_strerror (status));
136                 return (-1);
137         }
138
139         /* Create socket */
140         sd = -1;
141         for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
142         {
143                 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
144                 if (sd >= 0)
145                         break;
146         }
147         /* `ai_list' still holds the current description of the socket.. */
148
149         if (sd < 0)
150         {
151                 DEBUG ("Unable to open a socket");
152                 freeaddrinfo (ai_return);
153                 return (-1);
154         }
155
156         status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
157
158         freeaddrinfo (ai_return);
159
160         if (status != 0) /* `connect(2)' failed */
161         {
162                 char errbuf[1024];
163                 INFO ("connect failed: %s",
164                                 sstrerror (errno, errbuf, sizeof (errbuf)));
165                 close (sd);
166                 return (-1);
167         }
168
169         DEBUG ("Done opening a socket %i", sd);
170
171         return (sd);
172 } /* int net_open (char *host, char *service, int port) */
173
174 /* 
175  * Receive a message from the other end. Each message consists of
176  * two packets. The first is a header that contains the size
177  * of the data that follows in the second packet.
178  * Returns number of bytes read
179  * Returns 0 on end of file
180  * Returns -1 on hard end of file (i.e. network connection close)
181  * Returns -2 on error
182  */
183 static int net_recv (int *sockfd, char *buf, int buflen)
184 {
185         uint16_t packet_size;
186
187         /* get data size -- in short */
188         if (sread (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
189         {
190                 *sockfd = -1;
191                 return (-1);
192         }
193
194         packet_size = ntohs (packet_size);
195         if (packet_size > buflen)
196         {
197                 DEBUG ("record length too large");
198                 return (-2);
199         }
200
201         if (packet_size == 0)
202                 return (0);
203
204         /* now read the actual data */
205         if (sread (*sockfd, (void *) buf, packet_size) != 0)
206         {
207                 *sockfd = -1;
208                 return (-1);
209         }
210
211         return ((int) packet_size);
212 } /* static int net_recv (int *sockfd, char *buf, int buflen) */
213
214 /*
215  * Send a message over the network. The send consists of
216  * two network packets. The first is sends a short containing
217  * the length of the data packet which follows.
218  * Returns zero on success
219  * Returns non-zero on error
220  */
221 static int net_send (int *sockfd, char *buff, int len)
222 {
223         uint16_t packet_size;
224
225         assert (len > 0);
226         assert (*sockfd >= 0);
227
228         /* send short containing size of data packet */
229         packet_size = htons ((uint16_t) len);
230
231         if (swrite (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
232         {
233                 *sockfd = -1;
234                 return (-1);
235         }
236
237         /* send data packet */
238         if (swrite (*sockfd, (void *) buff, len) != 0)
239         {
240                 *sockfd = -1;
241                 return (-2);
242         }
243
244         return (0);
245 }
246
247 /* Get and print status from apcupsd NIS server */
248 static int apc_query_server (char *host, int port,
249                 struct apc_detail_s *apcups_detail)
250 {
251         int     n;
252         char    recvline[1024];
253         char   *tokptr;
254         char   *toksaveptr;
255         char   *key;
256         double  value;
257
258 #if APCMAIN
259 # define PRINT_VALUE(name, val) printf("  Found property: name = %s; value = %f;\n", name, val)
260 #else
261 # define PRINT_VALUE(name, val) /**/
262 #endif
263
264         if (global_sockfd < 0)
265         {
266                 global_sockfd = net_open (host, port);
267                 if (global_sockfd < 0)
268                 {
269                         ERROR ("apcups plugin: Connecting to the "
270                                         "apcupsd failed.");
271                         return (-1);
272                 }
273         }
274
275         if (net_send (&global_sockfd, "status", 6) < 0)
276         {
277                 ERROR ("apcups plugin: Writing to the socket failed.");
278                 return (-1);
279         }
280
281         while ((n = net_recv (&global_sockfd, recvline, sizeof (recvline) - 1)) > 0)
282         {
283                 assert ((unsigned int)n < sizeof (recvline));
284                 recvline[n] = '\0';
285 #if APCMAIN
286                 printf ("net_recv = `%s';\n", recvline);
287 #endif /* if APCMAIN */
288
289                 toksaveptr = NULL;
290                 tokptr = strtok_r (recvline, " :\t", &toksaveptr);
291                 while (tokptr != NULL)
292                 {
293                         key = tokptr;
294                         if ((tokptr = strtok_r (NULL, " :\t", &toksaveptr)) == NULL)
295                                 continue;
296                         value = atof (tokptr);
297
298                         PRINT_VALUE (key, value);
299
300                         if (strcmp ("LINEV", key) == 0)
301                                 apcups_detail->linev = value;
302                         else if (strcmp ("BATTV", key) == 0) 
303                                 apcups_detail->battv = value;
304                         else if (strcmp ("ITEMP", key) == 0)
305                                 apcups_detail->itemp = value;
306                         else if (strcmp ("LOADPCT", key) == 0)
307                                 apcups_detail->loadpct = value;
308                         else if (strcmp ("BCHARGE", key) == 0)
309                                 apcups_detail->bcharge = value;
310                         else if (strcmp ("OUTPUTV", key) == 0)
311                                 apcups_detail->outputv = value;
312                         else if (strcmp ("LINEFREQ", key) == 0)
313                                 apcups_detail->linefreq = value;
314                         else if (strcmp ("TIMELEFT", key) == 0)
315                                 apcups_detail->timeleft = value;
316
317                         tokptr = strtok_r (NULL, ":", &toksaveptr);
318                 } /* while (tokptr != NULL) */
319         }
320         
321         if (n < 0)
322         {
323                 WARNING ("apcups plugin: Error reading from socket");
324                 return (-1);
325         }
326
327         return (0);
328 }
329
330 static int apcups_config (const char *key, const char *value)
331 {
332         if (strcasecmp (key, "host") == 0)
333         {
334                 if (conf_host != NULL)
335                 {
336                         free (conf_host);
337                         conf_host = NULL;
338                 }
339                 if ((conf_host = strdup (value)) == NULL)
340                         return (1);
341         }
342         else if (strcasecmp (key, "Port") == 0)
343         {
344                 int port_tmp = atoi (value);
345                 if (port_tmp < 1 || port_tmp > 65535)
346                 {
347                         WARNING ("apcups plugin: Invalid port: %i", port_tmp);
348                         return (1);
349                 }
350                 conf_port = port_tmp;
351         }
352         else
353         {
354                 return (-1);
355         }
356         return (0);
357 }
358
359 static void apc_submit_generic (char *type, char *type_inst, double value)
360 {
361         value_t values[1];
362         value_list_t vl = VALUE_LIST_INIT;
363
364         values[0].gauge = value;
365
366         vl.values = values;
367         vl.values_len = 1;
368         vl.time = time (NULL);
369         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
370         sstrncpy (vl.plugin, "apcups", sizeof (vl.plugin));
371         sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
372         strncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
373
374         plugin_dispatch_values (type, &vl);
375 }
376
377 static void apc_submit (struct apc_detail_s *apcups_detail)
378 {
379         apc_submit_generic ("voltage",    "input",   apcups_detail->linev);
380         apc_submit_generic ("voltage",    "output",  apcups_detail->outputv);
381         apc_submit_generic ("voltage",    "battery", apcups_detail->battv);
382         apc_submit_generic ("charge",     "",        apcups_detail->bcharge);
383         apc_submit_generic ("percent",    "load",    apcups_detail->loadpct);
384         apc_submit_generic ("timeleft",   "",        apcups_detail->timeleft);
385         apc_submit_generic ("temperature", "",       apcups_detail->itemp);
386         apc_submit_generic ("frequency",  "input",   apcups_detail->linefreq);
387 }
388
389 static int apcups_read (void)
390 {
391         struct apc_detail_s apcups_detail;
392         int status;
393
394         apcups_detail.linev    =   -1.0;
395         apcups_detail.outputv  =   -1.0;
396         apcups_detail.battv    =   -1.0;
397         apcups_detail.loadpct  =   -1.0;
398         apcups_detail.bcharge  =   -1.0;
399         apcups_detail.timeleft =   -1.0;
400         apcups_detail.itemp    = -300.0;
401         apcups_detail.linefreq =   -1.0;
402   
403         status = apc_query_server (conf_host == NULL
404                         ? APCUPS_DEFAULT_HOST
405                         : conf_host,
406                         conf_port, &apcups_detail);
407  
408         /*
409          * if we did not connect then do not bother submitting
410          * zeros. We want rrd files to have NAN.
411          */
412         if (status != 0)
413         {
414                 DEBUG ("apc_query_server (%s, %i) = %i",
415                                 conf_host == NULL
416                                 ? APCUPS_DEFAULT_HOST
417                                 : conf_host,
418                                 conf_port, status);
419                 return (-1);
420         }
421
422         apc_submit (&apcups_detail);
423
424         return (0);
425 } /* apcups_read */
426
427 void module_register (void)
428 {
429         plugin_register_config ("apcups", apcups_config, config_keys,
430                         config_keys_num);
431         plugin_register_read ("apcups", apcups_read);
432         plugin_register_shutdown ("apcups", apcups_shutdown);
433 } /* void module_register */