2 * RRDTool - src/rrd_client.c
3 * Copyright (C) 2008 Florian octo Forster
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.
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.
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
19 * Florian octo Forster <octo at verplant.org>
20 * Sebastian tokkee Harl <sh at tokkee.org>
25 #include "rrd_client.h"
33 #include <sys/types.h>
34 #include <sys/socket.h>
40 #define ENODATA ENOENT
43 struct rrdc_response_s
50 typedef struct rrdc_response_s rrdc_response_t;
52 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
54 static FILE *sh = NULL;
55 static char *sd_path = NULL; /* cache the path for sd */
57 /* get_path: Return a path name appropriate to be sent to the daemon.
59 * When talking to a local daemon (thru a UNIX socket), relative path names
60 * are resolved to absolute path names to allow for transparent integration
61 * into existing solutions (as requested by Tobi). Else, absolute path names
62 * are not allowed, since path name translation is done by the server.
64 * One must hold `lock' when calling this function. */
65 static const char *get_path (const char *path, char *resolved_path) /* {{{ */
67 const char *ret = path;
71 || (strncmp ("unix:", sd_path, strlen ("unix:")) == 0))
74 if (*path == '/') /* absolute path */
78 rrd_set_error ("absolute path names not allowed when talking "
79 "to a remote daemon");
82 /* else: nothing to do */
84 else /* relative path */
88 realpath (path, resolved_path);
91 /* else: nothing to do */
94 } /* }}} char *get_path */
96 /* One must hold `lock' when calling `close_connection'. */
97 static void close_connection (void) /* {{{ */
114 } /* }}} void close_connection */
116 static int buffer_add_string (const char *str, /* {{{ */
117 char **buffer_ret, size_t *buffer_size_ret)
125 buffer = *buffer_ret;
126 buffer_size = *buffer_size_ret;
131 while (buffer_pos < buffer_size)
135 buffer[buffer_pos] = ' ';
140 else if ((str[i] == ' ') || (str[i] == '\\'))
142 if (buffer_pos >= (buffer_size - 1))
144 buffer[buffer_pos] = '\\';
146 buffer[buffer_pos] = str[i];
151 buffer[buffer_pos] = str[i];
155 } /* while (buffer_pos < buffer_size) */
160 *buffer_ret = buffer + buffer_pos;
161 *buffer_size_ret = buffer_size - buffer_pos;
164 } /* }}} int buffer_add_string */
166 static int buffer_add_value (const char *value, /* {{{ */
167 char **buffer_ret, size_t *buffer_size_ret)
171 if (strncmp (value, "N:", 2) == 0)
172 snprintf (temp, sizeof (temp), "%lu:%s",
173 (unsigned long) time (NULL), value + 2);
175 strncpy (temp, value, sizeof (temp));
176 temp[sizeof (temp) - 1] = 0;
178 return (buffer_add_string (temp, buffer_ret, buffer_size_ret));
179 } /* }}} int buffer_add_value */
181 /* Remove trailing newline (NL) and carriage return (CR) characters. Similar to
182 * the Perl function `chomp'. Returns the number of characters that have been
184 static int chomp (char *str) /* {{{ */
194 while ((len > 0) && ((str[len - 1] == '\n') || (str[len - 1] == '\r')))
202 } /* }}} int chomp */
204 static void response_free (rrdc_response_t *res) /* {{{ */
209 if (res->lines != NULL)
213 for (i = 0; i < res->lines_num; i++)
214 if (res->lines[i] != NULL)
215 free (res->lines[i]);
220 } /* }}} void response_free */
222 static int response_read (rrdc_response_t **ret_response) /* {{{ */
224 rrdc_response_t *ret;
234 ret = (rrdc_response_t *) malloc (sizeof (rrdc_response_t));
237 memset (ret, 0, sizeof (*ret));
241 buffer_ptr = fgets (buffer, sizeof (buffer), sh);
242 if (buffer_ptr == NULL)
246 ret->status = strtol (buffer, &ret->message, 0);
247 if (buffer == ret->message)
252 /* Skip leading whitespace of the status message */
253 ret->message += strspn (ret->message, " \t");
255 if (ret->status <= 0)
258 rrd_set_error("rrdcached: %s", ret->message);
263 ret->lines = (char **) malloc (sizeof (char *) * ret->status);
264 if (ret->lines == NULL)
269 memset (ret->lines, 0, sizeof (char *) * ret->status);
270 ret->lines_num = (size_t) ret->status;
272 for (i = 0; i < ret->lines_num; i++)
274 buffer_ptr = fgets (buffer, sizeof (buffer), sh);
275 if (buffer_ptr == NULL)
282 ret->lines[i] = strdup (buffer);
283 if (ret->lines[i] == NULL)
292 } /* }}} rrdc_response_t *response_read */
294 static int request (const char *buffer, size_t buffer_size, /* {{{ */
295 rrdc_response_t **ret_response)
298 rrdc_response_t *res;
303 status = (int) fwrite (buffer, buffer_size, /* nmemb = */ 1, sh);
307 rrd_set_error("request: socket error (%d) while talking to rrdcached",
314 status = response_read (&res);
319 rrd_set_error("request: internal error while talking to rrdcached");
325 } /* }}} int request */
327 /* determine whether we are connected to the specified daemon_addr if
328 * NULL, return whether we are connected at all
330 int rrdc_is_connected(const char *daemon_addr) /* {{{ */
334 else if (daemon_addr == NULL)
336 /* here we have to handle the case i.e.
337 * UPDATE --daemon ...; UPDATEV (no --daemon) ...
338 * In other words: we have a cached connection,
339 * but it is not specified in the current command.
340 * Daemon is only implied in this case if set in ENV
342 if (getenv(ENV_RRDCACHED_ADDRESS) != NULL)
347 else if (strcmp(daemon_addr, sd_path) == 0)
352 } /* }}} int rrdc_is_connected */
354 static int rrdc_connect_unix (const char *path) /* {{{ */
356 struct sockaddr_un sa;
359 assert (path != NULL);
362 sd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
369 memset (&sa, 0, sizeof (sa));
370 sa.sun_family = AF_UNIX;
371 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
373 status = connect (sd, (struct sockaddr *) &sa, sizeof (sa));
381 sh = fdopen (sd, "r+");
390 } /* }}} int rrdc_connect_unix */
392 static int rrdc_connect_network (const char *addr_orig) /* {{{ */
394 struct addrinfo ai_hints;
395 struct addrinfo *ai_res;
396 struct addrinfo *ai_ptr;
397 char addr_copy[NI_MAXHOST];
401 assert (addr_orig != NULL);
404 strncpy(addr_copy, addr_orig, sizeof(addr_copy));
405 addr_copy[sizeof(addr_copy) - 1] = '\0';
409 memset (&ai_hints, 0, sizeof (ai_hints));
410 ai_hints.ai_flags = 0;
412 ai_hints.ai_flags |= AI_ADDRCONFIG;
414 ai_hints.ai_family = AF_UNSPEC;
415 ai_hints.ai_socktype = SOCK_STREAM;
418 if (*addr == '[') /* IPv6+port format */
420 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
423 port = strchr (addr, ']');
426 rrd_set_error("malformed address: %s", addr_orig);
438 rrd_set_error("garbage after address: %s", port);
441 } /* if (*addr == '[') */
444 port = rindex(addr, ':');
453 status = getaddrinfo (addr,
454 port == NULL ? RRDCACHED_DEFAULT_PORT : port,
458 rrd_set_error ("failed to resolve address `%s' (port %s): %s",
459 addr, port == NULL ? RRDCACHED_DEFAULT_PORT : port,
460 gai_strerror (status));
464 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
466 sd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
474 status = connect (sd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
482 sh = fdopen (sd, "r+");
490 assert (status == 0);
495 } /* }}} int rrdc_connect_network */
497 int rrdc_connect (const char *addr) /* {{{ */
502 addr = getenv (ENV_RRDCACHED_ADDRESS);
507 pthread_mutex_lock(&lock);
509 if (sd >= 0 && sd_path != NULL && strcmp(addr, sd_path) == 0)
511 /* connection to the same daemon; use cached connection */
512 pthread_mutex_unlock (&lock);
521 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
522 status = rrdc_connect_unix (addr + strlen ("unix:"));
523 else if (addr[0] == '/')
524 status = rrdc_connect_unix (addr);
526 status = rrdc_connect_network(addr);
528 if (status == 0 && sd >= 0)
529 sd_path = strdup(addr);
532 char *err = rrd_test_error () ? rrd_get_error () : "Internal error";
533 /* err points the string that gets written to by rrd_set_error(), thus we
534 * cannot pass it to that function */
536 rrd_set_error("Unable to connect to rrdcached: %s",
538 ? (err ? err : "Internal error")
539 : rrd_strerror (status));
544 pthread_mutex_unlock (&lock);
546 } /* }}} int rrdc_connect */
548 int rrdc_disconnect (void) /* {{{ */
550 pthread_mutex_lock (&lock);
554 pthread_mutex_unlock (&lock);
557 } /* }}} int rrdc_disconnect */
559 int rrdc_update (const char *filename, int values_num, /* {{{ */
560 const char * const *values)
566 rrdc_response_t *res;
569 char file_path[PATH_MAX];
571 memset (buffer, 0, sizeof (buffer));
572 buffer_ptr = &buffer[0];
573 buffer_free = sizeof (buffer);
575 status = buffer_add_string ("update", &buffer_ptr, &buffer_free);
579 pthread_mutex_lock (&lock);
580 filename = get_path (filename, file_path);
581 if (filename == NULL)
583 pthread_mutex_unlock (&lock);
587 status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
590 pthread_mutex_unlock (&lock);
594 for (i = 0; i < values_num; i++)
596 status = buffer_add_value (values[i], &buffer_ptr, &buffer_free);
599 pthread_mutex_unlock (&lock);
604 assert (buffer_free < sizeof (buffer));
605 buffer_size = sizeof (buffer) - buffer_free;
606 assert (buffer[buffer_size - 1] == ' ');
607 buffer[buffer_size - 1] = '\n';
610 status = request (buffer, buffer_size, &res);
611 pthread_mutex_unlock (&lock);
616 status = res->status;
620 } /* }}} int rrdc_update */
622 int rrdc_flush (const char *filename) /* {{{ */
628 rrdc_response_t *res;
630 char file_path[PATH_MAX];
632 if (filename == NULL)
635 memset (buffer, 0, sizeof (buffer));
636 buffer_ptr = &buffer[0];
637 buffer_free = sizeof (buffer);
639 status = buffer_add_string ("flush", &buffer_ptr, &buffer_free);
643 pthread_mutex_lock (&lock);
644 filename = get_path (filename, file_path);
645 if (filename == NULL)
647 pthread_mutex_unlock (&lock);
651 status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
654 pthread_mutex_unlock (&lock);
658 assert (buffer_free < sizeof (buffer));
659 buffer_size = sizeof (buffer) - buffer_free;
660 assert (buffer[buffer_size - 1] == ' ');
661 buffer[buffer_size - 1] = '\n';
664 status = request (buffer, buffer_size, &res);
665 pthread_mutex_unlock (&lock);
670 status = res->status;
674 } /* }}} int rrdc_flush */
677 /* convenience function; if there is a daemon specified, or if we can
678 * detect one from the environment, then flush the file. Otherwise, no-op
680 int rrdc_flush_if_daemon (const char *opt_daemon, const char *filename) /* {{{ */
684 rrdc_connect(opt_daemon);
686 if (rrdc_is_connected(opt_daemon))
689 status = rrdc_flush (filename);
691 if (status != 0 && !rrd_test_error())
695 rrd_set_error("rrdc_flush (%s) failed: %s",
696 filename, rrd_strerror(status));
700 rrd_set_error("rrdc_flush (%s) failed with status %i.",
704 } /* if (rrdc_is_connected(..)) */
707 } /* }}} int rrdc_flush_if_daemon */
710 int rrdc_stats_get (rrdc_stats_t **ret_stats) /* {{{ */
715 rrdc_response_t *res;
720 /* Protocol example: {{{
722 * <- 5 Statistics follow
724 * <- UpdatesWritten: 0
725 * <- DataSetsWritten: 0
726 * <- TreeNodesNumber: 0
731 pthread_mutex_lock (&lock);
732 status = request ("STATS\n", strlen ("STATS\n"), &res);
733 pthread_mutex_unlock (&lock);
738 if (res->status <= 0)
746 for (i = 0; i < res->lines_num; i++)
754 value = strchr (key, ':');
760 while ((value[0] == ' ') || (value[0] == '\t'))
763 s = (rrdc_stats_t *) malloc (sizeof (rrdc_stats_t));
766 memset (s, 0, sizeof (*s));
768 s->name = strdup (key);
771 if ((strcmp ("QueueLength", key) == 0)
772 || (strcmp ("TreeDepth", key) == 0)
773 || (strcmp ("TreeNodesNumber", key) == 0))
775 s->type = RRDC_STATS_TYPE_GAUGE;
776 s->value.gauge = strtod (value, &endptr);
778 else if ((strcmp ("DataSetsWritten", key) == 0)
779 || (strcmp ("FlushesReceived", key) == 0)
780 || (strcmp ("JournalBytes", key) == 0)
781 || (strcmp ("JournalRotate", key) == 0)
782 || (strcmp ("UpdatesReceived", key) == 0)
783 || (strcmp ("UpdatesWritten", key) == 0))
785 s->type = RRDC_STATS_TYPE_COUNTER;
786 s->value.counter = (uint64_t) strtoll (value, &endptr, /* base = */ 0);
794 /* Conversion failed */
812 } /* for (i = 0; i < res->lines_num; i++) */
821 } /* }}} int rrdc_stats_get */
823 void rrdc_stats_free (rrdc_stats_t *ret_stats) /* {{{ */
834 if (this->name != NULL)
836 free ((char *)this->name);
842 } /* while (this != NULL) */
843 } /* }}} void rrdc_stats_free */
846 * vim: set sw=2 sts=2 ts=8 et fdm=marker :