Summary of changes:
[rrdtool.git] / src / rrd_client.c
1 /**
2  * RRDTool - src/rrd_client.c
3  * Copyright (C) 2008-2010  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy
6  * of this software and associated documentation files (the "Software"), to
7  * deal in the Software without restriction, including without limitation the
8  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9  * sell copies of the Software, and to permit persons to whom the Software is
10  * furnished to do so, subject to the following conditions:
11  * 
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  * 
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at verplant.org>
25  *   Sebastian tokkee Harl <sh at tokkee.org>
26  **/
27
28 #include "rrd.h"
29 #include "rrd_tool.h"
30 #include "rrd_client.h"
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <strings.h>
36 #include <errno.h>
37 #include <assert.h>
38 #include <pthread.h>
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <sys/un.h>
42 #include <netdb.h>
43 #include <limits.h>
44
45 #ifndef ENODATA
46 #define ENODATA ENOENT
47 #endif
48
49 struct rrdc_response_s
50 {
51   int status;
52   char *message;
53   char **lines;
54   size_t lines_num;
55 };
56 typedef struct rrdc_response_s rrdc_response_t;
57
58 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
59 static int sd = -1;
60 static FILE *sh = NULL;
61 static char *sd_path = NULL; /* cache the path for sd */
62
63 /* get_path: Return a path name appropriate to be sent to the daemon.
64  *
65  * When talking to a local daemon (thru a UNIX socket), relative path names
66  * are resolved to absolute path names to allow for transparent integration
67  * into existing solutions (as requested by Tobi). Else, absolute path names
68  * are not allowed, since path name translation is done by the server.
69  *
70  * One must hold `lock' when calling this function. */
71 static const char *get_path (const char *path, char *resolved_path) /* {{{ */
72 {
73   const char *ret = path;
74   int is_unix = 0;
75
76   if ((path == NULL) || (resolved_path == NULL) || (sd_path == NULL))
77     return (NULL);
78
79   if ((*sd_path == '/')
80       || (strncmp ("unix:", sd_path, strlen ("unix:")) == 0))
81     is_unix = 1;
82
83   if (is_unix)
84   {
85     ret = realpath(path, resolved_path);
86     if (ret == NULL)
87       rrd_set_error("realpath(%s): %s", path, rrd_strerror(errno));
88     return ret;
89   }
90   else
91   {
92     if (*path == '/') /* not absolute path */
93     {
94       rrd_set_error ("absolute path names not allowed when talking "
95           "to a remote daemon");
96       return NULL;
97     }
98   }
99
100   return path;
101 } /* }}} char *get_path */
102
103 static size_t strsplit (char *string, char **fields, size_t size) /* {{{ */
104 {
105   size_t i;
106   char *ptr;
107   char *saveptr;
108
109   i = 0;
110   ptr = string;
111   saveptr = NULL;
112   while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
113   {
114     ptr = NULL;
115     i++;
116
117     if (i >= size)
118       break;
119   }
120
121   return (i);
122 } /* }}} size_t strsplit */
123
124 static int parse_header (char *line, /* {{{ */
125     char **ret_key, char **ret_value)
126 {
127   char *tmp;
128
129   *ret_key = line;
130
131   tmp = strchr (line, ':');
132   if (tmp == NULL)
133     return (-1);
134
135   do
136   {
137     *tmp = 0;
138     tmp++;
139   }
140   while ((tmp[0] == ' ') || (tmp[0] == '\t'));
141
142   if (*tmp == 0)
143     return (-1);
144
145   *ret_value = tmp;
146   return (0);
147 } /* }}} int parse_header */
148
149 static int parse_ulong_header (char *line, /* {{{ */
150     char **ret_key, unsigned long *ret_value)
151 {
152   char *str_value;
153   char *endptr;
154   int status;
155
156   str_value = NULL;
157   status = parse_header (line, ret_key, &str_value);
158   if (status != 0)
159     return (status);
160
161   endptr = NULL;
162   errno = 0;
163   *ret_value = (unsigned long) strtol (str_value, &endptr, /* base = */ 0);
164   if ((endptr == str_value) || (errno != 0))
165     return (-1);
166
167   return (0);
168 } /* }}} int parse_ulong_header */
169
170 static int parse_char_array_header (char *line, /* {{{ */
171     char **ret_key, char **array, size_t array_len, int alloc)
172 {
173   char *tmp_array[array_len];
174   char *value;
175   size_t num;
176   int status;
177
178   value = NULL;
179   status = parse_header (line, ret_key, &value);
180   if (status != 0)
181     return (-1);
182
183   num = strsplit (value, tmp_array, array_len);
184   if (num != array_len)
185     return (-1);
186
187   if (alloc == 0)
188   {
189     memcpy (array, tmp_array, sizeof (tmp_array));
190   }
191   else
192   {
193     size_t i;
194
195     for (i = 0; i < array_len; i++)
196       array[i] = strdup (tmp_array[i]);
197   }
198
199   return (0);
200 } /* }}} int parse_char_array_header */
201
202 static int parse_value_array_header (char *line, /* {{{ */
203     time_t *ret_time, rrd_value_t *array, size_t array_len)
204 {
205   char *str_key;
206   char *str_array[array_len];
207   char *endptr;
208   int status;
209   size_t i;
210
211   str_key = NULL;
212   status = parse_char_array_header (line, &str_key,
213       str_array, array_len, /* alloc = */ 0);
214   if (status != 0)
215     return (-1);
216
217   errno = 0;
218   endptr = NULL;
219   *ret_time = (time_t) strtol (str_key, &endptr, /* base = */ 10);
220   if ((endptr == str_key) || (errno != 0))
221     return (-1);
222
223   for (i = 0; i < array_len; i++)
224   {
225     endptr = NULL;
226     array[i] = (rrd_value_t) strtod (str_array[i], &endptr);
227     if ((endptr == str_array[i]) || (errno != 0))
228       return (-1);
229   }
230
231   return (0);
232 } /* }}} int parse_value_array_header */
233
234 /* One must hold `lock' when calling `close_connection'. */
235 static void close_connection (void) /* {{{ */
236 {
237   if (sh != NULL)
238   {
239     fclose (sh);
240     sh = NULL;
241     sd = -1;
242   }
243   else if (sd >= 0)
244   {
245     close (sd);
246     sd = -1;
247   }
248
249   if (sd_path != NULL)
250     free (sd_path);
251   sd_path = NULL;
252 } /* }}} void close_connection */
253
254 static int buffer_add_string (const char *str, /* {{{ */
255     char **buffer_ret, size_t *buffer_size_ret)
256 {
257   char *buffer;
258   size_t buffer_size;
259   size_t buffer_pos;
260   size_t i;
261   int status;
262
263   buffer = *buffer_ret;
264   buffer_size = *buffer_size_ret;
265   buffer_pos = 0;
266
267   i = 0;
268   status = -1;
269   while (buffer_pos < buffer_size)
270   {
271     if (str[i] == 0)
272     {
273       buffer[buffer_pos] = ' ';
274       buffer_pos++;
275       status = 0;
276       break;
277     }
278     else if ((str[i] == ' ') || (str[i] == '\\'))
279     {
280       if (buffer_pos >= (buffer_size - 1))
281         break;
282       buffer[buffer_pos] = '\\';
283       buffer_pos++;
284       buffer[buffer_pos] = str[i];
285       buffer_pos++;
286     }
287     else
288     {
289       buffer[buffer_pos] = str[i];
290       buffer_pos++;
291     }
292     i++;
293   } /* while (buffer_pos < buffer_size) */
294
295   if (status != 0)
296     return (-1);
297
298   *buffer_ret = buffer + buffer_pos;
299   *buffer_size_ret = buffer_size - buffer_pos;
300
301   return (0);
302 } /* }}} int buffer_add_string */
303
304 static int buffer_add_value (const char *value, /* {{{ */
305     char **buffer_ret, size_t *buffer_size_ret)
306 {
307   char temp[4096];
308
309   if (strncmp (value, "N:", 2) == 0)
310     snprintf (temp, sizeof (temp), "%lu:%s",
311         (unsigned long) time (NULL), value + 2);
312   else
313     strncpy (temp, value, sizeof (temp));
314   temp[sizeof (temp) - 1] = 0;
315
316   return (buffer_add_string (temp, buffer_ret, buffer_size_ret));
317 } /* }}} int buffer_add_value */
318
319 static int buffer_add_ulong (const unsigned long value, /* {{{ */
320     char **buffer_ret, size_t *buffer_size_ret)
321 {
322   char temp[4096];
323
324   snprintf (temp, sizeof (temp), "%lu", value);
325   temp[sizeof (temp) - 1] = 0;
326   return (buffer_add_string (temp, buffer_ret, buffer_size_ret));
327 } /* }}} int buffer_add_ulong */
328
329 /* Remove trailing newline (NL) and carriage return (CR) characters. Similar to
330  * the Perl function `chomp'. Returns the number of characters that have been
331  * removed. */
332 static int chomp (char *str) /* {{{ */
333 {
334   size_t len;
335   int removed;
336
337   if (str == NULL)
338     return (-1);
339
340   len = strlen (str);
341   removed = 0;
342   while ((len > 0) && ((str[len - 1] == '\n') || (str[len - 1] == '\r')))
343   {
344     str[len - 1] = 0;
345     len--;
346     removed++;
347   }
348
349   return (removed);
350 } /* }}} int chomp */
351
352 static void response_free (rrdc_response_t *res) /* {{{ */
353 {
354   if (res == NULL)
355     return;
356
357   if (res->lines != NULL)
358   {
359     size_t i;
360
361     for (i = 0; i < res->lines_num; i++)
362       if (res->lines[i] != NULL)
363         free (res->lines[i]);
364     free (res->lines);
365   }
366
367   free (res);
368 } /* }}} void response_free */
369
370 static int response_read (rrdc_response_t **ret_response) /* {{{ */
371 {
372   rrdc_response_t *ret;
373
374   char buffer[4096];
375   char *buffer_ptr;
376
377   size_t i;
378
379   if (sh == NULL)
380     return (-1);
381
382   ret = (rrdc_response_t *) malloc (sizeof (rrdc_response_t));
383   if (ret == NULL)
384     return (-2);
385   memset (ret, 0, sizeof (*ret));
386   ret->lines = NULL;
387   ret->lines_num = 0;
388
389   buffer_ptr = fgets (buffer, sizeof (buffer), sh);
390   if (buffer_ptr == NULL) {
391     close_connection();
392     return (-3);
393   }
394   chomp (buffer);
395
396   ret->status = strtol (buffer, &ret->message, 0);
397   if (buffer == ret->message)
398   {
399     response_free (ret);
400     close_connection();
401     return (-4);
402   }
403   /* Skip leading whitespace of the status message */
404   ret->message += strspn (ret->message, " \t");
405
406   if (ret->status <= 0)
407   {
408     if (ret->status < 0)
409       rrd_set_error("rrdcached: %s", ret->message);
410     *ret_response = ret;
411     return (0);
412   }
413
414   ret->lines = (char **) malloc (sizeof (char *) * ret->status);
415   if (ret->lines == NULL)
416   {
417     response_free (ret);
418     close_connection();
419     return (-5);
420   }
421   memset (ret->lines, 0, sizeof (char *) * ret->status);
422   ret->lines_num = (size_t) ret->status;
423
424   for (i = 0; i < ret->lines_num; i++)
425   {
426     buffer_ptr = fgets (buffer, sizeof (buffer), sh);
427     if (buffer_ptr == NULL)
428     {
429       response_free (ret);
430       close_connection();
431       return (-6);
432     }
433     chomp (buffer);
434
435     ret->lines[i] = strdup (buffer);
436     if (ret->lines[i] == NULL)
437     {
438       response_free (ret);
439       close_connection();
440       return (-7);
441     }
442   }
443
444   *ret_response = ret;
445   return (0);
446 } /* }}} rrdc_response_t *response_read */
447
448 static int request (const char *buffer, size_t buffer_size, /* {{{ */
449     rrdc_response_t **ret_response)
450 {
451   int status;
452   rrdc_response_t *res;
453
454   if (sh == NULL)
455     return (ENOTCONN);
456
457   status = (int) fwrite (buffer, buffer_size, /* nmemb = */ 1, sh);
458   if (status != 1)
459   {
460     close_connection ();
461     rrd_set_error("request: socket error (%d) while talking to rrdcached",
462                   status);
463     return (-1);
464   }
465   fflush (sh);
466
467   res = NULL;
468   status = response_read (&res);
469
470   if (status != 0)
471   {
472     if (status < 0)
473       rrd_set_error("request: internal error while talking to rrdcached");
474     return (status);
475   }
476
477   *ret_response = res;
478   return (0);
479 } /* }}} int request */
480
481 /* determine whether we are connected to the specified daemon_addr if
482  * NULL, return whether we are connected at all
483  */
484 int rrdc_is_connected(const char *daemon_addr) /* {{{ */
485 {
486   if (sd < 0)
487     return 0;
488   else if (daemon_addr == NULL)
489   {
490     /* here we have to handle the case i.e.
491      *   UPDATE --daemon ...; UPDATEV (no --daemon) ...
492      * In other words: we have a cached connection,
493      * but it is not specified in the current command.
494      * Daemon is only implied in this case if set in ENV
495      */
496     if (getenv(ENV_RRDCACHED_ADDRESS) != NULL)
497       return 1;
498     else
499       return 0;
500   }
501   else if (strcmp(daemon_addr, sd_path) == 0)
502     return 1;
503   else
504     return 0;
505
506 } /* }}} int rrdc_is_connected */
507
508 static int rrdc_connect_unix (const char *path) /* {{{ */
509 {
510   struct sockaddr_un sa;
511   int status;
512
513   assert (path != NULL);
514   assert (sd == -1);
515
516   sd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
517   if (sd < 0)
518   {
519     status = errno;
520     return (status);
521   }
522
523   memset (&sa, 0, sizeof (sa));
524   sa.sun_family = AF_UNIX;
525   strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
526
527   status = connect (sd, (struct sockaddr *) &sa, sizeof (sa));
528   if (status != 0)
529   {
530     status = errno;
531     close_connection ();
532     return (status);
533   }
534
535   sh = fdopen (sd, "r+");
536   if (sh == NULL)
537   {
538     status = errno;
539     close_connection ();
540     return (status);
541   }
542
543   return (0);
544 } /* }}} int rrdc_connect_unix */
545
546 static int rrdc_connect_network (const char *addr_orig) /* {{{ */
547 {
548   struct addrinfo ai_hints;
549   struct addrinfo *ai_res;
550   struct addrinfo *ai_ptr;
551   char addr_copy[NI_MAXHOST];
552   char *addr;
553   char *port;
554
555   assert (addr_orig != NULL);
556   assert (sd == -1);
557
558   strncpy(addr_copy, addr_orig, sizeof(addr_copy));
559   addr_copy[sizeof(addr_copy) - 1] = '\0';
560   addr = addr_copy;
561
562   int status;
563   memset (&ai_hints, 0, sizeof (ai_hints));
564   ai_hints.ai_flags = 0;
565 #ifdef AI_ADDRCONFIG
566   ai_hints.ai_flags |= AI_ADDRCONFIG;
567 #endif
568   ai_hints.ai_family = AF_UNSPEC;
569   ai_hints.ai_socktype = SOCK_STREAM;
570
571   port = NULL;
572   if (*addr == '[') /* IPv6+port format */
573   {
574     /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
575     addr++;
576
577     port = strchr (addr, ']');
578     if (port == NULL)
579     {
580       rrd_set_error("malformed address: %s", addr_orig);
581       return (-1);
582     }
583     *port = 0;
584     port++;
585
586     if (*port == ':')
587       port++;
588     else if (*port == 0)
589       port = NULL;
590     else
591     {
592       rrd_set_error("garbage after address: %s", port);
593       return (-1);
594     }
595   } /* if (*addr == '[') */
596   else
597   {
598     port = rindex(addr, ':');
599     if (port != NULL)
600     {
601       *port = 0;
602       port++;
603     }
604   }
605
606   ai_res = NULL;
607   status = getaddrinfo (addr,
608                         port == NULL ? RRDCACHED_DEFAULT_PORT : port,
609                         &ai_hints, &ai_res);
610   if (status != 0)
611   {
612     rrd_set_error ("failed to resolve address `%s' (port %s): %s",
613         addr, port == NULL ? RRDCACHED_DEFAULT_PORT : port,
614         gai_strerror (status));
615     return (-1);
616   }
617
618   for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
619   {
620     sd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
621     if (sd < 0)
622     {
623       status = errno;
624       sd = -1;
625       continue;
626     }
627
628     status = connect (sd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
629     if (status != 0)
630     {
631       status = errno;
632       close_connection();
633       continue;
634     }
635
636     sh = fdopen (sd, "r+");
637     if (sh == NULL)
638     {
639       status = errno;
640       close_connection ();
641       continue;
642     }
643
644     assert (status == 0);
645     break;
646   } /* for (ai_ptr) */
647
648   return (status);
649 } /* }}} int rrdc_connect_network */
650
651 int rrdc_connect (const char *addr) /* {{{ */
652 {
653   int status = 0;
654
655   if (addr == NULL)
656     addr = getenv (ENV_RRDCACHED_ADDRESS);
657
658   if (addr == NULL)
659     return 0;
660
661   pthread_mutex_lock(&lock);
662
663   if (sd >= 0 && sd_path != NULL && strcmp(addr, sd_path) == 0)
664   {
665     /* connection to the same daemon; use cached connection */
666     pthread_mutex_unlock (&lock);
667     return (0);
668   }
669   else
670   {
671     close_connection();
672   }
673
674   rrd_clear_error ();
675   if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
676     status = rrdc_connect_unix (addr + strlen ("unix:"));
677   else if (addr[0] == '/')
678     status = rrdc_connect_unix (addr);
679   else
680     status = rrdc_connect_network(addr);
681
682   if (status == 0 && sd >= 0)
683     sd_path = strdup(addr);
684   else
685   {
686     char *err = rrd_test_error () ? rrd_get_error () : "Internal error";
687     /* err points the string that gets written to by rrd_set_error(), thus we
688      * cannot pass it to that function */
689     err = strdup (err);
690     rrd_set_error("Unable to connect to rrdcached: %s",
691                   (status < 0)
692                   ? (err ? err : "Internal error")
693                   : rrd_strerror (status));
694     if (err != NULL)
695       free (err);
696   }
697
698   pthread_mutex_unlock (&lock);
699   return (status);
700 } /* }}} int rrdc_connect */
701
702 int rrdc_disconnect (void) /* {{{ */
703 {
704   pthread_mutex_lock (&lock);
705
706   close_connection();
707
708   pthread_mutex_unlock (&lock);
709
710   return (0);
711 } /* }}} int rrdc_disconnect */
712
713 int rrdc_update (const char *filename, int values_num, /* {{{ */
714                 const char * const *values)
715 {
716   char buffer[4096];
717   char *buffer_ptr;
718   size_t buffer_free;
719   size_t buffer_size;
720   rrdc_response_t *res;
721   int status;
722   int i;
723   char file_path[PATH_MAX];
724
725   memset (buffer, 0, sizeof (buffer));
726   buffer_ptr = &buffer[0];
727   buffer_free = sizeof (buffer);
728
729   status = buffer_add_string ("update", &buffer_ptr, &buffer_free);
730   if (status != 0)
731     return (ENOBUFS);
732
733   pthread_mutex_lock (&lock);
734   filename = get_path (filename, file_path);
735   if (filename == NULL)
736   {
737     pthread_mutex_unlock (&lock);
738     return (-1);
739   }
740
741   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
742   if (status != 0)
743   {
744     pthread_mutex_unlock (&lock);
745     return (ENOBUFS);
746   }
747
748   for (i = 0; i < values_num; i++)
749   {
750     status = buffer_add_value (values[i], &buffer_ptr, &buffer_free);
751     if (status != 0)
752     {
753       pthread_mutex_unlock (&lock);
754       return (ENOBUFS);
755     }
756   }
757
758   assert (buffer_free < sizeof (buffer));
759   buffer_size = sizeof (buffer) - buffer_free;
760   assert (buffer[buffer_size - 1] == ' ');
761   buffer[buffer_size - 1] = '\n';
762
763   res = NULL;
764   status = request (buffer, buffer_size, &res);
765   pthread_mutex_unlock (&lock);
766
767   if (status != 0)
768     return (status);
769
770   status = res->status;
771   response_free (res);
772
773   return (status);
774 } /* }}} int rrdc_update */
775
776 int rrdc_flush (const char *filename) /* {{{ */
777 {
778   char buffer[4096];
779   char *buffer_ptr;
780   size_t buffer_free;
781   size_t buffer_size;
782   rrdc_response_t *res;
783   int status;
784   char file_path[PATH_MAX];
785
786   if (filename == NULL)
787     return (-1);
788
789   memset (buffer, 0, sizeof (buffer));
790   buffer_ptr = &buffer[0];
791   buffer_free = sizeof (buffer);
792
793   status = buffer_add_string ("flush", &buffer_ptr, &buffer_free);
794   if (status != 0)
795     return (ENOBUFS);
796
797   pthread_mutex_lock (&lock);
798   filename = get_path (filename, file_path);
799   if (filename == NULL)
800   {
801     pthread_mutex_unlock (&lock);
802     return (-1);
803   }
804
805   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
806   if (status != 0)
807   {
808     pthread_mutex_unlock (&lock);
809     return (ENOBUFS);
810   }
811
812   assert (buffer_free < sizeof (buffer));
813   buffer_size = sizeof (buffer) - buffer_free;
814   assert (buffer[buffer_size - 1] == ' ');
815   buffer[buffer_size - 1] = '\n';
816
817   res = NULL;
818   status = request (buffer, buffer_size, &res);
819   pthread_mutex_unlock (&lock);
820
821   if (status != 0)
822     return (status);
823
824   status = res->status;
825   response_free (res);
826
827   return (status);
828 } /* }}} int rrdc_flush */
829
830 rrd_info_t * rrdc_info (const char *filename) /* {{{ */
831 {
832   char buffer[4096];
833   char *buffer_ptr;
834   size_t buffer_free;
835   size_t buffer_size;
836   rrdc_response_t *res;
837   int status;
838   char file_path[PATH_MAX];
839   rrd_info_t *data = NULL, *cd;
840   rrd_infoval_t info;
841   unsigned int l;
842   rrd_info_type_t itype;
843   char *k, *s;
844
845   if (filename == NULL) {
846     rrd_set_error ("rrdc_info: no filename");
847     return (NULL);
848   }
849
850   memset (buffer, 0, sizeof (buffer));
851   buffer_ptr = &buffer[0];
852   buffer_free = sizeof (buffer);
853
854   status = buffer_add_string ("info", &buffer_ptr, &buffer_free);
855   if (status != 0) {
856     rrd_set_error ("rrdc_info: out of memory");
857     return (NULL);
858   }
859
860   pthread_mutex_lock (&lock);
861   filename = get_path (filename, file_path);
862   if (filename == NULL)
863   {
864     pthread_mutex_unlock (&lock);
865     return (NULL);
866   }
867
868   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
869   if (status != 0)
870   {
871     pthread_mutex_unlock (&lock);
872     rrd_set_error ("rrdc_info: out of memory");
873     return (NULL);
874   }
875
876   assert (buffer_free < sizeof (buffer));
877   buffer_size = sizeof (buffer) - buffer_free;
878   assert (buffer[buffer_size - 1] == ' ');
879   buffer[buffer_size - 1] = '\n';
880
881   res = NULL;
882   status = request (buffer, buffer_size, &res);
883   pthread_mutex_unlock (&lock);
884
885   if (status != 0) {
886     rrd_set_error ("rrdcached: %s", res->message);
887     return (NULL);
888   }
889   data = cd = NULL;
890   for( l=0 ; l < res->lines_num ; l++ ) {
891     /* first extract the keyword */
892         for(k = s = res->lines[l];s && *s;s++) {
893       if(*s == ' ') { *s = 0; s++; break; }
894         }
895     if(!s || !*s) break;
896         itype = atoi(s); /* extract type code */
897         for(;*s;s++) { if(*s == ' ') { *s = 0; s++; break; } }
898     if(!*s) break;
899     /* finally, we're pointing to the value */
900     switch(itype) {
901     case RD_I_VAL:
902         if(*s == 'N') { info.u_val = DNAN; } else { info.u_val = atof(s); }
903         break;
904     case RD_I_CNT:
905         info.u_cnt = atol(s);
906         break;
907     case RD_I_INT:
908         info.u_int = atoi(s);
909         break;
910     case RD_I_STR:
911         chomp(s);
912         info.u_str = (char*)malloc(sizeof(char) * (strlen(s) + 1));
913         strcpy(info.u_str,s);
914         break;
915     case RD_I_BLO:
916         rrd_set_error ("rrdc_info: BLOB objects are not supported");
917         return (NULL);
918     default:
919         rrd_set_error ("rrdc_info: Unsupported info type %d",itype);
920         return (NULL);
921     }
922         
923     cd = rrd_info_push(cd, sprintf_alloc("%s",k), itype, info);
924         if(!data) data = cd;
925   }
926   response_free (res);
927
928   return (data);
929 } /* }}} int rrdc_info */
930
931 time_t rrdc_last (const char *filename) /* {{{ */
932 {
933   char buffer[4096];
934   char *buffer_ptr;
935   size_t buffer_free;
936   size_t buffer_size;
937   rrdc_response_t *res;
938   int status;
939   char file_path[PATH_MAX];
940   time_t lastup;
941
942   if (filename == NULL) {
943     rrd_set_error ("rrdc_last: no filename");
944     return (-1);
945   }
946
947   memset (buffer, 0, sizeof (buffer));
948   buffer_ptr = &buffer[0];
949   buffer_free = sizeof (buffer);
950
951   status = buffer_add_string ("last", &buffer_ptr, &buffer_free);
952   if (status != 0) {
953     rrd_set_error ("rrdc_last: out of memory");
954     return (-1);
955   }
956
957   pthread_mutex_lock (&lock);
958   filename = get_path (filename, file_path);
959   if (filename == NULL)
960   {
961     pthread_mutex_unlock (&lock);
962     return (-1);
963   }
964
965   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
966   if (status != 0)
967   {
968     pthread_mutex_unlock (&lock);
969     rrd_set_error ("rrdc_last: out of memory");
970     return (-1);
971   }
972
973   assert (buffer_free < sizeof (buffer));
974   buffer_size = sizeof (buffer) - buffer_free;
975   assert (buffer[buffer_size - 1] == ' ');
976   buffer[buffer_size - 1] = '\n';
977
978   res = NULL;
979   status = request (buffer, buffer_size, &res);
980   pthread_mutex_unlock (&lock);
981
982   if (status != 0) {
983     rrd_set_error ("rrdcached: %s", res->message);
984     return (-1);
985   }
986   lastup = atol(res->message);
987   response_free (res);
988
989   return (lastup);
990 } /* }}} int rrdc_last */
991
992 time_t rrdc_first (const char *filename, int rraindex) /* {{{ */
993 {
994   char buffer[4096];
995   char *buffer_ptr;
996   size_t buffer_free;
997   size_t buffer_size;
998   rrdc_response_t *res;
999   int status;
1000   char file_path[PATH_MAX];
1001   time_t firstup;
1002
1003   if (filename == NULL) {
1004     rrd_set_error ("rrdc_first: no filename specified");
1005     return (-1);
1006   }
1007
1008   memset (buffer, 0, sizeof (buffer));
1009   buffer_ptr = &buffer[0];
1010   buffer_free = sizeof (buffer);
1011
1012   status = buffer_add_string ("first", &buffer_ptr, &buffer_free);
1013   if (status != 0) {
1014     rrd_set_error ("rrdc_first: out of memory");
1015     return (-1);
1016   }
1017
1018   pthread_mutex_lock (&lock);
1019   filename = get_path (filename, file_path);
1020   if (filename == NULL)
1021   {
1022     pthread_mutex_unlock (&lock);
1023     return (-1);
1024   }
1025
1026   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
1027   if (status != 0)
1028   {
1029     pthread_mutex_unlock (&lock);
1030     rrd_set_error ("rrdc_first: out of memory");
1031     return (-1);
1032   }
1033   status = buffer_add_ulong (rraindex, &buffer_ptr, &buffer_free);
1034   if (status != 0)
1035   {
1036     pthread_mutex_unlock (&lock);
1037     rrd_set_error ("rrdc_first: out of memory");
1038     return (-1);
1039   }
1040
1041   assert (buffer_free < sizeof (buffer));
1042   buffer_size = sizeof (buffer) - buffer_free;
1043   assert (buffer[buffer_size - 1] == ' ');
1044   buffer[buffer_size - 1] = '\n';
1045
1046   res = NULL;
1047   status = request (buffer, buffer_size, &res);
1048   pthread_mutex_unlock (&lock);
1049
1050   if (status != 0) {
1051     rrd_set_error ("rrdcached: %s", res->message);
1052     return (-1);
1053   }
1054   firstup = atol(res->message);
1055   response_free (res);
1056
1057   return (firstup);
1058 } /* }}} int rrdc_first */
1059
1060 int rrdc_create (const char *filename, /* {{{ */
1061     unsigned long pdp_step,
1062     time_t last_up,
1063     int no_overwrite,
1064     int argc,
1065     const char **argv)
1066 {
1067   char buffer[4096];
1068   char *buffer_ptr;
1069   size_t buffer_free;
1070   size_t buffer_size;
1071   rrdc_response_t *res;
1072   int status;
1073   char file_path[PATH_MAX];
1074   int i;
1075
1076   if (filename == NULL) {
1077     rrd_set_error ("rrdc_create: no filename specified");
1078     return (-1);
1079   }
1080
1081   memset (buffer, 0, sizeof (buffer));
1082   buffer_ptr = &buffer[0];
1083   buffer_free = sizeof (buffer);
1084
1085   status = buffer_add_string ("create", &buffer_ptr, &buffer_free);
1086   if (status != 0) {
1087     rrd_set_error ("rrdc_create: out of memory");
1088     return (-1);
1089   }
1090
1091   pthread_mutex_lock (&lock);
1092   filename = get_path (filename, file_path);
1093   if (filename == NULL)
1094   {
1095     pthread_mutex_unlock (&lock);
1096     return (-1);
1097   }
1098
1099   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
1100   status = buffer_add_string ("-b", &buffer_ptr, &buffer_free);
1101   status = buffer_add_ulong (last_up, &buffer_ptr, &buffer_free);
1102   status = buffer_add_string ("-s", &buffer_ptr, &buffer_free);
1103   status = buffer_add_ulong (pdp_step, &buffer_ptr, &buffer_free);
1104   if(no_overwrite) {
1105     status = buffer_add_string ("-O", &buffer_ptr, &buffer_free);
1106   }
1107   if (status != 0)
1108   {
1109     pthread_mutex_unlock (&lock);
1110     rrd_set_error ("rrdc_create: out of memory");
1111     return (-1);
1112   }
1113
1114   for( i=0; i<argc; i++ ) {
1115     if( argv[i] ) {
1116       status = buffer_add_string (argv[i], &buffer_ptr, &buffer_free);
1117       if (status != 0)
1118       {
1119         pthread_mutex_unlock (&lock);
1120         rrd_set_error ("rrdc_create: out of memory");
1121         return (-1);
1122       }
1123         }
1124   }
1125
1126   /* buffer ready to send? */
1127   assert (buffer_free < sizeof (buffer));
1128   buffer_size = sizeof (buffer) - buffer_free;
1129   assert (buffer[buffer_size - 1] == ' ');
1130   buffer[buffer_size - 1] = '\n';
1131
1132   res = NULL;
1133   status = request (buffer, buffer_size, &res);
1134   pthread_mutex_unlock (&lock);
1135
1136   if (status != 0) {
1137     rrd_set_error ("rrdcached: %s", res->message);
1138     return (-1);
1139   }
1140   response_free (res);
1141   return(0);
1142 } /* }}} int rrdc_create */
1143
1144 int rrdc_fetch (const char *filename, /* {{{ */
1145     const char *cf,
1146     time_t *ret_start, time_t *ret_end,
1147     unsigned long *ret_step,
1148     unsigned long *ret_ds_num,
1149     char ***ret_ds_names,
1150     rrd_value_t **ret_data)
1151 {
1152   char buffer[4096];
1153   char *buffer_ptr;
1154   size_t buffer_free;
1155   size_t buffer_size;
1156   rrdc_response_t *res;
1157   char path_buffer[PATH_MAX];
1158   const char *path_ptr;
1159
1160   char *str_tmp;
1161   unsigned long flush_version;
1162
1163   time_t start;
1164   time_t end;
1165   unsigned long step;
1166   unsigned long ds_num;
1167   char **ds_names;
1168
1169   rrd_value_t *data;
1170   size_t data_size;
1171   size_t data_fill;
1172
1173   int status;
1174   size_t current_line;
1175   time_t t;
1176
1177   if ((filename == NULL) || (cf == NULL))
1178     return (-1);
1179
1180   /* Send request {{{ */
1181   memset (buffer, 0, sizeof (buffer));
1182   buffer_ptr = &buffer[0];
1183   buffer_free = sizeof (buffer);
1184
1185   status = buffer_add_string ("FETCH", &buffer_ptr, &buffer_free);
1186   if (status != 0)
1187     return (ENOBUFS);
1188
1189   /* change to path for rrdcached */
1190   path_ptr = get_path (filename, path_buffer);
1191   if (path_ptr == NULL)
1192     return (EINVAL);
1193
1194   status = buffer_add_string (path_ptr, &buffer_ptr, &buffer_free);
1195   if (status != 0)
1196     return (ENOBUFS);
1197
1198   status = buffer_add_string (cf, &buffer_ptr, &buffer_free);
1199   if (status != 0)
1200     return (ENOBUFS);
1201
1202   if ((ret_start != NULL) && (*ret_start > 0))
1203   {
1204     char tmp[64];
1205     snprintf (tmp, sizeof (tmp), "%lu", (unsigned long) *ret_start);
1206     tmp[sizeof (tmp) - 1] = 0;
1207     status = buffer_add_string (tmp, &buffer_ptr, &buffer_free);
1208     if (status != 0)
1209       return (ENOBUFS);
1210
1211     if ((ret_end != NULL) && (*ret_end > 0))
1212     {
1213       snprintf (tmp, sizeof (tmp), "%lu", (unsigned long) *ret_end);
1214       tmp[sizeof (tmp) - 1] = 0;
1215       status = buffer_add_string (tmp, &buffer_ptr, &buffer_free);
1216       if (status != 0)
1217         return (ENOBUFS);
1218     }
1219   }
1220
1221   assert (buffer_free < sizeof (buffer));
1222   buffer_size = sizeof (buffer) - buffer_free;
1223   assert (buffer[buffer_size - 1] == ' ');
1224   buffer[buffer_size - 1] = '\n';
1225
1226   res = NULL;
1227   status = request (buffer, buffer_size, &res);
1228   if (status != 0)
1229     return (status);
1230
1231   status = res->status;
1232   if (status < 0)
1233   {
1234     rrd_set_error ("rrdcached: %s", res->message);
1235     response_free (res);
1236     return (status);
1237   }
1238   /* }}} Send request */
1239
1240   ds_names = NULL;
1241   ds_num = 0;
1242   data = NULL;
1243   current_line = 0;
1244
1245   /* Macros to make error handling a little easier (i. e. less to type and
1246    * read. `BAIL_OUT' sets the error message, frees all dynamically allocated
1247    * variables and returns the provided status code. */
1248 #define BAIL_OUT(status, ...) do { \
1249     rrd_set_error ("rrdc_fetch: " __VA_ARGS__); \
1250     free (data); \
1251     if (ds_names != 0) { size_t k; for (k = 0; k < ds_num; k++) free (ds_names[k]); } \
1252     free (ds_names); \
1253     response_free (res); \
1254     return (status); \
1255   } while (0)
1256
1257 #define READ_NUMERIC_FIELD(name,type,var) do { \
1258     char *key; \
1259     unsigned long value; \
1260     assert (current_line < res->lines_num); \
1261     status = parse_ulong_header (res->lines[current_line], &key, &value); \
1262     if (status != 0) \
1263       BAIL_OUT (-1, "Unable to parse header `%s'", name); \
1264     if (strcasecmp (key, name) != 0) \
1265       BAIL_OUT (-1, "Unexpected header line: Expected `%s', got `%s'", name, key); \
1266     var = (type) value; \
1267     current_line++; \
1268   } while (0)
1269
1270   if (res->lines_num < 1)
1271     BAIL_OUT (-1, "Premature end of response packet");
1272
1273   /* We're making some very strong assumptions about the fields below. We
1274    * therefore check the version of the `flush' command first, so that later
1275    * versions can change the order of fields and it's easier to implement
1276    * backwards compatibility. */
1277   READ_NUMERIC_FIELD ("FlushVersion", unsigned long, flush_version);
1278   if (flush_version != 1)
1279     BAIL_OUT (-1, "Don't know how to handle flush format version %lu.",
1280         flush_version);
1281
1282   if (res->lines_num < 5)
1283     BAIL_OUT (-1, "Premature end of response packet");
1284
1285   READ_NUMERIC_FIELD ("Start", time_t, start);
1286   READ_NUMERIC_FIELD ("End", time_t, end);
1287   if (start >= end)
1288     BAIL_OUT (-1, "Malformed start and end times: start = %lu; end = %lu;",
1289         (unsigned long) start,
1290         (unsigned long) end);
1291
1292   READ_NUMERIC_FIELD ("Step", unsigned long, step);
1293   if (step < 1)
1294     BAIL_OUT (-1, "Invalid number for Step: %lu", step);
1295
1296   READ_NUMERIC_FIELD ("DSCount", unsigned long, ds_num);
1297   if (ds_num < 1)
1298     BAIL_OUT (-1, "Invalid number for DSCount: %lu", ds_num);
1299   
1300   /* It's time to allocate some memory */
1301   ds_names = calloc ((size_t) ds_num, sizeof (*ds_names));
1302   if (ds_names == NULL)
1303     BAIL_OUT (-1, "Out of memory");
1304
1305   status = parse_char_array_header (res->lines[current_line],
1306       &str_tmp, ds_names, (size_t) ds_num, /* alloc = */ 1);
1307   if (status != 0)
1308     BAIL_OUT (-1, "Unable to parse header `DSName'");
1309   if (strcasecmp ("DSName", str_tmp) != 0)
1310     BAIL_OUT (-1, "Unexpected header line: Expected `DSName', got `%s'", str_tmp);
1311   current_line++;
1312
1313   data_size = ds_num * (end - start) / step;
1314   if (data_size < 1)
1315     BAIL_OUT (-1, "No data returned or headers invalid.");
1316
1317   if (res->lines_num != (6 + (data_size / ds_num)))
1318     BAIL_OUT (-1, "Got %zu lines, expected %zu",
1319         res->lines_num, (6 + (data_size / ds_num)));
1320
1321   data = calloc (data_size, sizeof (*data));
1322   if (data == NULL)
1323     BAIL_OUT (-1, "Out of memory");
1324   
1325
1326   data_fill = 0;
1327   for (t = start + step; t <= end; t += step, current_line++)
1328   {
1329     time_t tmp;
1330
1331     assert (current_line < res->lines_num);
1332
1333     status = parse_value_array_header (res->lines[current_line],
1334         &tmp, data + data_fill, (size_t) ds_num);
1335     if (status != 0)
1336       BAIL_OUT (-1, "Cannot parse value line");
1337
1338     data_fill += (size_t) ds_num;
1339   }
1340
1341   *ret_start = start;
1342   *ret_end = end;
1343   *ret_step = step;
1344   *ret_ds_num = ds_num;
1345   *ret_ds_names = ds_names;
1346   *ret_data = data;
1347
1348   response_free (res);
1349   return (0);
1350 #undef READ_NUMERIC_FIELD
1351 #undef BAIL_OUT
1352 } /* }}} int rrdc_flush */
1353
1354 /* convenience function; if there is a daemon specified, or if we can
1355  * detect one from the environment, then flush the file.  Otherwise, no-op
1356  */
1357 int rrdc_flush_if_daemon (const char *opt_daemon, const char *filename) /* {{{ */
1358 {
1359   int status = 0;
1360
1361   rrdc_connect(opt_daemon);
1362
1363   if (rrdc_is_connected(opt_daemon))
1364   {
1365     rrd_clear_error();
1366     status = rrdc_flush (filename);
1367
1368     if (status != 0 && !rrd_test_error())
1369     {
1370       if (status > 0)
1371       {
1372         rrd_set_error("rrdc_flush (%s) failed: %s",
1373                       filename, rrd_strerror(status));
1374       }
1375       else if (status < 0)
1376       {
1377         rrd_set_error("rrdc_flush (%s) failed with status %i.",
1378                       filename, status);
1379       }
1380     }
1381   } /* if (rrdc_is_connected(..)) */
1382
1383   return status;
1384 } /* }}} int rrdc_flush_if_daemon */
1385
1386
1387 int rrdc_stats_get (rrdc_stats_t **ret_stats) /* {{{ */
1388 {
1389   rrdc_stats_t *head;
1390   rrdc_stats_t *tail;
1391
1392   rrdc_response_t *res;
1393
1394   int status;
1395   size_t i;
1396
1397   /* Protocol example: {{{
1398    * ->  STATS
1399    * <-  5 Statistics follow
1400    * <-  QueueLength: 0
1401    * <-  UpdatesWritten: 0
1402    * <-  DataSetsWritten: 0
1403    * <-  TreeNodesNumber: 0
1404    * <-  TreeDepth: 0
1405    * }}} */
1406
1407   res = NULL;
1408   pthread_mutex_lock (&lock);
1409   status = request ("STATS\n", strlen ("STATS\n"), &res);
1410   pthread_mutex_unlock (&lock);
1411
1412   if (status != 0)
1413     return (status);
1414
1415   if (res->status <= 0)
1416   {
1417     response_free (res);
1418     return (EIO);
1419   }
1420
1421   head = NULL;
1422   tail = NULL;
1423   for (i = 0; i < res->lines_num; i++)
1424   {
1425     char *key;
1426     char *value;
1427     char *endptr;
1428     rrdc_stats_t *s;
1429
1430     key = res->lines[i];
1431     value = strchr (key, ':');
1432     if (value == NULL)
1433       continue;
1434     *value = 0;
1435     value++;
1436
1437     while ((value[0] == ' ') || (value[0] == '\t'))
1438       value++;
1439
1440     s = (rrdc_stats_t *) malloc (sizeof (rrdc_stats_t));
1441     if (s == NULL)
1442       continue;
1443     memset (s, 0, sizeof (*s));
1444
1445     s->name = strdup (key);
1446
1447     endptr = NULL;
1448     if ((strcmp ("QueueLength", key) == 0)
1449         || (strcmp ("TreeDepth", key) == 0)
1450         || (strcmp ("TreeNodesNumber", key) == 0))
1451     {
1452       s->type = RRDC_STATS_TYPE_GAUGE;
1453       s->value.gauge = strtod (value, &endptr);
1454     }
1455     else if ((strcmp ("DataSetsWritten", key) == 0)
1456         || (strcmp ("FlushesReceived", key) == 0)
1457         || (strcmp ("JournalBytes", key) == 0)
1458         || (strcmp ("JournalRotate", key) == 0)
1459         || (strcmp ("UpdatesReceived", key) == 0)
1460         || (strcmp ("UpdatesWritten", key) == 0))
1461     {
1462       s->type = RRDC_STATS_TYPE_COUNTER;
1463       s->value.counter = (uint64_t) strtoll (value, &endptr, /* base = */ 0);
1464     }
1465     else
1466     {
1467       free (s);
1468       continue;
1469     }
1470
1471     /* Conversion failed */
1472     if (endptr == value)
1473     {
1474       free (s);
1475       continue;
1476     }
1477
1478     if (head == NULL)
1479     {
1480       head = s;
1481       tail = s;
1482       s->next = NULL;
1483     }
1484     else
1485     {
1486       tail->next = s;
1487       tail = s;
1488     }
1489   } /* for (i = 0; i < res->lines_num; i++) */
1490
1491   response_free (res);
1492
1493   if (head == NULL)
1494     return (EPROTO);
1495
1496   *ret_stats = head;
1497   return (0);
1498 } /* }}} int rrdc_stats_get */
1499
1500 void rrdc_stats_free (rrdc_stats_t *ret_stats) /* {{{ */
1501 {
1502   rrdc_stats_t *this;
1503
1504   this = ret_stats;
1505   while (this != NULL)
1506   {
1507     rrdc_stats_t *next;
1508
1509     next = this->next;
1510
1511     if (this->name != NULL)
1512     {
1513       free ((char *)this->name);
1514       this->name = NULL;
1515     }
1516     free (this);
1517
1518     this = next;
1519   } /* while (this != NULL) */
1520 } /* }}} void rrdc_stats_free */
1521
1522 /*
1523  * vim: set sw=2 sts=2 ts=8 et fdm=marker :
1524  */