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) /* {{{ */
105 {
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)
125 {
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)
175 {
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) /* {{{ */
192 {
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) /* {{{ */
212 {
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) /* {{{ */
230 {
231 rrdc_response_t *ret;
233 char buffer[4096];
234 char *buffer_ptr;
236 size_t i;
238 if (sh == NULL)
239 return (-1);
241 ret = (rrdc_response_t *) malloc (sizeof (rrdc_response_t));
242 if (ret == NULL)
243 return (-2);
244 memset (ret, 0, sizeof (*ret));
245 ret->lines = NULL;
246 ret->lines_num = 0;
248 buffer_ptr = fgets (buffer, sizeof (buffer), sh);
249 if (buffer_ptr == NULL) {
250 close_connection();
251 return (-3);
252 }
253 chomp (buffer);
255 ret->status = strtol (buffer, &ret->message, 0);
256 if (buffer == ret->message)
257 {
258 response_free (ret);
259 close_connection();
260 return (-4);
261 }
262 /* Skip leading whitespace of the status message */
263 ret->message += strspn (ret->message, " \t");
265 if (ret->status <= 0)
266 {
267 if (ret->status < 0)
268 rrd_set_error("rrdcached: %s", ret->message);
269 *ret_response = ret;
270 return (0);
271 }
273 ret->lines = (char **) malloc (sizeof (char *) * ret->status);
274 if (ret->lines == NULL)
275 {
276 response_free (ret);
277 close_connection();
278 return (-5);
279 }
280 memset (ret->lines, 0, sizeof (char *) * ret->status);
281 ret->lines_num = (size_t) ret->status;
283 for (i = 0; i < ret->lines_num; i++)
284 {
285 buffer_ptr = fgets (buffer, sizeof (buffer), sh);
286 if (buffer_ptr == NULL)
287 {
288 response_free (ret);
289 close_connection();
290 return (-6);
291 }
292 chomp (buffer);
294 ret->lines[i] = strdup (buffer);
295 if (ret->lines[i] == NULL)
296 {
297 response_free (ret);
298 close_connection();
299 return (-7);
300 }
301 }
303 *ret_response = ret;
304 return (0);
305 } /* }}} rrdc_response_t *response_read */
307 static int request (const char *buffer, size_t buffer_size, /* {{{ */
308 rrdc_response_t **ret_response)
309 {
310 int status;
311 rrdc_response_t *res;
313 if (sh == NULL)
314 return (ENOTCONN);
316 status = (int) fwrite (buffer, buffer_size, /* nmemb = */ 1, sh);
317 if (status != 1)
318 {
319 close_connection ();
320 rrd_set_error("request: socket error (%d) while talking to rrdcached",
321 status);
322 return (-1);
323 }
324 fflush (sh);
326 res = NULL;
327 status = response_read (&res);
329 if (status != 0)
330 {
331 if (status < 0)
332 rrd_set_error("request: internal error while talking to rrdcached");
333 return (status);
334 }
336 *ret_response = res;
337 return (0);
338 } /* }}} int request */
340 /* determine whether we are connected to the specified daemon_addr if
341 * NULL, return whether we are connected at all
342 */
343 int rrdc_is_connected(const char *daemon_addr) /* {{{ */
344 {
345 if (sd < 0)
346 return 0;
347 else if (daemon_addr == NULL)
348 {
349 /* here we have to handle the case i.e.
350 * UPDATE --daemon ...; UPDATEV (no --daemon) ...
351 * In other words: we have a cached connection,
352 * but it is not specified in the current command.
353 * Daemon is only implied in this case if set in ENV
354 */
355 if (getenv(ENV_RRDCACHED_ADDRESS) != NULL)
356 return 1;
357 else
358 return 0;
359 }
360 else if (strcmp(daemon_addr, sd_path) == 0)
361 return 1;
362 else
363 return 0;
365 } /* }}} int rrdc_is_connected */
367 static int rrdc_connect_unix (const char *path) /* {{{ */
368 {
369 struct sockaddr_un sa;
370 int status;
372 assert (path != NULL);
373 assert (sd == -1);
375 sd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
376 if (sd < 0)
377 {
378 status = errno;
379 return (status);
380 }
382 memset (&sa, 0, sizeof (sa));
383 sa.sun_family = AF_UNIX;
384 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
386 status = connect (sd, (struct sockaddr *) &sa, sizeof (sa));
387 if (status != 0)
388 {
389 status = errno;
390 close_connection ();
391 return (status);
392 }
394 sh = fdopen (sd, "r+");
395 if (sh == NULL)
396 {
397 status = errno;
398 close_connection ();
399 return (status);
400 }
402 return (0);
403 } /* }}} int rrdc_connect_unix */
405 static int rrdc_connect_network (const char *addr_orig) /* {{{ */
406 {
407 struct addrinfo ai_hints;
408 struct addrinfo *ai_res;
409 struct addrinfo *ai_ptr;
410 char addr_copy[NI_MAXHOST];
411 char *addr;
412 char *port;
414 assert (addr_orig != NULL);
415 assert (sd == -1);
417 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
418 addr_copy[sizeof(addr_copy) - 1] = '\0';
419 addr = addr_copy;
421 int status;
422 memset (&ai_hints, 0, sizeof (ai_hints));
423 ai_hints.ai_flags = 0;
424 #ifdef AI_ADDRCONFIG
425 ai_hints.ai_flags |= AI_ADDRCONFIG;
426 #endif
427 ai_hints.ai_family = AF_UNSPEC;
428 ai_hints.ai_socktype = SOCK_STREAM;
430 port = NULL;
431 if (*addr == '[') /* IPv6+port format */
432 {
433 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
434 addr++;
436 port = strchr (addr, ']');
437 if (port == NULL)
438 {
439 rrd_set_error("malformed address: %s", addr_orig);
440 return (-1);
441 }
442 *port = 0;
443 port++;
445 if (*port == ':')
446 port++;
447 else if (*port == 0)
448 port = NULL;
449 else
450 {
451 rrd_set_error("garbage after address: %s", port);
452 return (-1);
453 }
454 } /* if (*addr == '[') */
455 else
456 {
457 port = rindex(addr, ':');
458 if (port != NULL)
459 {
460 *port = 0;
461 port++;
462 }
463 }
465 ai_res = NULL;
466 status = getaddrinfo (addr,
467 port == NULL ? RRDCACHED_DEFAULT_PORT : port,
468 &ai_hints, &ai_res);
469 if (status != 0)
470 {
471 rrd_set_error ("failed to resolve address `%s' (port %s): %s",
472 addr, port == NULL ? RRDCACHED_DEFAULT_PORT : port,
473 gai_strerror (status));
474 return (-1);
475 }
477 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
478 {
479 sd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
480 if (sd < 0)
481 {
482 status = errno;
483 sd = -1;
484 continue;
485 }
487 status = connect (sd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
488 if (status != 0)
489 {
490 status = errno;
491 close_connection();
492 continue;
493 }
495 sh = fdopen (sd, "r+");
496 if (sh == NULL)
497 {
498 status = errno;
499 close_connection ();
500 continue;
501 }
503 assert (status == 0);
504 break;
505 } /* for (ai_ptr) */
507 return (status);
508 } /* }}} int rrdc_connect_network */
510 int rrdc_connect (const char *addr) /* {{{ */
511 {
512 int status = 0;
514 if (addr == NULL)
515 addr = getenv (ENV_RRDCACHED_ADDRESS);
517 if (addr == NULL)
518 return 0;
520 pthread_mutex_lock(&lock);
522 if (sd >= 0 && sd_path != NULL && strcmp(addr, sd_path) == 0)
523 {
524 /* connection to the same daemon; use cached connection */
525 pthread_mutex_unlock (&lock);
526 return (0);
527 }
528 else
529 {
530 close_connection();
531 }
533 rrd_clear_error ();
534 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
535 status = rrdc_connect_unix (addr + strlen ("unix:"));
536 else if (addr[0] == '/')
537 status = rrdc_connect_unix (addr);
538 else
539 status = rrdc_connect_network(addr);
541 if (status == 0 && sd >= 0)
542 sd_path = strdup(addr);
543 else
544 {
545 char *err = rrd_test_error () ? rrd_get_error () : "Internal error";
546 /* err points the string that gets written to by rrd_set_error(), thus we
547 * cannot pass it to that function */
548 err = strdup (err);
549 rrd_set_error("Unable to connect to rrdcached: %s",
550 (status < 0)
551 ? (err ? err : "Internal error")
552 : rrd_strerror (status));
553 if (err != NULL)
554 free (err);
555 }
557 pthread_mutex_unlock (&lock);
558 return (status);
559 } /* }}} int rrdc_connect */
561 int rrdc_disconnect (void) /* {{{ */
562 {
563 pthread_mutex_lock (&lock);
565 close_connection();
567 pthread_mutex_unlock (&lock);
569 return (0);
570 } /* }}} int rrdc_disconnect */
572 int rrdc_update (const char *filename, int values_num, /* {{{ */
573 const char * const *values)
574 {
575 char buffer[4096];
576 char *buffer_ptr;
577 size_t buffer_free;
578 size_t buffer_size;
579 rrdc_response_t *res;
580 int status;
581 int i;
582 char file_path[PATH_MAX];
584 memset (buffer, 0, sizeof (buffer));
585 buffer_ptr = &buffer[0];
586 buffer_free = sizeof (buffer);
588 status = buffer_add_string ("update", &buffer_ptr, &buffer_free);
589 if (status != 0)
590 return (ENOBUFS);
592 pthread_mutex_lock (&lock);
593 filename = get_path (filename, file_path);
594 if (filename == NULL)
595 {
596 pthread_mutex_unlock (&lock);
597 return (-1);
598 }
600 status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
601 if (status != 0)
602 {
603 pthread_mutex_unlock (&lock);
604 return (ENOBUFS);
605 }
607 for (i = 0; i < values_num; i++)
608 {
609 status = buffer_add_value (values[i], &buffer_ptr, &buffer_free);
610 if (status != 0)
611 {
612 pthread_mutex_unlock (&lock);
613 return (ENOBUFS);
614 }
615 }
617 assert (buffer_free < sizeof (buffer));
618 buffer_size = sizeof (buffer) - buffer_free;
619 assert (buffer[buffer_size - 1] == ' ');
620 buffer[buffer_size - 1] = '\n';
622 res = NULL;
623 status = request (buffer, buffer_size, &res);
624 pthread_mutex_unlock (&lock);
626 if (status != 0)
627 return (status);
629 status = res->status;
630 response_free (res);
632 return (status);
633 } /* }}} int rrdc_update */
635 int rrdc_flush (const char *filename) /* {{{ */
636 {
637 char buffer[4096];
638 char *buffer_ptr;
639 size_t buffer_free;
640 size_t buffer_size;
641 rrdc_response_t *res;
642 int status;
643 char file_path[PATH_MAX];
645 if (filename == NULL)
646 return (-1);
648 memset (buffer, 0, sizeof (buffer));
649 buffer_ptr = &buffer[0];
650 buffer_free = sizeof (buffer);
652 status = buffer_add_string ("flush", &buffer_ptr, &buffer_free);
653 if (status != 0)
654 return (ENOBUFS);
656 pthread_mutex_lock (&lock);
657 filename = get_path (filename, file_path);
658 if (filename == NULL)
659 {
660 pthread_mutex_unlock (&lock);
661 return (-1);
662 }
664 status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
665 if (status != 0)
666 {
667 pthread_mutex_unlock (&lock);
668 return (ENOBUFS);
669 }
671 assert (buffer_free < sizeof (buffer));
672 buffer_size = sizeof (buffer) - buffer_free;
673 assert (buffer[buffer_size - 1] == ' ');
674 buffer[buffer_size - 1] = '\n';
676 res = NULL;
677 status = request (buffer, buffer_size, &res);
678 pthread_mutex_unlock (&lock);
680 if (status != 0)
681 return (status);
683 status = res->status;
684 response_free (res);
686 return (status);
687 } /* }}} int rrdc_flush */
690 /* convenience function; if there is a daemon specified, or if we can
691 * detect one from the environment, then flush the file. Otherwise, no-op
692 */
693 int rrdc_flush_if_daemon (const char *opt_daemon, const char *filename) /* {{{ */
694 {
695 int status = 0;
697 rrdc_connect(opt_daemon);
699 if (rrdc_is_connected(opt_daemon))
700 {
701 rrd_clear_error();
702 status = rrdc_flush (filename);
704 if (status != 0 && !rrd_test_error())
705 {
706 if (status > 0)
707 {
708 rrd_set_error("rrdc_flush (%s) failed: %s",
709 filename, rrd_strerror(status));
710 }
711 else if (status < 0)
712 {
713 rrd_set_error("rrdc_flush (%s) failed with status %i.",
714 filename, status);
715 }
716 }
717 } /* if (rrdc_is_connected(..)) */
719 return status;
720 } /* }}} int rrdc_flush_if_daemon */
723 int rrdc_stats_get (rrdc_stats_t **ret_stats) /* {{{ */
724 {
725 rrdc_stats_t *head;
726 rrdc_stats_t *tail;
728 rrdc_response_t *res;
730 int status;
731 size_t i;
733 /* Protocol example: {{{
734 * -> STATS
735 * <- 5 Statistics follow
736 * <- QueueLength: 0
737 * <- UpdatesWritten: 0
738 * <- DataSetsWritten: 0
739 * <- TreeNodesNumber: 0
740 * <- TreeDepth: 0
741 * }}} */
743 res = NULL;
744 pthread_mutex_lock (&lock);
745 status = request ("STATS\n", strlen ("STATS\n"), &res);
746 pthread_mutex_unlock (&lock);
748 if (status != 0)
749 return (status);
751 if (res->status <= 0)
752 {
753 response_free (res);
754 return (EIO);
755 }
757 head = NULL;
758 tail = NULL;
759 for (i = 0; i < res->lines_num; i++)
760 {
761 char *key;
762 char *value;
763 char *endptr;
764 rrdc_stats_t *s;
766 key = res->lines[i];
767 value = strchr (key, ':');
768 if (value == NULL)
769 continue;
770 *value = 0;
771 value++;
773 while ((value[0] == ' ') || (value[0] == '\t'))
774 value++;
776 s = (rrdc_stats_t *) malloc (sizeof (rrdc_stats_t));
777 if (s == NULL)
778 continue;
779 memset (s, 0, sizeof (*s));
781 s->name = strdup (key);
783 endptr = NULL;
784 if ((strcmp ("QueueLength", key) == 0)
785 || (strcmp ("TreeDepth", key) == 0)
786 || (strcmp ("TreeNodesNumber", key) == 0))
787 {
788 s->type = RRDC_STATS_TYPE_GAUGE;
789 s->value.gauge = strtod (value, &endptr);
790 }
791 else if ((strcmp ("DataSetsWritten", key) == 0)
792 || (strcmp ("FlushesReceived", key) == 0)
793 || (strcmp ("JournalBytes", key) == 0)
794 || (strcmp ("JournalRotate", key) == 0)
795 || (strcmp ("UpdatesReceived", key) == 0)
796 || (strcmp ("UpdatesWritten", key) == 0))
797 {
798 s->type = RRDC_STATS_TYPE_COUNTER;
799 s->value.counter = (uint64_t) strtoll (value, &endptr, /* base = */ 0);
800 }
801 else
802 {
803 free (s);
804 continue;
805 }
807 /* Conversion failed */
808 if (endptr == value)
809 {
810 free (s);
811 continue;
812 }
814 if (head == NULL)
815 {
816 head = s;
817 tail = s;
818 s->next = NULL;
819 }
820 else
821 {
822 tail->next = s;
823 tail = s;
824 }
825 } /* for (i = 0; i < res->lines_num; i++) */
827 response_free (res);
829 if (head == NULL)
830 return (EPROTO);
832 *ret_stats = head;
833 return (0);
834 } /* }}} int rrdc_stats_get */
836 void rrdc_stats_free (rrdc_stats_t *ret_stats) /* {{{ */
837 {
838 rrdc_stats_t *this;
840 this = ret_stats;
841 while (this != NULL)
842 {
843 rrdc_stats_t *next;
845 next = this->next;
847 if (this->name != NULL)
848 {
849 free ((char *)this->name);
850 this->name = NULL;
851 }
852 free (this);
854 this = next;
855 } /* while (this != NULL) */
856 } /* }}} void rrdc_stats_free */
858 /*
859 * vim: set sw=2 sts=2 ts=8 et fdm=marker :
860 */