Add a "FETCH" command to RRDCacheD which behaves like a (simplified
[rrdtool.git] / src / rrd_client.c
1 /**
2  * RRDTool - src/rrd_client.c
3  * Copyright (C) 2008-2010  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  *   Sebastian tokkee Harl <sh at tokkee.org>
21  **/
22
23 #include "rrd.h"
24 #include "rrd_tool.h"
25 #include "rrd_client.h"
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <strings.h>
31 #include <errno.h>
32 #include <assert.h>
33 #include <pthread.h>
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <sys/un.h>
37 #include <netdb.h>
38 #include <limits.h>
39
40 #ifndef ENODATA
41 #define ENODATA ENOENT
42 #endif
43
44 struct rrdc_response_s
45 {
46   int status;
47   char *message;
48   char **lines;
49   size_t lines_num;
50 };
51 typedef struct rrdc_response_s rrdc_response_t;
52
53 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
54 static int sd = -1;
55 static FILE *sh = NULL;
56 static char *sd_path = NULL; /* cache the path for sd */
57
58 /* get_path: Return a path name appropriate to be sent to the daemon.
59  *
60  * When talking to a local daemon (thru a UNIX socket), relative path names
61  * are resolved to absolute path names to allow for transparent integration
62  * into existing solutions (as requested by Tobi). Else, absolute path names
63  * are not allowed, since path name translation is done by the server.
64  *
65  * One must hold `lock' when calling this function. */
66 static const char *get_path (const char *path, char *resolved_path) /* {{{ */
67 {
68   const char *ret = path;
69   int is_unix = 0;
70
71   if ((*sd_path == '/')
72       || (strncmp ("unix:", sd_path, strlen ("unix:")) == 0))
73     is_unix = 1;
74
75   if (*path == '/') /* absolute path */
76   {
77     if (! is_unix)
78     {
79       rrd_set_error ("absolute path names not allowed when talking "
80           "to a remote daemon");
81       return (NULL);
82     }
83     /* else: nothing to do */
84   }
85   else /* relative path */
86   {
87     if (is_unix)
88     {
89       realpath (path, resolved_path);
90       ret = resolved_path;
91     }
92     /* else: nothing to do */
93   }
94   return (ret);
95 } /* }}} char *get_path */
96
97 static size_t strsplit (char *string, char **fields, size_t size) /* {{{ */
98 {
99   size_t i;
100   char *ptr;
101   char *saveptr;
102
103   i = 0;
104   ptr = string;
105   saveptr = NULL;
106   while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
107   {
108     ptr = NULL;
109     i++;
110
111     if (i >= size)
112       break;
113   }
114
115   return (i);
116 } /* }}} size_t strsplit */
117
118 static int parse_header (char *line, /* {{{ */
119     char **ret_key, char **ret_value)
120 {
121   char *tmp;
122
123   *ret_key = line;
124
125   tmp = strchr (line, ':');
126   if (tmp == NULL)
127     return (-1);
128
129   do
130   {
131     *tmp = 0;
132     tmp++;
133   }
134   while ((tmp[0] == ' ') || (tmp[0] == '\t'));
135
136   if (*tmp == 0)
137     return (-1);
138
139   *ret_value = tmp;
140   return (0);
141 } /* }}} int parse_header */
142
143 static int parse_ulong_header (char *line, /* {{{ */
144     char **ret_key, unsigned long *ret_value)
145 {
146   char *str_value;
147   char *endptr;
148   int status;
149
150   str_value = NULL;
151   status = parse_header (line, ret_key, &str_value);
152   if (status != 0)
153     return (status);
154
155   endptr = NULL;
156   errno = 0;
157   *ret_value = (unsigned long) strtol (str_value, &endptr, /* base = */ 0);
158   if ((endptr == str_value) || (errno != 0))
159     return (-1);
160
161   return (0);
162 } /* }}} int parse_ulong_header */
163
164 static int parse_char_array_header (char *line, /* {{{ */
165     char **ret_key, char **array, size_t array_len, int alloc)
166 {
167   char *tmp_array[array_len];
168   char *value;
169   size_t num;
170   int status;
171
172   value = NULL;
173   status = parse_header (line, ret_key, &value);
174   if (status != 0)
175     return (-1);
176
177   num = strsplit (value, tmp_array, array_len);
178   if (num != array_len)
179     return (-1);
180
181   if (alloc == 0)
182   {
183     memcpy (array, tmp_array, sizeof (tmp_array));
184   }
185   else
186   {
187     size_t i;
188
189     for (i = 0; i < array_len; i++)
190       array[i] = strdup (tmp_array[i]);
191   }
192
193   return (0);
194 } /* }}} int parse_char_array_header */
195
196 static int parse_value_array_header (char *line, /* {{{ */
197     time_t *ret_time, rrd_value_t *array, size_t array_len)
198 {
199   char *str_key;
200   char *str_array[array_len];
201   char *endptr;
202   int status;
203   size_t i;
204
205   str_key = NULL;
206   status = parse_char_array_header (line, &str_key,
207       str_array, array_len, /* alloc = */ 0);
208   if (status != 0)
209     return (-1);
210
211   errno = 0;
212   endptr = NULL;
213   *ret_time = (time_t) strtol (str_key, &endptr, /* base = */ 10);
214   if ((endptr == str_key) || (errno != 0))
215     return (-1);
216
217   for (i = 0; i < array_len; i++)
218   {
219     endptr = NULL;
220     array[i] = (rrd_value_t) strtod (str_array[i], &endptr);
221     if ((endptr == str_array[i]) || (errno != 0))
222       return (-1);
223   }
224
225   return (0);
226 } /* }}} int parse_value_array_header */
227
228 /* One must hold `lock' when calling `close_connection'. */
229 static void close_connection (void) /* {{{ */
230 {
231   if (sh != NULL)
232   {
233     fclose (sh);
234     sh = NULL;
235     sd = -1;
236   }
237   else if (sd >= 0)
238   {
239     close (sd);
240     sd = -1;
241   }
242
243   if (sd_path != NULL)
244     free (sd_path);
245   sd_path = NULL;
246 } /* }}} void close_connection */
247
248 static int buffer_add_string (const char *str, /* {{{ */
249     char **buffer_ret, size_t *buffer_size_ret)
250 {
251   char *buffer;
252   size_t buffer_size;
253   size_t buffer_pos;
254   size_t i;
255   int status;
256
257   buffer = *buffer_ret;
258   buffer_size = *buffer_size_ret;
259   buffer_pos = 0;
260
261   i = 0;
262   status = -1;
263   while (buffer_pos < buffer_size)
264   {
265     if (str[i] == 0)
266     {
267       buffer[buffer_pos] = ' ';
268       buffer_pos++;
269       status = 0;
270       break;
271     }
272     else if ((str[i] == ' ') || (str[i] == '\\'))
273     {
274       if (buffer_pos >= (buffer_size - 1))
275         break;
276       buffer[buffer_pos] = '\\';
277       buffer_pos++;
278       buffer[buffer_pos] = str[i];
279       buffer_pos++;
280     }
281     else
282     {
283       buffer[buffer_pos] = str[i];
284       buffer_pos++;
285     }
286     i++;
287   } /* while (buffer_pos < buffer_size) */
288
289   if (status != 0)
290     return (-1);
291
292   *buffer_ret = buffer + buffer_pos;
293   *buffer_size_ret = buffer_size - buffer_pos;
294
295   return (0);
296 } /* }}} int buffer_add_string */
297
298 static int buffer_add_value (const char *value, /* {{{ */
299     char **buffer_ret, size_t *buffer_size_ret)
300 {
301   char temp[4096];
302
303   if (strncmp (value, "N:", 2) == 0)
304     snprintf (temp, sizeof (temp), "%lu:%s",
305         (unsigned long) time (NULL), value + 2);
306   else
307     strncpy (temp, value, sizeof (temp));
308   temp[sizeof (temp) - 1] = 0;
309
310   return (buffer_add_string (temp, buffer_ret, buffer_size_ret));
311 } /* }}} int buffer_add_value */
312
313 /* Remove trailing newline (NL) and carriage return (CR) characters. Similar to
314  * the Perl function `chomp'. Returns the number of characters that have been
315  * removed. */
316 static int chomp (char *str) /* {{{ */
317 {
318   size_t len;
319   int removed;
320
321   if (str == NULL)
322     return (-1);
323
324   len = strlen (str);
325   removed = 0;
326   while ((len > 0) && ((str[len - 1] == '\n') || (str[len - 1] == '\r')))
327   {
328     str[len - 1] = 0;
329     len--;
330     removed++;
331   }
332
333   return (removed);
334 } /* }}} int chomp */
335
336 static void response_free (rrdc_response_t *res) /* {{{ */
337 {
338   if (res == NULL)
339     return;
340
341   if (res->lines != NULL)
342   {
343     size_t i;
344
345     for (i = 0; i < res->lines_num; i++)
346       if (res->lines[i] != NULL)
347         free (res->lines[i]);
348     free (res->lines);
349   }
350
351   free (res);
352 } /* }}} void response_free */
353
354 static int response_read (rrdc_response_t **ret_response) /* {{{ */
355 {
356   rrdc_response_t *ret;
357
358   char buffer[4096];
359   char *buffer_ptr;
360
361   size_t i;
362
363   if (sh == NULL)
364     return (-1);
365
366   ret = (rrdc_response_t *) malloc (sizeof (rrdc_response_t));
367   if (ret == NULL)
368     return (-2);
369   memset (ret, 0, sizeof (*ret));
370   ret->lines = NULL;
371   ret->lines_num = 0;
372
373   buffer_ptr = fgets (buffer, sizeof (buffer), sh);
374   if (buffer_ptr == NULL)
375     return (-3);
376   chomp (buffer);
377
378   ret->status = strtol (buffer, &ret->message, 0);
379   if (buffer == ret->message)
380   {
381     response_free (ret);
382     return (-4);
383   }
384   /* Skip leading whitespace of the status message */
385   ret->message += strspn (ret->message, " \t");
386
387   if (ret->status <= 0)
388   {
389     if (ret->status < 0)
390       rrd_set_error("rrdcached: %s", ret->message);
391     *ret_response = ret;
392     return (0);
393   }
394
395   ret->lines = (char **) malloc (sizeof (char *) * ret->status);
396   if (ret->lines == NULL)
397   {
398     response_free (ret);
399     return (-5);
400   }
401   memset (ret->lines, 0, sizeof (char *) * ret->status);
402   ret->lines_num = (size_t) ret->status;
403
404   for (i = 0; i < ret->lines_num; i++)
405   {
406     buffer_ptr = fgets (buffer, sizeof (buffer), sh);
407     if (buffer_ptr == NULL)
408     {
409       response_free (ret);
410       return (-6);
411     }
412     chomp (buffer);
413
414     ret->lines[i] = strdup (buffer);
415     if (ret->lines[i] == NULL)
416     {
417       response_free (ret);
418       return (-7);
419     }
420   }
421
422   *ret_response = ret;
423   return (0);
424 } /* }}} rrdc_response_t *response_read */
425
426 static int request (const char *buffer, size_t buffer_size, /* {{{ */
427     rrdc_response_t **ret_response)
428 {
429   int status;
430   rrdc_response_t *res;
431
432   if (sh == NULL)
433     return (ENOTCONN);
434
435   status = (int) fwrite (buffer, buffer_size, /* nmemb = */ 1, sh);
436   if (status != 1)
437   {
438     close_connection ();
439     rrd_set_error("request: socket error (%d) while talking to rrdcached",
440                   status);
441     return (-1);
442   }
443   fflush (sh);
444
445   res = NULL;
446   status = response_read (&res);
447
448   if (status != 0)
449   {
450     if (status < 0)
451       rrd_set_error("request: internal error while talking to rrdcached");
452     return (status);
453   }
454
455   *ret_response = res;
456   return (0);
457 } /* }}} int request */
458
459 /* determine whether we are connected to the specified daemon_addr if
460  * NULL, return whether we are connected at all
461  */
462 int rrdc_is_connected(const char *daemon_addr) /* {{{ */
463 {
464   if (sd < 0)
465     return 0;
466   else if (daemon_addr == NULL)
467   {
468     /* here we have to handle the case i.e.
469      *   UPDATE --daemon ...; UPDATEV (no --daemon) ...
470      * In other words: we have a cached connection,
471      * but it is not specified in the current command.
472      * Daemon is only implied in this case if set in ENV
473      */
474     if (getenv(ENV_RRDCACHED_ADDRESS) != NULL)
475       return 1;
476     else
477       return 0;
478   }
479   else if (strcmp(daemon_addr, sd_path) == 0)
480     return 1;
481   else
482     return 0;
483
484 } /* }}} int rrdc_is_connected */
485
486 static int rrdc_connect_unix (const char *path) /* {{{ */
487 {
488   struct sockaddr_un sa;
489   int status;
490
491   assert (path != NULL);
492   assert (sd == -1);
493
494   sd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
495   if (sd < 0)
496   {
497     status = errno;
498     return (status);
499   }
500
501   memset (&sa, 0, sizeof (sa));
502   sa.sun_family = AF_UNIX;
503   strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
504
505   status = connect (sd, (struct sockaddr *) &sa, sizeof (sa));
506   if (status != 0)
507   {
508     status = errno;
509     close_connection ();
510     return (status);
511   }
512
513   sh = fdopen (sd, "r+");
514   if (sh == NULL)
515   {
516     status = errno;
517     close_connection ();
518     return (status);
519   }
520
521   return (0);
522 } /* }}} int rrdc_connect_unix */
523
524 static int rrdc_connect_network (const char *addr_orig) /* {{{ */
525 {
526   struct addrinfo ai_hints;
527   struct addrinfo *ai_res;
528   struct addrinfo *ai_ptr;
529   char addr_copy[NI_MAXHOST];
530   char *addr;
531   char *port;
532
533   assert (addr_orig != NULL);
534   assert (sd == -1);
535
536   strncpy(addr_copy, addr_orig, sizeof(addr_copy));
537   addr_copy[sizeof(addr_copy) - 1] = '\0';
538   addr = addr_copy;
539
540   int status;
541   memset (&ai_hints, 0, sizeof (ai_hints));
542   ai_hints.ai_flags = 0;
543 #ifdef AI_ADDRCONFIG
544   ai_hints.ai_flags |= AI_ADDRCONFIG;
545 #endif
546   ai_hints.ai_family = AF_UNSPEC;
547   ai_hints.ai_socktype = SOCK_STREAM;
548
549   port = NULL;
550   if (*addr == '[') /* IPv6+port format */
551   {
552     /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
553     addr++;
554
555     port = strchr (addr, ']');
556     if (port == NULL)
557     {
558       rrd_set_error("malformed address: %s", addr_orig);
559       return (-1);
560     }
561     *port = 0;
562     port++;
563
564     if (*port == ':')
565       port++;
566     else if (*port == 0)
567       port = NULL;
568     else
569     {
570       rrd_set_error("garbage after address: %s", port);
571       return (-1);
572     }
573   } /* if (*addr == '[') */
574   else
575   {
576     port = rindex(addr, ':');
577     if (port != NULL)
578     {
579       *port = 0;
580       port++;
581     }
582   }
583
584   ai_res = NULL;
585   status = getaddrinfo (addr,
586                         port == NULL ? RRDCACHED_DEFAULT_PORT : port,
587                         &ai_hints, &ai_res);
588   if (status != 0)
589   {
590     rrd_set_error ("failed to resolve address `%s' (port %s): %s",
591         addr, port == NULL ? RRDCACHED_DEFAULT_PORT : port,
592         gai_strerror (status));
593     return (-1);
594   }
595
596   for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
597   {
598     sd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
599     if (sd < 0)
600     {
601       status = errno;
602       sd = -1;
603       continue;
604     }
605
606     status = connect (sd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
607     if (status != 0)
608     {
609       status = errno;
610       close_connection();
611       continue;
612     }
613
614     sh = fdopen (sd, "r+");
615     if (sh == NULL)
616     {
617       status = errno;
618       close_connection ();
619       continue;
620     }
621
622     assert (status == 0);
623     break;
624   } /* for (ai_ptr) */
625
626   return (status);
627 } /* }}} int rrdc_connect_network */
628
629 int rrdc_connect (const char *addr) /* {{{ */
630 {
631   int status = 0;
632
633   if (addr == NULL)
634     addr = getenv (ENV_RRDCACHED_ADDRESS);
635
636   if (addr == NULL)
637     return 0;
638
639   pthread_mutex_lock(&lock);
640
641   if (sd >= 0 && sd_path != NULL && strcmp(addr, sd_path) == 0)
642   {
643     /* connection to the same daemon; use cached connection */
644     pthread_mutex_unlock (&lock);
645     return (0);
646   }
647   else
648   {
649     close_connection();
650   }
651
652   rrd_clear_error ();
653   if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
654     status = rrdc_connect_unix (addr + strlen ("unix:"));
655   else if (addr[0] == '/')
656     status = rrdc_connect_unix (addr);
657   else
658     status = rrdc_connect_network(addr);
659
660   if (status == 0 && sd >= 0)
661     sd_path = strdup(addr);
662   else
663   {
664     char *err = rrd_test_error () ? rrd_get_error () : "Internal error";
665     /* err points the string that gets written to by rrd_set_error(), thus we
666      * cannot pass it to that function */
667     err = strdup (err);
668     rrd_set_error("Unable to connect to rrdcached: %s",
669                   (status < 0)
670                   ? (err ? err : "Internal error")
671                   : rrd_strerror (status));
672     if (err != NULL)
673       free (err);
674   }
675
676   pthread_mutex_unlock (&lock);
677   return (status);
678 } /* }}} int rrdc_connect */
679
680 int rrdc_disconnect (void) /* {{{ */
681 {
682   pthread_mutex_lock (&lock);
683
684   close_connection();
685
686   pthread_mutex_unlock (&lock);
687
688   return (0);
689 } /* }}} int rrdc_disconnect */
690
691 int rrdc_update (const char *filename, int values_num, /* {{{ */
692                 const char * const *values)
693 {
694   char buffer[4096];
695   char *buffer_ptr;
696   size_t buffer_free;
697   size_t buffer_size;
698   rrdc_response_t *res;
699   int status;
700   int i;
701   char file_path[PATH_MAX];
702
703   memset (buffer, 0, sizeof (buffer));
704   buffer_ptr = &buffer[0];
705   buffer_free = sizeof (buffer);
706
707   status = buffer_add_string ("update", &buffer_ptr, &buffer_free);
708   if (status != 0)
709     return (ENOBUFS);
710
711   pthread_mutex_lock (&lock);
712   filename = get_path (filename, file_path);
713   if (filename == NULL)
714   {
715     pthread_mutex_unlock (&lock);
716     return (-1);
717   }
718
719   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
720   if (status != 0)
721   {
722     pthread_mutex_unlock (&lock);
723     return (ENOBUFS);
724   }
725
726   for (i = 0; i < values_num; i++)
727   {
728     status = buffer_add_value (values[i], &buffer_ptr, &buffer_free);
729     if (status != 0)
730     {
731       pthread_mutex_unlock (&lock);
732       return (ENOBUFS);
733     }
734   }
735
736   assert (buffer_free < sizeof (buffer));
737   buffer_size = sizeof (buffer) - buffer_free;
738   assert (buffer[buffer_size - 1] == ' ');
739   buffer[buffer_size - 1] = '\n';
740
741   res = NULL;
742   status = request (buffer, buffer_size, &res);
743   pthread_mutex_unlock (&lock);
744
745   if (status != 0)
746     return (status);
747
748   status = res->status;
749   response_free (res);
750
751   return (status);
752 } /* }}} int rrdc_update */
753
754 int rrdc_flush (const char *filename) /* {{{ */
755 {
756   char buffer[4096];
757   char *buffer_ptr;
758   size_t buffer_free;
759   size_t buffer_size;
760   rrdc_response_t *res;
761   int status;
762   char file_path[PATH_MAX];
763
764   if (filename == NULL)
765     return (-1);
766
767   memset (buffer, 0, sizeof (buffer));
768   buffer_ptr = &buffer[0];
769   buffer_free = sizeof (buffer);
770
771   status = buffer_add_string ("flush", &buffer_ptr, &buffer_free);
772   if (status != 0)
773     return (ENOBUFS);
774
775   pthread_mutex_lock (&lock);
776   filename = get_path (filename, file_path);
777   if (filename == NULL)
778   {
779     pthread_mutex_unlock (&lock);
780     return (-1);
781   }
782
783   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
784   if (status != 0)
785   {
786     pthread_mutex_unlock (&lock);
787     return (ENOBUFS);
788   }
789
790   assert (buffer_free < sizeof (buffer));
791   buffer_size = sizeof (buffer) - buffer_free;
792   assert (buffer[buffer_size - 1] == ' ');
793   buffer[buffer_size - 1] = '\n';
794
795   res = NULL;
796   status = request (buffer, buffer_size, &res);
797   pthread_mutex_unlock (&lock);
798
799   if (status != 0)
800     return (status);
801
802   status = res->status;
803   response_free (res);
804
805   return (status);
806 } /* }}} int rrdc_flush */
807
808 int rrdc_fetch (const char *filename, /* {{{ */
809     const char *cf,
810     time_t *ret_start, time_t *ret_end,
811     unsigned long *ret_step,
812     unsigned long *ret_ds_num,
813     char ***ret_ds_names,
814     rrd_value_t **ret_data)
815 {
816   char buffer[4096];
817   char *buffer_ptr;
818   size_t buffer_free;
819   size_t buffer_size;
820   rrdc_response_t *res;
821   char path_buffer[PATH_MAX];
822   char *path_ptr;
823
824   char *str_tmp;
825   unsigned long flush_version;
826
827   time_t start;
828   time_t end;
829   unsigned long step;
830   unsigned long ds_num;
831   char **ds_names;
832
833   rrd_value_t *data;
834   size_t data_size;
835   size_t data_fill;
836
837   int status;
838   size_t current_line;
839   time_t t;
840
841   if ((filename == NULL) || (cf == NULL))
842     return (-1);
843
844   /* Send request {{{ */
845   memset (buffer, 0, sizeof (buffer));
846   buffer_ptr = &buffer[0];
847   buffer_free = sizeof (buffer);
848
849   status = buffer_add_string ("FETCH", &buffer_ptr, &buffer_free);
850   if (status != 0)
851     return (ENOBUFS);
852
853   /* change to path for rrdcached */
854   path_ptr = get_path (filename, path_buffer);
855   if (path_ptr == NULL)
856     return (EINVAL);
857
858   status = buffer_add_string (path_ptr, &buffer_ptr, &buffer_free);
859   if (status != 0)
860     return (ENOBUFS);
861
862   status = buffer_add_string (cf, &buffer_ptr, &buffer_free);
863   if (status != 0)
864     return (ENOBUFS);
865
866   if ((ret_start != NULL) && (*ret_start > 0))
867   {
868     char tmp[64];
869     snprintf (tmp, sizeof (tmp), "%lu", (unsigned long) *ret_start);
870     tmp[sizeof (tmp) - 1] = 0;
871     status = buffer_add_string (tmp, &buffer_ptr, &buffer_free);
872     if (status != 0)
873       return (ENOBUFS);
874
875     if ((ret_end != NULL) && (*ret_end > 0))
876     {
877       snprintf (tmp, sizeof (tmp), "%lu", (unsigned long) *ret_end);
878       tmp[sizeof (tmp) - 1] = 0;
879       status = buffer_add_string (tmp, &buffer_ptr, &buffer_free);
880       if (status != 0)
881         return (ENOBUFS);
882     }
883   }
884
885   assert (buffer_free < sizeof (buffer));
886   buffer_size = sizeof (buffer) - buffer_free;
887   assert (buffer[buffer_size - 1] == ' ');
888   buffer[buffer_size - 1] = '\n';
889
890   res = NULL;
891   status = request (buffer, buffer_size, &res);
892   if (status != 0)
893     return (status);
894
895   status = res->status;
896   if (status < 0)
897   {
898     rrd_set_error ("rrdcached: %s", res->message);
899     response_free (res);
900     return (status);
901   }
902   /* }}} Send request */
903
904   ds_names = NULL;
905   ds_num = 0;
906   data = NULL;
907   current_line = 0;
908
909   /* Macros to make error handling a little easier (i. e. less to type and
910    * read. `BAIL_OUT' sets the error message, frees all dynamically allocated
911    * variables and returns the provided status code. */
912 #define BAIL_OUT(status, ...) do { \
913     rrd_set_error ("rrdc_fetch: " __VA_ARGS__); \
914     free (data); \
915     if (ds_names != 0) { size_t k; for (k = 0; k < ds_num; k++) free (ds_names[k]); } \
916     free (ds_names); \
917     response_free (res); \
918     return (status); \
919   } while (0)
920
921 #define READ_NUMERIC_FIELD(name,type,var) do { \
922     char *key; \
923     unsigned long value; \
924     assert (current_line < res->lines_num); \
925     status = parse_ulong_header (res->lines[current_line], &key, &value); \
926     if (status != 0) \
927       BAIL_OUT (-1, "Unable to parse header `%s'", name); \
928     if (strcasecmp (key, name) != 0) \
929       BAIL_OUT (-1, "Unexpected header line: Expected `%s', got `%s'", name, key); \
930     var = (type) value; \
931     current_line++; \
932   } while (0)
933
934   if (res->lines_num < 1)
935     BAIL_OUT (-1, "Premature end of response packet");
936
937   /* We're making some very strong assumptions about the fields below. We
938    * therefore check the version of the `flush' command first, so that later
939    * versions can change the order of fields and it's easier to implement
940    * backwards compatibility. */
941   READ_NUMERIC_FIELD ("FlushVersion", unsigned long, flush_version);
942   if (flush_version != 1)
943     BAIL_OUT (-1, "Don't know how to handle flush format version %lu.",
944         flush_version);
945
946   if (res->lines_num < 5)
947     BAIL_OUT (-1, "Premature end of response packet");
948
949   READ_NUMERIC_FIELD ("Start", time_t, start);
950   READ_NUMERIC_FIELD ("End", time_t, end);
951   if (start >= end)
952     BAIL_OUT (-1, "Malformed start and end times: start = %lu; end = %lu;",
953         (unsigned long) start,
954         (unsigned long) end);
955
956   READ_NUMERIC_FIELD ("Step", unsigned long, step);
957   if (step < 1)
958     BAIL_OUT (-1, "Invalid number for Step: %lu", step);
959
960   READ_NUMERIC_FIELD ("DSCount", unsigned long, ds_num);
961   if (ds_num < 1)
962     BAIL_OUT (-1, "Invalid number for DSCount: %lu", ds_num);
963   
964   /* It's time to allocate some memory */
965   ds_names = calloc ((size_t) ds_num, sizeof (*ds_names));
966   if (ds_names == NULL)
967     BAIL_OUT (-1, "Out of memory");
968
969   status = parse_char_array_header (res->lines[current_line],
970       &str_tmp, ds_names, (size_t) ds_num, /* alloc = */ 1);
971   if (status != 0)
972     BAIL_OUT (-1, "Unable to parse header `DSName'");
973   if (strcasecmp ("DSName", str_tmp) != 0)
974     BAIL_OUT (-1, "Unexpected header line: Expected `DSName', got `%s'", str_tmp);
975   current_line++;
976
977   data_size = ds_num * (end - start) / step;
978   if (data_size < 1)
979     BAIL_OUT (-1, "No data returned or headers invalid.");
980
981   if (res->lines_num != (6 + (data_size / ds_num)))
982     BAIL_OUT (-1, "Got %zu lines, expected %zu",
983         res->lines_num, (6 + (data_size / ds_num)));
984
985   data = calloc (data_size, sizeof (*data));
986   if (data == NULL)
987     BAIL_OUT (-1, "Out of memory");
988   
989
990   data_fill = 0;
991   for (t = start + step; t <= end; t += step, current_line++)
992   {
993     time_t tmp;
994
995     assert (current_line < res->lines_num);
996
997     status = parse_value_array_header (res->lines[current_line],
998         &tmp, data + data_fill, (size_t) ds_num);
999     if (status != 0)
1000       BAIL_OUT (-1, "Cannot parse value line");
1001
1002     data_fill += (size_t) ds_num;
1003   }
1004
1005   *ret_start = start;
1006   *ret_end = end;
1007   *ret_step = step;
1008   *ret_ds_num = ds_num;
1009   *ret_ds_names = ds_names;
1010   *ret_data = data;
1011
1012   response_free (res);
1013   return (0);
1014 #undef READ_NUMERIC_FIELD
1015 #undef BAIL_OUT
1016 } /* }}} int rrdc_flush */
1017
1018 /* convenience function; if there is a daemon specified, or if we can
1019  * detect one from the environment, then flush the file.  Otherwise, no-op
1020  */
1021 int rrdc_flush_if_daemon (const char *opt_daemon, const char *filename) /* {{{ */
1022 {
1023   int status = 0;
1024
1025   rrdc_connect(opt_daemon);
1026
1027   if (rrdc_is_connected(opt_daemon))
1028   {
1029     rrd_clear_error();
1030     status = rrdc_flush (filename);
1031
1032     if (status != 0 && !rrd_test_error())
1033     {
1034       if (status > 0)
1035       {
1036         rrd_set_error("rrdc_flush (%s) failed: %s",
1037                       filename, rrd_strerror(status));
1038       }
1039       else if (status < 0)
1040       {
1041         rrd_set_error("rrdc_flush (%s) failed with status %i.",
1042                       filename, status);
1043       }
1044     }
1045   } /* if (rrdc_is_connected(..)) */
1046
1047   return status;
1048 } /* }}} int rrdc_flush_if_daemon */
1049
1050
1051 int rrdc_stats_get (rrdc_stats_t **ret_stats) /* {{{ */
1052 {
1053   rrdc_stats_t *head;
1054   rrdc_stats_t *tail;
1055
1056   rrdc_response_t *res;
1057
1058   int status;
1059   size_t i;
1060
1061   /* Protocol example: {{{
1062    * ->  STATS
1063    * <-  5 Statistics follow
1064    * <-  QueueLength: 0
1065    * <-  UpdatesWritten: 0
1066    * <-  DataSetsWritten: 0
1067    * <-  TreeNodesNumber: 0
1068    * <-  TreeDepth: 0
1069    * }}} */
1070
1071   res = NULL;
1072   pthread_mutex_lock (&lock);
1073   status = request ("STATS\n", strlen ("STATS\n"), &res);
1074   pthread_mutex_unlock (&lock);
1075
1076   if (status != 0)
1077     return (status);
1078
1079   if (res->status <= 0)
1080   {
1081     response_free (res);
1082     return (EIO);
1083   }
1084
1085   head = NULL;
1086   tail = NULL;
1087   for (i = 0; i < res->lines_num; i++)
1088   {
1089     char *key;
1090     char *value;
1091     char *endptr;
1092     rrdc_stats_t *s;
1093
1094     key = res->lines[i];
1095     value = strchr (key, ':');
1096     if (value == NULL)
1097       continue;
1098     *value = 0;
1099     value++;
1100
1101     while ((value[0] == ' ') || (value[0] == '\t'))
1102       value++;
1103
1104     s = (rrdc_stats_t *) malloc (sizeof (rrdc_stats_t));
1105     if (s == NULL)
1106       continue;
1107     memset (s, 0, sizeof (*s));
1108
1109     s->name = strdup (key);
1110
1111     endptr = NULL;
1112     if ((strcmp ("QueueLength", key) == 0)
1113         || (strcmp ("TreeDepth", key) == 0)
1114         || (strcmp ("TreeNodesNumber", key) == 0))
1115     {
1116       s->type = RRDC_STATS_TYPE_GAUGE;
1117       s->value.gauge = strtod (value, &endptr);
1118     }
1119     else if ((strcmp ("DataSetsWritten", key) == 0)
1120         || (strcmp ("FlushesReceived", key) == 0)
1121         || (strcmp ("JournalBytes", key) == 0)
1122         || (strcmp ("JournalRotate", key) == 0)
1123         || (strcmp ("UpdatesReceived", key) == 0)
1124         || (strcmp ("UpdatesWritten", key) == 0))
1125     {
1126       s->type = RRDC_STATS_TYPE_COUNTER;
1127       s->value.counter = (uint64_t) strtoll (value, &endptr, /* base = */ 0);
1128     }
1129     else
1130     {
1131       free (s);
1132       continue;
1133     }
1134
1135     /* Conversion failed */
1136     if (endptr == value)
1137     {
1138       free (s);
1139       continue;
1140     }
1141
1142     if (head == NULL)
1143     {
1144       head = s;
1145       tail = s;
1146       s->next = NULL;
1147     }
1148     else
1149     {
1150       tail->next = s;
1151       tail = s;
1152     }
1153   } /* for (i = 0; i < res->lines_num; i++) */
1154
1155   response_free (res);
1156
1157   if (head == NULL)
1158     return (EPROTO);
1159
1160   *ret_stats = head;
1161   return (0);
1162 } /* }}} int rrdc_stats_get */
1163
1164 void rrdc_stats_free (rrdc_stats_t *ret_stats) /* {{{ */
1165 {
1166   rrdc_stats_t *this;
1167
1168   this = ret_stats;
1169   while (this != NULL)
1170   {
1171     rrdc_stats_t *next;
1172
1173     next = this->next;
1174
1175     if (this->name != NULL)
1176     {
1177       free ((char *)this->name);
1178       this->name = NULL;
1179     }
1180     free (this);
1181
1182     this = next;
1183   } /* while (this != NULL) */
1184 } /* }}} void rrdc_stats_free */
1185
1186 /*
1187  * vim: set sw=2 sts=2 ts=8 et fdm=marker :
1188  */