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