47333df099a1495737e4fb4afdbee6986d6d93db
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 = 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)
307 {
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) /* {{{ */
342 {
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) /* {{{ */
366 {
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) /* {{{ */
404 {
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 return (status);
506 } /* }}} int rrdc_connect_network */
508 int rrdc_connect (const char *addr) /* {{{ */
509 {
510 int status = 0;
512 if (addr == NULL)
513 addr = getenv (ENV_RRDCACHED_ADDRESS);
515 if (addr == NULL)
516 return 0;
518 pthread_mutex_lock(&lock);
520 if (sd >= 0 && sd_path != NULL && strcmp(addr, sd_path) == 0)
521 {
522 /* connection to the same daemon; use cached connection */
523 pthread_mutex_unlock (&lock);
524 return (0);
525 }
526 else
527 {
528 close_connection();
529 }
531 rrd_clear_error ();
532 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
533 status = rrdc_connect_unix (addr + strlen ("unix:"));
534 else if (addr[0] == '/')
535 status = rrdc_connect_unix (addr);
536 else
537 status = rrdc_connect_network(addr);
539 if (status == 0 && sd >= 0)
540 sd_path = strdup(addr);
541 else
542 {
543 char *err = rrd_test_error () ? rrd_get_error () : "Internal error";
544 /* err points the string that gets written to by rrd_set_error(), thus we
545 * cannot pass it to that function */
546 err = strdup (err);
547 rrd_set_error("Unable to connect to rrdcached: %s",
548 (status < 0)
549 ? (err ? err : "Internal error")
550 : rrd_strerror (status));
551 if (err != NULL)
552 free (err);
553 }
555 pthread_mutex_unlock (&lock);
556 return (status);
557 } /* }}} int rrdc_connect */
559 int rrdc_disconnect (void) /* {{{ */
560 {
561 pthread_mutex_lock (&lock);
563 close_connection();
565 pthread_mutex_unlock (&lock);
567 return (0);
568 } /* }}} int rrdc_disconnect */
570 int rrdc_update (const char *filename, int values_num, /* {{{ */
571 const char * const *values)
572 {
573 char buffer[4096];
574 char *buffer_ptr;
575 size_t buffer_free;
576 size_t buffer_size;
577 rrdc_response_t *res;
578 int status;
579 int i;
580 char file_path[PATH_MAX];
582 memset (buffer, 0, sizeof (buffer));
583 buffer_ptr = &buffer[0];
584 buffer_free = sizeof (buffer);
586 status = buffer_add_string ("update", &buffer_ptr, &buffer_free);
587 if (status != 0)
588 return (ENOBUFS);
590 pthread_mutex_lock (&lock);
591 filename = get_path (filename, file_path);
592 if (filename == NULL)
593 {
594 pthread_mutex_unlock (&lock);
595 return (-1);
596 }
598 status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
599 if (status != 0)
600 {
601 pthread_mutex_unlock (&lock);
602 return (ENOBUFS);
603 }
605 for (i = 0; i < values_num; i++)
606 {
607 status = buffer_add_value (values[i], &buffer_ptr, &buffer_free);
608 if (status != 0)
609 {
610 pthread_mutex_unlock (&lock);
611 return (ENOBUFS);
612 }
613 }
615 assert (buffer_free < sizeof (buffer));
616 buffer_size = sizeof (buffer) - buffer_free;
617 assert (buffer[buffer_size - 1] == ' ');
618 buffer[buffer_size - 1] = '\n';
620 res = NULL;
621 status = request (buffer, buffer_size, &res);
622 pthread_mutex_unlock (&lock);
624 if (status != 0)
625 return (status);
627 status = res->status;
628 response_free (res);
630 return (status);
631 } /* }}} int rrdc_update */
633 int rrdc_flush (const char *filename) /* {{{ */
634 {
635 char buffer[4096];
636 char *buffer_ptr;
637 size_t buffer_free;
638 size_t buffer_size;
639 rrdc_response_t *res;
640 int status;
641 char file_path[PATH_MAX];
643 if (filename == NULL)
644 return (-1);
646 memset (buffer, 0, sizeof (buffer));
647 buffer_ptr = &buffer[0];
648 buffer_free = sizeof (buffer);
650 status = buffer_add_string ("flush", &buffer_ptr, &buffer_free);
651 if (status != 0)
652 return (ENOBUFS);
654 pthread_mutex_lock (&lock);
655 filename = get_path (filename, file_path);
656 if (filename == NULL)
657 {
658 pthread_mutex_unlock (&lock);
659 return (-1);
660 }
662 status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
663 if (status != 0)
664 {
665 pthread_mutex_unlock (&lock);
666 return (ENOBUFS);
667 }
669 assert (buffer_free < sizeof (buffer));
670 buffer_size = sizeof (buffer) - buffer_free;
671 assert (buffer[buffer_size - 1] == ' ');
672 buffer[buffer_size - 1] = '\n';
674 res = NULL;
675 status = request (buffer, buffer_size, &res);
676 pthread_mutex_unlock (&lock);
678 if (status != 0)
679 return (status);
681 status = res->status;
682 response_free (res);
684 return (status);
685 } /* }}} int rrdc_flush */
688 /* convenience function; if there is a daemon specified, or if we can
689 * detect one from the environment, then flush the file. Otherwise, no-op
690 */
691 int rrdc_flush_if_daemon (const char *opt_daemon, const char *filename) /* {{{ */
692 {
693 int status = 0;
695 rrdc_connect(opt_daemon);
697 if (rrdc_is_connected(opt_daemon))
698 {
699 rrd_clear_error();
700 status = rrdc_flush (filename);
702 if (status != 0 && !rrd_test_error())
703 {
704 if (status > 0)
705 {
706 rrd_set_error("rrdc_flush (%s) failed: %s",
707 filename, rrd_strerror(status));
708 }
709 else if (status < 0)
710 {
711 rrd_set_error("rrdc_flush (%s) failed with status %i.",
712 filename, status);
713 }
714 }
715 } /* if (rrdc_is_connected(..)) */
717 return status;
718 } /* }}} int rrdc_flush_if_daemon */
721 int rrdc_stats_get (rrdc_stats_t **ret_stats) /* {{{ */
722 {
723 rrdc_stats_t *head;
724 rrdc_stats_t *tail;
726 rrdc_response_t *res;
728 int status;
729 size_t i;
731 /* Protocol example: {{{
732 * -> STATS
733 * <- 5 Statistics follow
734 * <- QueueLength: 0
735 * <- UpdatesWritten: 0
736 * <- DataSetsWritten: 0
737 * <- TreeNodesNumber: 0
738 * <- TreeDepth: 0
739 * }}} */
741 res = NULL;
742 pthread_mutex_lock (&lock);
743 status = request ("STATS\n", strlen ("STATS\n"), &res);
744 pthread_mutex_unlock (&lock);
746 if (status != 0)
747 return (status);
749 if (res->status <= 0)
750 {
751 response_free (res);
752 return (EIO);
753 }
755 head = NULL;
756 tail = NULL;
757 for (i = 0; i < res->lines_num; i++)
758 {
759 char *key;
760 char *value;
761 char *endptr;
762 rrdc_stats_t *s;
764 key = res->lines[i];
765 value = strchr (key, ':');
766 if (value == NULL)
767 continue;
768 *value = 0;
769 value++;
771 while ((value[0] == ' ') || (value[0] == '\t'))
772 value++;
774 s = (rrdc_stats_t *) malloc (sizeof (rrdc_stats_t));
775 if (s == NULL)
776 continue;
777 memset (s, 0, sizeof (*s));
779 s->name = strdup (key);
781 endptr = NULL;
782 if ((strcmp ("QueueLength", key) == 0)
783 || (strcmp ("TreeDepth", key) == 0)
784 || (strcmp ("TreeNodesNumber", key) == 0))
785 {
786 s->type = RRDC_STATS_TYPE_GAUGE;
787 s->value.gauge = strtod (value, &endptr);
788 }
789 else if ((strcmp ("DataSetsWritten", key) == 0)
790 || (strcmp ("FlushesReceived", key) == 0)
791 || (strcmp ("JournalBytes", key) == 0)
792 || (strcmp ("JournalRotate", key) == 0)
793 || (strcmp ("UpdatesReceived", key) == 0)
794 || (strcmp ("UpdatesWritten", key) == 0))
795 {
796 s->type = RRDC_STATS_TYPE_COUNTER;
797 s->value.counter = (uint64_t) strtoll (value, &endptr, /* base = */ 0);
798 }
799 else
800 {
801 free (s);
802 continue;
803 }
805 /* Conversion failed */
806 if (endptr == value)
807 {
808 free (s);
809 continue;
810 }
812 if (head == NULL)
813 {
814 head = s;
815 tail = s;
816 s->next = NULL;
817 }
818 else
819 {
820 tail->next = s;
821 tail = s;
822 }
823 } /* for (i = 0; i < res->lines_num; i++) */
825 response_free (res);
827 if (head == NULL)
828 return (EPROTO);
830 *ret_stats = head;
831 return (0);
832 } /* }}} int rrdc_stats_get */
834 void rrdc_stats_free (rrdc_stats_t *ret_stats) /* {{{ */
835 {
836 rrdc_stats_t *this;
838 this = ret_stats;
839 while (this != NULL)
840 {
841 rrdc_stats_t *next;
843 next = this->next;
845 if (this->name != NULL)
846 {
847 free ((char *)this->name);
848 this->name = NULL;
849 }
850 free (this);
852 this = next;
853 } /* while (this != NULL) */
854 } /* }}} void rrdc_stats_free */
856 /*
857 * vim: set sw=2 sts=2 ts=8 et fdm=marker :
858 */