Use the same IPv6/IPv4 as for the client as Florian did for the server -- kevin brintnall
[rrdtool.git] / src / rrd_client.c
1 /**
2  * RRDTool - src/rrd_client.c
3  * Copyright (C) 2008 Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 #include "rrd.h"
23 #include "rrd_client.h"
24 #include "rrd_tool.h"
25
26 #include <stdlib.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <assert.h>
30 #include <pthread.h>
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <sys/un.h>
34 #include <netdb.h>
35
36 #ifndef ENODATA
37 #define ENODATA ENOENT
38 #endif
39
40 struct rrdc_response_s
41 {
42   int status;
43   char *message;
44   char **lines;
45   size_t lines_num;
46 };
47 typedef struct rrdc_response_s rrdc_response_t;
48
49 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
50 static int sd = -1;
51 static FILE *sh = NULL;
52 static char *sd_path = NULL; /* cache the path for sd */
53
54 /* One must hold `lock' when calling `close_connection'. */
55 static void close_connection (void) /* {{{ */
56 {
57   if (sh != NULL)
58   {
59     fclose (sh);
60     sh = NULL;
61     sd = -1;
62   }
63   else if (sd >= 0)
64   {
65     close (sd);
66     sd = -1;
67   }
68
69   if (sd_path != NULL)
70     free (sd_path);
71   sd_path = NULL;
72 } /* }}} void close_connection */
73
74 static int buffer_add_string (const char *str, /* {{{ */
75     char **buffer_ret, size_t *buffer_size_ret)
76 {
77   char *buffer;
78   size_t buffer_size;
79   size_t buffer_pos;
80   size_t i;
81   int status;
82
83   buffer = *buffer_ret;
84   buffer_size = *buffer_size_ret;
85   buffer_pos = 0;
86
87   i = 0;
88   status = -1;
89   while (buffer_pos < buffer_size)
90   {
91     if (str[i] == 0)
92     {
93       buffer[buffer_pos] = ' ';
94       buffer_pos++;
95       status = 0;
96       break;
97     }
98     else if ((str[i] == ' ') || (str[i] == '\\'))
99     {
100       if (buffer_pos >= (buffer_size - 1))
101         break;
102       buffer[buffer_pos] = '\\';
103       buffer_pos++;
104       buffer[buffer_pos] = str[i];
105       buffer_pos++;
106     }
107     else
108     {
109       buffer[buffer_pos] = str[i];
110       buffer_pos++;
111     }
112     i++;
113   } /* while (buffer_pos < buffer_size) */
114
115   if (status != 0)
116     return (-1);
117
118   *buffer_ret = buffer + buffer_pos;
119   *buffer_size_ret = buffer_size - buffer_pos;
120
121   return (0);
122 } /* }}} int buffer_add_string */
123
124 static int buffer_add_value (const char *value, /* {{{ */
125     char **buffer_ret, size_t *buffer_size_ret)
126 {
127   char temp[4096];
128
129   if (strncmp (value, "N:", 2) == 0)
130     snprintf (temp, sizeof (temp), "%lu:%s",
131         (unsigned long) time (NULL), value + 2);
132   else
133     strncpy (temp, value, sizeof (temp));
134   temp[sizeof (temp) - 1] = 0;
135
136   return (buffer_add_string (temp, buffer_ret, buffer_size_ret));
137 } /* }}} int buffer_add_value */
138
139 /* Remove trailing newline (NL) and carriage return (CR) characters. Similar to
140  * the Perl function `chomp'. Returns the number of characters that have been
141  * removed. */
142 static int chomp (char *str) /* {{{ */
143 {
144   size_t len;
145   int removed;
146
147   if (str == NULL)
148     return (-1);
149
150   len = strlen (str);
151   removed = 0;
152   while ((len > 0) && ((str[len - 1] == '\n') || (str[len - 1] == '\r')))
153   {
154     str[len - 1] = 0;
155     len--;
156     removed++;
157   }
158
159   return (removed);
160 } /* }}} int chomp */
161
162 static void response_free (rrdc_response_t *res) /* {{{ */
163 {
164   if (res == NULL)
165     return;
166
167   if (res->lines != NULL)
168   {
169     size_t i;
170
171     for (i = 0; i < res->lines_num; i++)
172       if (res->lines[i] != NULL)
173         free (res->lines[i]);
174     free (res->lines);
175   }
176
177   free (res);
178 } /* }}} void response_free */
179
180 static int response_read (rrdc_response_t **ret_response) /* {{{ */
181 {
182   rrdc_response_t *ret;
183
184   char buffer[4096];
185   char *buffer_ptr;
186
187   size_t i;
188
189   if (sh == NULL)
190     return (-1);
191
192   ret = (rrdc_response_t *) malloc (sizeof (rrdc_response_t));
193   if (ret == NULL)
194     return (-2);
195   memset (ret, 0, sizeof (*ret));
196   ret->lines = NULL;
197   ret->lines_num = 0;
198
199   buffer_ptr = fgets (buffer, sizeof (buffer), sh);
200   if (buffer_ptr == NULL)
201     return (-3);
202   chomp (buffer);
203
204   ret->status = strtol (buffer, &ret->message, 0);
205   if (buffer == ret->message)
206   {
207     response_free (ret);
208     return (-4);
209   }
210   /* Skip leading whitespace of the status message */
211   ret->message += strspn (ret->message, " \t");
212
213   if (ret->status <= 0)
214   {
215     *ret_response = ret;
216     return (0);
217   }
218
219   ret->lines = (char **) malloc (sizeof (char *) * ret->status);
220   if (ret->lines == NULL)
221   {
222     response_free (ret);
223     return (-5);
224   }
225   memset (ret->lines, 0, sizeof (char *) * ret->status);
226   ret->lines_num = (size_t) ret->status;
227
228   for (i = 0; i < ret->lines_num; i++)
229   {
230     buffer_ptr = fgets (buffer, sizeof (buffer), sh);
231     if (buffer_ptr == NULL)
232     {
233       response_free (ret);
234       return (-6);
235     }
236     chomp (buffer);
237
238     ret->lines[i] = strdup (buffer);
239     if (ret->lines[i] == NULL)
240     {
241       response_free (ret);
242       return (-7);
243     }
244   }
245
246   *ret_response = ret;
247   return (0);
248 } /* }}} rrdc_response_t *response_read */
249
250 static int request (const char *buffer, size_t buffer_size, /* {{{ */
251     rrdc_response_t **ret_response)
252 {
253   int status;
254   rrdc_response_t *res;
255
256   pthread_mutex_lock (&lock);
257
258   if (sh == NULL)
259   {
260     pthread_mutex_unlock (&lock);
261     return (ENOTCONN);
262   }
263
264   status = (int) fwrite (buffer, buffer_size, /* nmemb = */ 1, sh);
265   if (status != 1)
266   {
267     close_connection ();
268     pthread_mutex_unlock (&lock);
269     return (-1);
270   }
271   fflush (sh);
272
273   res = NULL;
274   status = response_read (&res);
275
276   pthread_mutex_unlock (&lock);
277
278   if (status != 0)
279     return (status);
280
281   *ret_response = res;
282   return (0);
283 } /* }}} int request */
284
285 /* determine whether we are connected to the specified daemon_addr if
286  * NULL, return whether we are connected at all
287  */
288 int rrdc_is_connected(const char *daemon_addr) /* {{{ */
289 {
290   if (sd < 0)
291     return 0;
292   else if (daemon_addr == NULL)
293   {
294     /* here we have to handle the case i.e.
295      *   UPDATE --daemon ...; UPDATEV (no --daemon) ...
296      * In other words: we have a cached connection,
297      * but it is not specified in the current command.
298      * Daemon is only implied in this case if set in ENV
299      */
300     if (getenv(ENV_RRDCACHED_ADDRESS) != NULL)
301       return 1;
302     else
303       return 0;
304   }
305   else if (strcmp(daemon_addr, sd_path) == 0)
306     return 1;
307   else
308     return 0;
309
310 } /* }}} int rrdc_is_connected */
311
312 static int rrdc_connect_unix (const char *path) /* {{{ */
313 {
314   struct sockaddr_un sa;
315   int status;
316
317   assert (path != NULL);
318   assert (sd == -1);
319
320   sd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
321   if (sd < 0)
322   {
323     status = errno;
324     return (status);
325   }
326
327   memset (&sa, 0, sizeof (sa));
328   sa.sun_family = AF_UNIX;
329   strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
330
331   status = connect (sd, (struct sockaddr *) &sa, sizeof (sa));
332   if (status != 0)
333   {
334     status = errno;
335     close_connection ();
336     return (status);
337   }
338
339   sh = fdopen (sd, "r+");
340   if (sh == NULL)
341   {
342     status = errno;
343     close_connection ();
344     return (status);
345   }
346
347   return (0);
348 } /* }}} int rrdc_connect_unix */
349
350 static int rrdc_connect_network (const char *addr_orig) /* {{{ */
351 {
352   struct addrinfo ai_hints;
353   struct addrinfo *ai_res;
354   struct addrinfo *ai_ptr;
355   char addr_copy[NI_MAXHOST];
356   char *addr;
357   char *port;
358
359   assert (addr_orig != NULL);
360   assert (sd == -1);
361
362   strncpy(addr_copy, addr_orig, sizeof(addr_copy));
363   addr_copy[sizeof(addr_copy) - 1] = '\0';
364   addr = addr_copy;
365
366   int status;
367   memset (&ai_hints, 0, sizeof (ai_hints));
368   ai_hints.ai_flags = 0;
369 #ifdef AI_ADDRCONFIG
370   ai_hints.ai_flags |= AI_ADDRCONFIG;
371 #endif
372   ai_hints.ai_family = AF_UNSPEC;
373   ai_hints.ai_socktype = SOCK_STREAM;
374
375   port = NULL;
376   if (*addr == '[') /* IPv6+port format */
377   {
378     /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
379     addr++;
380
381     port = strchr (addr, ']');
382     if (port == NULL)
383     {
384       rrd_set_error("malformed address: %s", addr_orig);
385       return (-1);
386     }
387     *port = 0;
388     port++;
389
390     if (*port == ':')
391       port++;
392     else if (*port == 0)
393       port = NULL;
394     else
395     {
396       rrd_set_error("garbage after address: %s", port);
397       return (-1);
398     }
399   } /* if (*addr = ']') */
400   else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
401   {
402     port = rindex(addr, ':');
403     if (port != NULL)
404     {
405       *port = 0;
406       port++;
407     }
408   }
409
410   ai_res = NULL;
411   status = getaddrinfo (addr,
412                         port == NULL ? RRDCACHED_DEFAULT_PORT : port,
413                         &ai_hints, &ai_res);
414   if (status != 0)
415     return (status);
416
417   for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
418   {
419     sd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
420     if (sd < 0)
421     {
422       status = errno;
423       sd = -1;
424       continue;
425     }
426
427     status = connect (sd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
428     if (status != 0)
429     {
430       status = errno;
431       close_connection();
432       continue;
433     }
434
435     sh = fdopen (sd, "r+");
436     if (sh == NULL)
437     {
438       status = errno;
439       close_connection ();
440       continue;
441     }
442
443     assert (status == 0);
444     break;
445   } /* for (ai_ptr) */
446
447   return (status);
448 } /* }}} int rrdc_connect_network */
449
450 int rrdc_connect (const char *addr) /* {{{ */
451 {
452   int status = 0;
453
454   if (addr == NULL)
455     addr = getenv (ENV_RRDCACHED_ADDRESS);
456
457   if (addr == NULL)
458     return 0;
459
460   pthread_mutex_lock(&lock);
461
462   if (sd >= 0 && sd_path != NULL && strcmp(addr, sd_path) == 0)
463   {
464     /* connection to the same daemon; use cached connection */
465     pthread_mutex_unlock (&lock);
466     return (0);
467   }
468   else
469   {
470     close_connection();
471   }
472
473   if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
474     status = rrdc_connect_unix (addr + strlen ("unix:"));
475   else if (addr[0] == '/')
476     status = rrdc_connect_unix (addr);
477   else
478     status = rrdc_connect_network(addr);
479
480   if (status == 0 && sd >= 0)
481     sd_path = strdup(addr);
482   else
483     rrd_set_error("Unable to connect to rrdcached: %s",
484                   (status < 0)
485                   ? "Internal error"
486                   : rrd_strerror (status));
487
488   pthread_mutex_unlock (&lock);
489   return (status);
490 } /* }}} int rrdc_connect */
491
492 int rrdc_disconnect (void) /* {{{ */
493 {
494   pthread_mutex_lock (&lock);
495
496   close_connection();
497
498   pthread_mutex_unlock (&lock);
499
500   return (0);
501 } /* }}} int rrdc_disconnect */
502
503 int rrdc_update (const char *filename, int values_num, /* {{{ */
504                 const char * const *values)
505 {
506   char buffer[4096];
507   char *buffer_ptr;
508   size_t buffer_free;
509   size_t buffer_size;
510   rrdc_response_t *res;
511   int status;
512   int i;
513
514   memset (buffer, 0, sizeof (buffer));
515   buffer_ptr = &buffer[0];
516   buffer_free = sizeof (buffer);
517
518   status = buffer_add_string ("update", &buffer_ptr, &buffer_free);
519   if (status != 0)
520     return (ENOBUFS);
521
522   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
523   if (status != 0)
524     return (ENOBUFS);
525
526   for (i = 0; i < values_num; i++)
527   {
528     status = buffer_add_value (values[i], &buffer_ptr, &buffer_free);
529     if (status != 0)
530       return (ENOBUFS);
531   }
532
533   assert (buffer_free < sizeof (buffer));
534   buffer_size = sizeof (buffer) - buffer_free;
535   assert (buffer[buffer_size - 1] == ' ');
536   buffer[buffer_size - 1] = '\n';
537
538   res = NULL;
539   status = request (buffer, buffer_size, &res);
540   if (status != 0)
541     return (status);
542
543   status = res->status;
544   response_free (res);
545
546   return (status);
547 } /* }}} int rrdc_update */
548
549 int rrdc_flush (const char *filename) /* {{{ */
550 {
551   char buffer[4096];
552   char *buffer_ptr;
553   size_t buffer_free;
554   size_t buffer_size;
555   rrdc_response_t *res;
556   int status;
557
558   if (filename == NULL)
559     return (-1);
560
561   memset (buffer, 0, sizeof (buffer));
562   buffer_ptr = &buffer[0];
563   buffer_free = sizeof (buffer);
564
565   status = buffer_add_string ("flush", &buffer_ptr, &buffer_free);
566   if (status != 0)
567     return (ENOBUFS);
568
569   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
570   if (status != 0)
571     return (ENOBUFS);
572
573   assert (buffer_free < sizeof (buffer));
574   buffer_size = sizeof (buffer) - buffer_free;
575   assert (buffer[buffer_size - 1] == ' ');
576   buffer[buffer_size - 1] = '\n';
577
578   res = NULL;
579   status = request (buffer, buffer_size, &res);
580   if (status != 0)
581     return (status);
582
583   status = res->status;
584   response_free (res);
585
586   return (status);
587 } /* }}} int rrdc_flush */
588
589
590 /* convenience function; if there is a daemon specified, or if we can
591  * detect one from the environment, then flush the file.  Otherwise, no-op
592  */
593 int rrdc_flush_if_daemon (const char *opt_daemon, const char *filename) /* {{{ */
594 {
595   int status = 0;
596
597   rrdc_connect(opt_daemon);
598
599   if (rrdc_is_connected(opt_daemon))
600   {
601     status = rrdc_flush (filename);
602     if (status != 0)
603     {
604       rrd_set_error ("rrdc_flush (%s) failed with status %i.",
605                      filename, status);
606     }
607   } /* if (daemon_addr) */
608
609   return status;
610 } /* }}} int rrdc_flush_if_daemon */
611
612
613 int rrdc_stats_get (rrdc_stats_t **ret_stats) /* {{{ */
614 {
615   rrdc_stats_t *head;
616   rrdc_stats_t *tail;
617
618   rrdc_response_t *res;
619
620   int status;
621   size_t i;
622
623   /* Protocol example: {{{
624    * ->  STATS
625    * <-  5 Statistics follow
626    * <-  QueueLength: 0
627    * <-  UpdatesWritten: 0
628    * <-  DataSetsWritten: 0
629    * <-  TreeNodesNumber: 0
630    * <-  TreeDepth: 0
631    * }}} */
632
633   res = NULL;
634   status = request ("STATS\n", strlen ("STATS\n"), &res);
635   if (status != 0)
636     return (status);
637
638   if (res->status <= 0)
639   {
640     response_free (res);
641     return (EIO);
642   }
643
644   head = NULL;
645   tail = NULL;
646   for (i = 0; i < res->lines_num; i++)
647   {
648     char *key;
649     char *value;
650     char *endptr;
651     rrdc_stats_t *s;
652
653     key = res->lines[i];
654     value = strchr (key, ':');
655     if (value == NULL)
656       continue;
657     *value = 0;
658     value++;
659
660     while ((value[0] == ' ') || (value[0] == '\t'))
661       value++;
662
663     s = (rrdc_stats_t *) malloc (sizeof (rrdc_stats_t));
664     if (s == NULL)
665       continue;
666     memset (s, 0, sizeof (*s));
667
668     s->name = strdup (key);
669
670     endptr = NULL;
671     if ((strcmp ("QueueLength", key) == 0)
672         || (strcmp ("TreeDepth", key) == 0)
673         || (strcmp ("TreeNodesNumber", key) == 0))
674     {
675       s->type = RRDC_STATS_TYPE_GAUGE;
676       s->value.gauge = strtod (value, &endptr);
677     }
678     else if ((strcmp ("DataSetsWritten", key) == 0)
679         || (strcmp ("FlushesReceived", key) == 0)
680         || (strcmp ("JournalBytes", key) == 0)
681         || (strcmp ("JournalRotate", key) == 0)
682         || (strcmp ("UpdatesReceived", key) == 0)
683         || (strcmp ("UpdatesWritten", key) == 0))
684     {
685       s->type = RRDC_STATS_TYPE_COUNTER;
686       s->value.counter = (uint64_t) strtoll (value, &endptr, /* base = */ 0);
687     }
688     else
689     {
690       free (s);
691       continue;
692     }
693
694     /* Conversion failed */
695     if (endptr == value)
696     {
697       free (s);
698       continue;
699     }
700
701     if (head == NULL)
702     {
703       head = s;
704       tail = s;
705       s->next = NULL;
706     }
707     else
708     {
709       tail->next = s;
710       tail = s;
711     }
712   } /* for (i = 0; i < res->lines_num; i++) */
713
714   response_free (res);
715
716   if (head == NULL)
717     return (EPROTO);
718
719   *ret_stats = head;
720   return (0);
721 } /* }}} int rrdc_stats_get */
722
723 void rrdc_stats_free (rrdc_stats_t *ret_stats) /* {{{ */
724 {
725   rrdc_stats_t *this;
726
727   this = ret_stats;
728   while (this != NULL)
729   {
730     rrdc_stats_t *next;
731
732     next = this->next;
733
734     if (this->name != NULL)
735     {
736       free (this->name);
737       this->name = NULL;
738     }
739     free (this);
740
741     this = next;
742   } /* while (this != NULL) */
743 } /* }}} void rrdc_stats_free */
744
745 /*
746  * vim: set sw=2 sts=2 ts=8 et fdm=marker :
747  */