Code

handling of ENV_RRDCACHED_ADDRESS:
[rrdtool-all.git] / program / src / rrd_client.c
1 /**
2  * RRDTool - src/rrd_client.c
3  * Copyright (C) 2008 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  **/
28 #include "rrd.h"
29 #include "rrd_tool.h"
30 #include "rrd_client.h"
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>
45 #ifndef ENODATA
46 #define ENODATA ENOENT
47 #endif
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;
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 */
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;
76   if ((path == NULL) || (resolved_path == NULL) || (sd_path == NULL))
77     return (NULL);
79   if ((*sd_path == '/')
80       || (strncmp ("unix:", sd_path, strlen ("unix:")) == 0))
81     is_unix = 1;
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   }
100   return path;
101 } /* }}} char *get_path */
103 /* One must hold `lock' when calling `close_connection'. */
104 static void close_connection (void) /* {{{ */
106   if (sh != NULL)
107   {
108     fclose (sh);
109     sh = NULL;
110     sd = -1;
111   }
112   else if (sd >= 0)
113   {
114     close (sd);
115     sd = -1;
116   }
118   if (sd_path != NULL)
119     free (sd_path);
120   sd_path = NULL;
121 } /* }}} void close_connection */
123 static int buffer_add_string (const char *str, /* {{{ */
124     char **buffer_ret, size_t *buffer_size_ret)
126   char *buffer;
127   size_t buffer_size;
128   size_t buffer_pos;
129   size_t i;
130   int status;
132   buffer = *buffer_ret;
133   buffer_size = *buffer_size_ret;
134   buffer_pos = 0;
136   i = 0;
137   status = -1;
138   while (buffer_pos < buffer_size)
139   {
140     if (str[i] == 0)
141     {
142       buffer[buffer_pos] = ' ';
143       buffer_pos++;
144       status = 0;
145       break;
146     }
147     else if ((str[i] == ' ') || (str[i] == '\\'))
148     {
149       if (buffer_pos >= (buffer_size - 1))
150         break;
151       buffer[buffer_pos] = '\\';
152       buffer_pos++;
153       buffer[buffer_pos] = str[i];
154       buffer_pos++;
155     }
156     else
157     {
158       buffer[buffer_pos] = str[i];
159       buffer_pos++;
160     }
161     i++;
162   } /* while (buffer_pos < buffer_size) */
164   if (status != 0)
165     return (-1);
167   *buffer_ret = buffer + buffer_pos;
168   *buffer_size_ret = buffer_size - buffer_pos;
170   return (0);
171 } /* }}} int buffer_add_string */
173 static int buffer_add_value (const char *value, /* {{{ */
174     char **buffer_ret, size_t *buffer_size_ret)
176   char temp[4096];
178   if (strncmp (value, "N:", 2) == 0)
179     snprintf (temp, sizeof (temp), "%lu:%s",
180         (unsigned long) time (NULL), value + 2);
181   else
182     strncpy (temp, value, sizeof (temp));
183   temp[sizeof (temp) - 1] = 0;
185   return (buffer_add_string (temp, buffer_ret, buffer_size_ret));
186 } /* }}} int buffer_add_value */
188 /* Remove trailing newline (NL) and carriage return (CR) characters. Similar to
189  * the Perl function `chomp'. Returns the number of characters that have been
190  * removed. */
191 static int chomp (char *str) /* {{{ */
193   size_t len;
194   int removed;
196   if (str == NULL)
197     return (-1);
199   len = strlen (str);
200   removed = 0;
201   while ((len > 0) && ((str[len - 1] == '\n') || (str[len - 1] == '\r')))
202   {
203     str[len - 1] = 0;
204     len--;
205     removed++;
206   }
208   return (removed);
209 } /* }}} int chomp */
211 static void response_free (rrdc_response_t *res) /* {{{ */
213   if (res == NULL)
214     return;
216   if (res->lines != NULL)
217   {
218     size_t i;
220     for (i = 0; i < res->lines_num; i++)
221       if (res->lines[i] != NULL)
222         free (res->lines[i]);
223     free (res->lines);
224   }
226   free (res);
227 } /* }}} void response_free */
229 static int response_read (rrdc_response_t **ret_response) /* {{{ */
231   rrdc_response_t *ret = NULL;
232   int status = 0;
234   char buffer[4096];
235   char *buffer_ptr;
237   size_t i;
239 #define DIE(code) do { status = code; goto err_out; } while(0)
241   if (sh == NULL)
242     DIE(-1);
244   ret = (rrdc_response_t *) malloc (sizeof (rrdc_response_t));
245   if (ret == NULL)
246     DIE(-2);
247   memset (ret, 0, sizeof (*ret));
248   ret->lines = NULL;
249   ret->lines_num = 0;
251   buffer_ptr = fgets (buffer, sizeof (buffer), sh);
252   if (buffer_ptr == NULL)
253     DIE(-3);
255   chomp (buffer);
257   ret->status = strtol (buffer, &ret->message, 0);
258   if (buffer == ret->message)
259     DIE(-4);
261   /* Skip leading whitespace of the status message */
262   ret->message += strspn (ret->message, " \t");
264   if (ret->status <= 0)
265   {
266     if (ret->status < 0)
267       rrd_set_error("rrdcached: %s", ret->message);
268     goto out;
269   }
271   ret->lines = (char **) malloc (sizeof (char *) * ret->status);
272   if (ret->lines == NULL)
273     DIE(-5);
275   memset (ret->lines, 0, sizeof (char *) * ret->status);
276   ret->lines_num = (size_t) ret->status;
278   for (i = 0; i < ret->lines_num; i++)
279   {
280     buffer_ptr = fgets (buffer, sizeof (buffer), sh);
281     if (buffer_ptr == NULL)
282       DIE(-6);
284     chomp (buffer);
286     ret->lines[i] = strdup (buffer);
287     if (ret->lines[i] == NULL)
288       DIE(-7);
289   }
291 out:
292   *ret_response = ret;
293   fflush(sh);
294   return (status);
296 err_out:
297   response_free(ret);
298   close_connection();
299   return (status);
301 #undef DIE
303 } /* }}} rrdc_response_t *response_read */
305 static int request (const char *buffer, size_t buffer_size, /* {{{ */
306     rrdc_response_t **ret_response)
308   int status;
309   rrdc_response_t *res;
311   if (sh == NULL)
312     return (ENOTCONN);
314   status = (int) fwrite (buffer, buffer_size, /* nmemb = */ 1, sh);
315   if (status != 1)
316   {
317     close_connection ();
318     rrd_set_error("request: socket error (%d) while talking to rrdcached",
319                   status);
320     return (-1);
321   }
322   fflush (sh);
324   res = NULL;
325   status = response_read (&res);
327   if (status != 0)
328   {
329     if (status < 0)
330       rrd_set_error("request: internal error while talking to rrdcached");
331     return (status);
332   }
334   *ret_response = res;
335   return (0);
336 } /* }}} int request */
338 /* determine whether we are connected to the specified daemon_addr if
339  * NULL, return whether we are connected at all
340  */
341 int rrdc_is_connected(const char *daemon_addr) /* {{{ */
343   if (sd < 0)
344     return 0;
345   else if (daemon_addr == NULL)
346   {
347     /* here we have to handle the case i.e.
348      *   UPDATE --daemon ...; UPDATEV (no --daemon) ...
349      * In other words: we have a cached connection,
350      * but it is not specified in the current command.
351      * Daemon is only implied in this case if set in ENV
352      */
353     if (getenv(ENV_RRDCACHED_ADDRESS) != NULL)
354       return 1;
355     else
356       return 0;
357   }
358   else if (strcmp(daemon_addr, sd_path) == 0)
359     return 1;
360   else
361     return 0;
363 } /* }}} int rrdc_is_connected */
365 static int rrdc_connect_unix (const char *path) /* {{{ */
367   struct sockaddr_un sa;
368   int status;
370   assert (path != NULL);
371   assert (sd == -1);
373   sd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
374   if (sd < 0)
375   {
376     status = errno;
377     return (status);
378   }
380   memset (&sa, 0, sizeof (sa));
381   sa.sun_family = AF_UNIX;
382   strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
384   status = connect (sd, (struct sockaddr *) &sa, sizeof (sa));
385   if (status != 0)
386   {
387     status = errno;
388     close_connection ();
389     return (status);
390   }
392   sh = fdopen (sd, "r+");
393   if (sh == NULL)
394   {
395     status = errno;
396     close_connection ();
397     return (status);
398   }
400   return (0);
401 } /* }}} int rrdc_connect_unix */
403 static int rrdc_connect_network (const char *addr_orig) /* {{{ */
405   struct addrinfo ai_hints;
406   struct addrinfo *ai_res;
407   struct addrinfo *ai_ptr;
408   char addr_copy[NI_MAXHOST];
409   char *addr;
410   char *port;
412   assert (addr_orig != NULL);
413   assert (sd == -1);
415   strncpy(addr_copy, addr_orig, sizeof(addr_copy));
416   addr_copy[sizeof(addr_copy) - 1] = '\0';
417   addr = addr_copy;
419   int status;
420   memset (&ai_hints, 0, sizeof (ai_hints));
421   ai_hints.ai_flags = 0;
422 #ifdef AI_ADDRCONFIG
423   ai_hints.ai_flags |= AI_ADDRCONFIG;
424 #endif
425   ai_hints.ai_family = AF_UNSPEC;
426   ai_hints.ai_socktype = SOCK_STREAM;
428   port = NULL;
429   if (*addr == '[') /* IPv6+port format */
430   {
431     /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
432     addr++;
434     port = strchr (addr, ']');
435     if (port == NULL)
436     {
437       rrd_set_error("malformed address: %s", addr_orig);
438       return (-1);
439     }
440     *port = 0;
441     port++;
443     if (*port == ':')
444       port++;
445     else if (*port == 0)
446       port = NULL;
447     else
448     {
449       rrd_set_error("garbage after address: %s", port);
450       return (-1);
451     }
452   } /* if (*addr == '[') */
453   else
454   {
455     port = rindex(addr, ':');
456     if (port != NULL)
457     {
458       *port = 0;
459       port++;
460     }
461   }
463   ai_res = NULL;
464   status = getaddrinfo (addr,
465                         port == NULL ? RRDCACHED_DEFAULT_PORT : port,
466                         &ai_hints, &ai_res);
467   if (status != 0)
468   {
469     rrd_set_error ("failed to resolve address `%s' (port %s): %s",
470         addr, port == NULL ? RRDCACHED_DEFAULT_PORT : port,
471         gai_strerror (status));
472     return (-1);
473   }
475   for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
476   {
477     sd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
478     if (sd < 0)
479     {
480       status = errno;
481       sd = -1;
482       continue;
483     }
485     status = connect (sd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
486     if (status != 0)
487     {
488       status = errno;
489       close_connection();
490       continue;
491     }
493     sh = fdopen (sd, "r+");
494     if (sh == NULL)
495     {
496       status = errno;
497       close_connection ();
498       continue;
499     }
501     assert (status == 0);
502     break;
503   } /* for (ai_ptr) */
505   freeaddrinfo(ai_res);
507   return (status);
508 } /* }}} int rrdc_connect_network */
510 int rrdc_connect (const char *addr) /* {{{ */
512   int status = 0;
514   if (addr == NULL) {
515     addr = getenv (ENV_RRDCACHED_ADDRESS);
516   }
518   if (addr == NULL || ! strcmp(addr,"") ) {
519     addr = NULL;
520     return 0;   
521   }
523   pthread_mutex_lock(&lock);
525   if (sd >= 0 && sd_path != NULL && strcmp(addr, sd_path) == 0)
526   {
527     /* connection to the same daemon; use cached connection */
528     pthread_mutex_unlock (&lock);
529     return (0);
530   }
531   else
532   {
533     close_connection();
534   }
536   rrd_clear_error ();
537   if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
538     status = rrdc_connect_unix (addr + strlen ("unix:"));
539   else if (addr[0] == '/')
540     status = rrdc_connect_unix (addr);
541   else
542     status = rrdc_connect_network(addr);
544   if (status == 0 && sd >= 0)
545     sd_path = strdup(addr);
546   else
547   {
548     char *err = rrd_test_error () ? rrd_get_error () : "Internal error";
549     /* err points the string that gets written to by rrd_set_error(), thus we
550      * cannot pass it to that function */
551     err = strdup (err);
552     rrd_set_error("Unable to connect to rrdcached: %s",
553                   (status < 0)
554                   ? (err ? err : "Internal error")
555                   : rrd_strerror (status));
556     if (err != NULL)
557       free (err);
558   }
560   pthread_mutex_unlock (&lock);
561   return (status);
562 } /* }}} int rrdc_connect */
564 int rrdc_disconnect (void) /* {{{ */
566   pthread_mutex_lock (&lock);
568   close_connection();
570   pthread_mutex_unlock (&lock);
572   return (0);
573 } /* }}} int rrdc_disconnect */
575 int rrdc_update (const char *filename, int values_num, /* {{{ */
576                 const char * const *values)
578   char buffer[4096];
579   char *buffer_ptr;
580   size_t buffer_free;
581   size_t buffer_size;
582   rrdc_response_t *res;
583   int status;
584   int i;
585   char file_path[PATH_MAX];
587   memset (buffer, 0, sizeof (buffer));
588   buffer_ptr = &buffer[0];
589   buffer_free = sizeof (buffer);
591   status = buffer_add_string ("update", &buffer_ptr, &buffer_free);
592   if (status != 0)
593     return (ENOBUFS);
595   pthread_mutex_lock (&lock);
596   filename = get_path (filename, file_path);
597   if (filename == NULL)
598   {
599     pthread_mutex_unlock (&lock);
600     return (-1);
601   }
603   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
604   if (status != 0)
605   {
606     pthread_mutex_unlock (&lock);
607     return (ENOBUFS);
608   }
610   for (i = 0; i < values_num; i++)
611   {
612     status = buffer_add_value (values[i], &buffer_ptr, &buffer_free);
613     if (status != 0)
614     {
615       pthread_mutex_unlock (&lock);
616       return (ENOBUFS);
617     }
618   }
620   assert (buffer_free < sizeof (buffer));
621   buffer_size = sizeof (buffer) - buffer_free;
622   assert (buffer[buffer_size - 1] == ' ');
623   buffer[buffer_size - 1] = '\n';
625   res = NULL;
626   status = request (buffer, buffer_size, &res);
627   pthread_mutex_unlock (&lock);
629   if (status != 0)
630     return (status);
632   status = res->status;
633   response_free (res);
635   return (status);
636 } /* }}} int rrdc_update */
638 int rrdc_flush (const char *filename) /* {{{ */
640   char buffer[4096];
641   char *buffer_ptr;
642   size_t buffer_free;
643   size_t buffer_size;
644   rrdc_response_t *res;
645   int status;
646   char file_path[PATH_MAX];
648   if (filename == NULL)
649     return (-1);
651   memset (buffer, 0, sizeof (buffer));
652   buffer_ptr = &buffer[0];
653   buffer_free = sizeof (buffer);
655   status = buffer_add_string ("flush", &buffer_ptr, &buffer_free);
656   if (status != 0)
657     return (ENOBUFS);
659   pthread_mutex_lock (&lock);
660   filename = get_path (filename, file_path);
661   if (filename == NULL)
662   {
663     pthread_mutex_unlock (&lock);
664     return (-1);
665   }
667   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
668   if (status != 0)
669   {
670     pthread_mutex_unlock (&lock);
671     return (ENOBUFS);
672   }
674   assert (buffer_free < sizeof (buffer));
675   buffer_size = sizeof (buffer) - buffer_free;
676   assert (buffer[buffer_size - 1] == ' ');
677   buffer[buffer_size - 1] = '\n';
679   res = NULL;
680   status = request (buffer, buffer_size, &res);
681   pthread_mutex_unlock (&lock);
683   if (status != 0)
684     return (status);
686   status = res->status;
687   response_free (res);
689   return (status);
690 } /* }}} int rrdc_flush */
693 /* convenience function; if there is a daemon specified, or if we can
694  * detect one from the environment, then flush the file.  Otherwise, no-op
695  */
696 int rrdc_flush_if_daemon (const char *opt_daemon, const char *filename) /* {{{ */
698   int status = 0;
700   rrdc_connect(opt_daemon);
702   if (rrdc_is_connected(opt_daemon))
703   {
704     rrd_clear_error();
705     status = rrdc_flush (filename);
707     if (status != 0 && !rrd_test_error())
708     {
709       if (status > 0)
710       {
711         rrd_set_error("rrdc_flush (%s) failed: %s",
712                       filename, rrd_strerror(status));
713       }
714       else if (status < 0)
715       {
716         rrd_set_error("rrdc_flush (%s) failed with status %i.",
717                       filename, status);
718       }
719     }
720   } /* if (rrdc_is_connected(..)) */
722   return status;
723 } /* }}} int rrdc_flush_if_daemon */
726 int rrdc_stats_get (rrdc_stats_t **ret_stats) /* {{{ */
728   rrdc_stats_t *head;
729   rrdc_stats_t *tail;
731   rrdc_response_t *res;
733   int status;
734   size_t i;
736   /* Protocol example: {{{
737    * ->  STATS
738    * <-  5 Statistics follow
739    * <-  QueueLength: 0
740    * <-  UpdatesWritten: 0
741    * <-  DataSetsWritten: 0
742    * <-  TreeNodesNumber: 0
743    * <-  TreeDepth: 0
744    * }}} */
746   res = NULL;
747   pthread_mutex_lock (&lock);
748   status = request ("STATS\n", strlen ("STATS\n"), &res);
749   pthread_mutex_unlock (&lock);
751   if (status != 0)
752     return (status);
754   if (res->status <= 0)
755   {
756     response_free (res);
757     return (EIO);
758   }
760   head = NULL;
761   tail = NULL;
762   for (i = 0; i < res->lines_num; i++)
763   {
764     char *key;
765     char *value;
766     char *endptr;
767     rrdc_stats_t *s;
769     key = res->lines[i];
770     value = strchr (key, ':');
771     if (value == NULL)
772       continue;
773     *value = 0;
774     value++;
776     while ((value[0] == ' ') || (value[0] == '\t'))
777       value++;
779     s = (rrdc_stats_t *) malloc (sizeof (rrdc_stats_t));
780     if (s == NULL)
781       continue;
782     memset (s, 0, sizeof (*s));
784     s->name = strdup (key);
786     endptr = NULL;
787     if ((strcmp ("QueueLength", key) == 0)
788         || (strcmp ("TreeDepth", key) == 0)
789         || (strcmp ("TreeNodesNumber", key) == 0))
790     {
791       s->type = RRDC_STATS_TYPE_GAUGE;
792       s->value.gauge = strtod (value, &endptr);
793     }
794     else if ((strcmp ("DataSetsWritten", key) == 0)
795         || (strcmp ("FlushesReceived", key) == 0)
796         || (strcmp ("JournalBytes", key) == 0)
797         || (strcmp ("JournalRotate", key) == 0)
798         || (strcmp ("UpdatesReceived", key) == 0)
799         || (strcmp ("UpdatesWritten", key) == 0))
800     {
801       s->type = RRDC_STATS_TYPE_COUNTER;
802       s->value.counter = (uint64_t) strtoll (value, &endptr, /* base = */ 0);
803     }
804     else
805     {
806       free (s);
807       continue;
808     }
810     /* Conversion failed */
811     if (endptr == value)
812     {
813       free (s);
814       continue;
815     }
817     if (head == NULL)
818     {
819       head = s;
820       tail = s;
821       s->next = NULL;
822     }
823     else
824     {
825       tail->next = s;
826       tail = s;
827     }
828   } /* for (i = 0; i < res->lines_num; i++) */
830   response_free (res);
832   if (head == NULL)
833     return (EPROTO);
835   *ret_stats = head;
836   return (0);
837 } /* }}} int rrdc_stats_get */
839 void rrdc_stats_free (rrdc_stats_t *ret_stats) /* {{{ */
841   rrdc_stats_t *this;
843   this = ret_stats;
844   while (this != NULL)
845   {
846     rrdc_stats_t *next;
848     next = this->next;
850     if (this->name != NULL)
851     {
852       free ((char *)this->name);
853       this->name = NULL;
854     }
855     free (this);
857     this = next;
858   } /* while (this != NULL) */
859 } /* }}} void rrdc_stats_free */
861 /*
862  * vim: set sw=2 sts=2 ts=8 et fdm=marker :
863  */