Replace all syslog-calls with one of the new logging-macros.
[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                 DEBUG ("getaddrinfo failed: %s", status == EAI_SYSTEM ? strerror (errno) : gai_strerror (status));
190                 return (-1);
191         }
192
193         /* Create socket */
194         sd = -1;
195         for (ai_list = ai_return; ai_list != NULL; ai_list = ai_list->ai_next)
196         {
197                 sd = socket (ai_list->ai_family, ai_list->ai_socktype, ai_list->ai_protocol);
198                 if (sd >= 0)
199                         break;
200         }
201         /* `ai_list' still holds the current description of the socket.. */
202
203         if (sd < 0)
204         {
205                 DEBUG ("Unable to open a socket");
206                 freeaddrinfo (ai_return);
207                 return (-1);
208         }
209
210         status = connect (sd, ai_list->ai_addr, ai_list->ai_addrlen);
211
212         freeaddrinfo (ai_return);
213
214         if (status != 0) /* `connect(2)' failed */
215         {
216                 DEBUG ("connect failed: %s", strerror (errno));
217                 close (sd);
218                 return (-1);
219         }
220
221         DEBUG ("Done opening a socket %i", sd);
222
223         return (sd);
224 } /* int net_open (char *host, char *service, int port) */
225
226 /* 
227  * Receive a message from the other end. Each message consists of
228  * two packets. The first is a header that contains the size
229  * of the data that follows in the second packet.
230  * Returns number of bytes read
231  * Returns 0 on end of file
232  * Returns -1 on hard end of file (i.e. network connection close)
233  * Returns -2 on error
234  */
235 static int net_recv (int *sockfd, char *buf, int buflen)
236 {
237         uint16_t packet_size;
238
239         /* get data size -- in short */
240         if (sread (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
241         {
242                 *sockfd = -1;
243                 return (-1);
244         }
245
246         packet_size = ntohs (packet_size);
247         if (packet_size > buflen)
248         {
249                 DEBUG ("record length too large");
250                 return (-2);
251         }
252
253         if (packet_size == 0)
254                 return (0);
255
256         /* now read the actual data */
257         if (sread (*sockfd, (void *) buf, packet_size) != 0)
258         {
259                 *sockfd = -1;
260                 return (-1);
261         }
262
263         return ((int) packet_size);
264 } /* static int net_recv (int *sockfd, char *buf, int buflen) */
265
266 /*
267  * Send a message over the network. The send consists of
268  * two network packets. The first is sends a short containing
269  * the length of the data packet which follows.
270  * Returns zero on success
271  * Returns non-zero on error
272  */
273 static int net_send (int *sockfd, char *buff, int len)
274 {
275         uint16_t packet_size;
276
277         assert (len > 0);
278         assert (*sockfd >= 0);
279
280         /* send short containing size of data packet */
281         packet_size = htons ((uint16_t) len);
282
283         if (swrite (*sockfd, (void *) &packet_size, sizeof (packet_size)) != 0)
284         {
285                 *sockfd = -1;
286                 return (-1);
287         }
288
289         /* send data packet */
290         if (swrite (*sockfd, (void *) buff, len) != 0)
291         {
292                 *sockfd = -1;
293                 return (-2);
294         }
295
296         return (0);
297 }
298
299 /* Get and print status from apcupsd NIS server */
300 static int apc_query_server (char *host, int port,
301                 struct apc_detail_s *apcups_detail)
302 {
303         int     n;
304         char    recvline[1024];
305         char   *tokptr;
306         char   *toksaveptr;
307         char   *key;
308         double  value;
309
310         static complain_t compl;
311
312 #if APCMAIN
313 # define PRINT_VALUE(name, val) printf("  Found property: name = %s; value = %f;\n", name, val)
314 #else
315 # define PRINT_VALUE(name, val) /**/
316 #endif
317
318         if (global_sockfd < 0)
319         {
320                 if ((global_sockfd = net_open (host, NULL, port)) < 0)
321                 {
322                         plugin_complain (LOG_ERR, &compl, "apcups plugin: "
323                                         "Connecting to the apcupsd failed.");
324                         return (-1);
325                 }
326                 else
327                 {
328                         plugin_relief (LOG_NOTICE, &compl, "apcups plugin: "
329                                         "Connection re-established to the apcupsd.");
330                 }
331         }
332
333         if (net_send (&global_sockfd, "status", 6) < 0)
334         {
335                 ERROR ("apcups plugin: Writing to the socket failed.");
336                 return (-1);
337         }
338
339         while ((n = net_recv (&global_sockfd, recvline, sizeof (recvline) - 1)) > 0)
340         {
341                 assert (n < sizeof (recvline));
342                 recvline[n] = '\0';
343 #if APCMAIN
344                 printf ("net_recv = `%s';\n", recvline);
345 #endif /* if APCMAIN */
346
347                 toksaveptr = NULL;
348                 tokptr = strtok_r (recvline, " :\t", &toksaveptr);
349                 while (tokptr != NULL)
350                 {
351                         key = tokptr;
352                         if ((tokptr = strtok_r (NULL, " :\t", &toksaveptr)) == NULL)
353                                 continue;
354                         value = atof (tokptr);
355
356                         PRINT_VALUE (key, value);
357
358                         if (strcmp ("LINEV", key) == 0)
359                                 apcups_detail->linev = value;
360                         else if (strcmp ("BATTV", key) == 0) 
361                                 apcups_detail->battv = value;
362                         else if (strcmp ("ITEMP", key) == 0)
363                                 apcups_detail->itemp = value;
364                         else if (strcmp ("LOADPCT", key) == 0)
365                                 apcups_detail->loadpct = value;
366                         else if (strcmp ("BCHARGE", key) == 0)
367                                 apcups_detail->bcharge = value;
368                         else if (strcmp ("OUTPUTV", key) == 0)
369                                 apcups_detail->outputv = value;
370                         else if (strcmp ("LINEFREQ", key) == 0)
371                                 apcups_detail->linefreq = value;
372                         else if (strcmp ("TIMELEFT", key) == 0)
373                                 apcups_detail->timeleft = value;
374
375                         tokptr = strtok_r (NULL, ":", &toksaveptr);
376                 } /* while (tokptr != NULL) */
377         }
378         
379         if (n < 0)
380         {
381                 WARNING ("apcups plugin: Error reading from socket");
382                 return (-1);
383         }
384
385         return (0);
386 }
387
388 static int apcups_config (const char *key, const char *value)
389 {
390         if (strcasecmp (key, "host") == 0)
391         {
392                 if (conf_host != NULL)
393                 {
394                         free (conf_host);
395                         conf_host = NULL;
396                 }
397                 if ((conf_host = strdup (value)) == NULL)
398                         return (1);
399         }
400         else if (strcasecmp (key, "Port") == 0)
401         {
402                 int port_tmp = atoi (value);
403                 if (port_tmp < 1 || port_tmp > 65535)
404                 {
405                         WARNING ("apcups plugin: Invalid port: %i", port_tmp);
406                         return (1);
407                 }
408                 conf_port = port_tmp;
409         }
410         else
411         {
412                 return (-1);
413         }
414         return (0);
415 }
416
417 static void apc_submit_generic (char *type, char *type_inst, double value)
418 {
419         value_t values[1];
420         value_list_t vl = VALUE_LIST_INIT;
421
422         values[0].gauge = value;
423
424         vl.values = values;
425         vl.values_len = 1;
426         vl.time = time (NULL);
427         strcpy (vl.host, hostname_g);
428         strcpy (vl.plugin, "apcups");
429         strcpy (vl.plugin_instance, "");
430         strncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
431
432         plugin_dispatch_values (type, &vl);
433 }
434
435 static void apc_submit (struct apc_detail_s *apcups_detail)
436 {
437         apc_submit_generic ("apcups_voltage",    "input",   apcups_detail->linev);
438         apc_submit_generic ("apcups_voltage",    "output",  apcups_detail->outputv);
439         apc_submit_generic ("apcups_voltage",    "battery", apcups_detail->battv);
440         apc_submit_generic ("apcups_charge",     "",        apcups_detail->bcharge);
441         apc_submit_generic ("apcups_charge_pct", "",        apcups_detail->loadpct);
442         apc_submit_generic ("apcups_timeleft",   "",        apcups_detail->timeleft);
443         apc_submit_generic ("apcups_temp",       "",        apcups_detail->itemp);
444         apc_submit_generic ("apcups_frequency",  "input",   apcups_detail->linefreq);
445 }
446
447 static int apcups_read (void)
448 {
449         struct apc_detail_s apcups_detail;
450         int status;
451
452         apcups_detail.linev    =   -1.0;
453         apcups_detail.outputv  =   -1.0;
454         apcups_detail.battv    =   -1.0;
455         apcups_detail.loadpct  =   -1.0;
456         apcups_detail.bcharge  =   -1.0;
457         apcups_detail.timeleft =   -1.0;
458         apcups_detail.itemp    = -300.0;
459         apcups_detail.linefreq =   -1.0;
460   
461         status = apc_query_server (conf_host == NULL
462                         ? APCUPS_DEFAULT_HOST
463                         : conf_host,
464                         conf_port, &apcups_detail);
465  
466         /*
467          * if we did not connect then do not bother submitting
468          * zeros. We want rrd files to have NAN.
469          */
470         if (status != 0)
471         {
472                 DEBUG ("apc_query_server (%s, %i) = %i",
473                                 conf_host == NULL
474                                 ? APCUPS_DEFAULT_HOST
475                                 : conf_host,
476                                 conf_port, status);
477                 return (-1);
478         }
479
480         apc_submit (&apcups_detail);
481
482         return (0);
483 } /* apcups_read */
484
485 void module_register (void)
486 {
487         plugin_register_data_set (&ds_voltage);
488         plugin_register_data_set (&ds_percent);
489         plugin_register_data_set (&ds_timeleft);
490         plugin_register_data_set (&ds_temperature);
491         plugin_register_data_set (&ds_frequency);
492
493         plugin_register_config ("apcups", apcups_config, config_keys, config_keys_num);
494
495         plugin_register_read ("apcups", apcups_read);
496         plugin_register_shutdown ("apcups", apcups_shutdown);
497 }