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