2 * RRDTool - src/rrd_daemon.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 * kevin brintnall <kbrint@rufus.net>
34 * Now for some includes..
36 #include "rrd.h" /* {{{ */
37 #include "rrd_client.h"
48 #include <sys/types.h>
52 #include <sys/socket.h>
63 #include <glib-2.0/glib.h>
66 #define RRDD_LOG(severity, ...) syslog ((severity), __VA_ARGS__)
69 # define __attribute__(x) /**/
75 struct listen_socket_s
78 char path[PATH_MAX + 1];
80 typedef struct listen_socket_s listen_socket_t;
83 typedef struct cache_item_s cache_item_t;
89 time_t last_flush_time;
90 #define CI_FLAGS_IN_TREE (1<<0)
91 #define CI_FLAGS_IN_QUEUE (1<<1)
97 struct callback_flush_data_s
104 typedef struct callback_flush_data_s callback_flush_data_t;
111 typedef enum queue_side_e queue_side_t;
113 /* max length of socket command or response */
119 static int stay_foreground = 0;
121 static listen_socket_t *listen_fds = NULL;
122 static size_t listen_fds_num = 0;
124 static int do_shutdown = 0;
126 static pthread_t queue_thread;
128 static pthread_t *connection_threads = NULL;
129 static pthread_mutex_t connection_threads_lock = PTHREAD_MUTEX_INITIALIZER;
130 static int connection_threads_num = 0;
133 static GTree *cache_tree = NULL;
134 static cache_item_t *cache_queue_head = NULL;
135 static cache_item_t *cache_queue_tail = NULL;
136 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
137 static pthread_cond_t cache_cond = PTHREAD_COND_INITIALIZER;
139 static pthread_cond_t flush_cond = PTHREAD_COND_INITIALIZER;
141 static int config_write_interval = 300;
142 static int config_write_jitter = 0;
143 static int config_flush_interval = 3600;
144 static char *config_pid_file = NULL;
145 static char *config_base_dir = NULL;
147 static char **config_listen_address_list = NULL;
148 static int config_listen_address_list_len = 0;
150 static uint64_t stats_queue_length = 0;
151 static uint64_t stats_updates_received = 0;
152 static uint64_t stats_flush_received = 0;
153 static uint64_t stats_updates_written = 0;
154 static uint64_t stats_data_sets_written = 0;
155 static uint64_t stats_journal_bytes = 0;
156 static uint64_t stats_journal_rotate = 0;
157 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
159 /* Journaled updates */
160 static char *journal_cur = NULL;
161 static char *journal_old = NULL;
162 static FILE *journal_fh = NULL;
163 static pthread_mutex_t journal_lock = PTHREAD_MUTEX_INITIALIZER;
164 static int journal_write(char *cmd, char *args);
165 static void journal_done(void);
166 static void journal_rotate(void);
171 static void sig_int_handler (int s __attribute__((unused))) /* {{{ */
173 RRDD_LOG(LOG_NOTICE, "caught SIGINT");
175 pthread_cond_broadcast(&cache_cond);
176 } /* }}} void sig_int_handler */
178 static void sig_term_handler (int s __attribute__((unused))) /* {{{ */
180 RRDD_LOG(LOG_NOTICE, "caught SIGTERM");
182 pthread_cond_broadcast(&cache_cond);
183 } /* }}} void sig_term_handler */
185 static int write_pidfile (void) /* {{{ */
194 file = (config_pid_file != NULL)
196 : LOCALSTATEDIR "/run/rrdcached.pid";
198 fd = open(file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IRGRP|S_IROTH);
201 RRDD_LOG(LOG_ERR, "FATAL: cannot create '%s' (%s)",
202 file, rrd_strerror(errno));
206 fh = fdopen (fd, "w");
209 RRDD_LOG (LOG_ERR, "write_pidfile: Opening `%s' failed.", file);
214 fprintf (fh, "%i\n", (int) pid);
218 } /* }}} int write_pidfile */
220 static int remove_pidfile (void) /* {{{ */
225 file = (config_pid_file != NULL)
227 : LOCALSTATEDIR "/run/rrdcached.pid";
229 status = unlink (file);
233 } /* }}} int remove_pidfile */
235 static ssize_t sread (int fd, void *buffer_void, size_t buffer_size) /* {{{ */
242 buffer = (char *) buffer_void;
244 buffer_free = buffer_size;
246 while (buffer_free > 0)
248 status = read (fd, buffer + buffer_used, buffer_free);
249 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
258 assert ((0 > status) || (buffer_free >= (size_t) status));
260 buffer_free = buffer_free - status;
261 buffer_used = buffer_used + status;
263 if (buffer[buffer_used - 1] == '\n')
267 assert (buffer_used > 0);
269 if (buffer[buffer_used - 1] != '\n')
275 buffer[buffer_used - 1] = 0;
277 /* Fix network line endings. */
278 if ((buffer_used > 1) && (buffer[buffer_used - 2] == '\r'))
281 buffer[buffer_used - 1] = 0;
284 return (buffer_used);
285 } /* }}} ssize_t sread */
287 static ssize_t swrite (int fd, const void *buf, size_t count) /* {{{ */
293 /* special case for journal replay */
294 if (fd < 0) return 0;
296 ptr = (const char *) buf;
301 status = write (fd, (const void *) ptr, nleft);
303 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
314 } /* }}} ssize_t swrite */
316 static void _wipe_ci_values(cache_item_t *ci, time_t when)
321 ci->last_flush_time = when;
322 if (config_write_jitter > 0)
323 ci->last_flush_time += (random() % config_write_jitter);
325 ci->flags &= ~(CI_FLAGS_IN_QUEUE);
329 * enqueue_cache_item:
330 * `cache_lock' must be acquired before calling this function!
332 static int enqueue_cache_item (cache_item_t *ci, /* {{{ */
340 if (ci->values_num == 0)
345 if ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
347 assert (ci->next == NULL);
348 ci->next = cache_queue_head;
349 cache_queue_head = ci;
351 if (cache_queue_tail == NULL)
352 cache_queue_tail = cache_queue_head;
356 else if (cache_queue_head == ci)
360 else /* enqueued, but not first entry */
364 /* find previous entry */
365 for (prev = cache_queue_head; prev != NULL; prev = prev->next)
366 if (prev->next == ci)
368 assert (prev != NULL);
370 /* move to the front */
371 prev->next = ci->next;
372 ci->next = cache_queue_head;
373 cache_queue_head = ci;
375 /* check if we need to adapt the tail */
376 if (cache_queue_tail == ci)
377 cache_queue_tail = prev;
380 else /* (side == TAIL) */
382 /* We don't move values back in the list.. */
383 if ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
386 assert (ci->next == NULL);
388 if (cache_queue_tail == NULL)
389 cache_queue_head = ci;
391 cache_queue_tail->next = ci;
392 cache_queue_tail = ci;
397 ci->flags |= CI_FLAGS_IN_QUEUE;
401 pthread_mutex_lock (&stats_lock);
402 stats_queue_length++;
403 pthread_mutex_unlock (&stats_lock);
407 } /* }}} int enqueue_cache_item */
410 * tree_callback_flush:
411 * Called via `g_tree_foreach' in `queue_thread_main'. `cache_lock' is held
412 * while this is in progress.
414 static gboolean tree_callback_flush (gpointer key, gpointer value, /* {{{ */
418 callback_flush_data_t *cfd;
420 ci = (cache_item_t *) value;
421 cfd = (callback_flush_data_t *) data;
423 if ((ci->last_flush_time <= cfd->abs_timeout)
424 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
425 && (ci->values_num > 0))
427 enqueue_cache_item (ci, TAIL);
429 else if ((do_shutdown != 0)
430 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
431 && (ci->values_num > 0))
433 enqueue_cache_item (ci, TAIL);
435 else if (((cfd->now - ci->last_flush_time) >= config_flush_interval)
436 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
437 && (ci->values_num <= 0))
441 temp = (char **) realloc (cfd->keys,
442 sizeof (char *) * (cfd->keys_num + 1));
445 RRDD_LOG (LOG_ERR, "tree_callback_flush: realloc failed.");
449 /* Make really sure this points to the _same_ place */
450 assert ((char *) key == ci->file);
451 cfd->keys[cfd->keys_num] = (char *) key;
456 } /* }}} gboolean tree_callback_flush */
458 static int flush_old_values (int max_age)
460 callback_flush_data_t cfd;
463 memset (&cfd, 0, sizeof (cfd));
464 /* Pass the current time as user data so that we don't need to call
465 * `time' for each node. */
466 cfd.now = time (NULL);
471 cfd.abs_timeout = cfd.now - max_age;
473 cfd.abs_timeout = cfd.now + 1;
475 /* `tree_callback_flush' will return the keys of all values that haven't
476 * been touched in the last `config_flush_interval' seconds in `cfd'.
477 * The char*'s in this array point to the same memory as ci->file, so we
478 * don't need to free them separately. */
479 g_tree_foreach (cache_tree, tree_callback_flush, (gpointer) &cfd);
481 for (k = 0; k < cfd.keys_num; k++)
485 /* This must not fail. */
486 ci = (cache_item_t *) g_tree_lookup (cache_tree, cfd.keys[k]);
489 /* If we end up here with values available, something's seriously
491 assert (ci->values_num == 0);
493 /* Remove the node from the tree */
494 g_tree_remove (cache_tree, cfd.keys[k]);
497 /* Now free and clean up `ci'. */
502 } /* for (k = 0; k < cfd.keys_num; k++) */
504 if (cfd.keys != NULL)
511 } /* int flush_old_values */
513 static void *queue_thread_main (void *args __attribute__((unused))) /* {{{ */
516 struct timespec next_flush;
518 gettimeofday (&now, NULL);
519 next_flush.tv_sec = now.tv_sec + config_flush_interval;
520 next_flush.tv_nsec = 1000 * now.tv_usec;
522 pthread_mutex_lock (&cache_lock);
523 while ((do_shutdown == 0) || (cache_queue_head != NULL))
532 /* First, check if it's time to do the cache flush. */
533 gettimeofday (&now, NULL);
534 if ((now.tv_sec > next_flush.tv_sec)
535 || ((now.tv_sec == next_flush.tv_sec)
536 && ((1000 * now.tv_usec) > next_flush.tv_nsec)))
538 /* Flush all values that haven't been written in the last
539 * `config_write_interval' seconds. */
540 flush_old_values (config_write_interval);
542 /* Determine the time of the next cache flush. */
543 while (next_flush.tv_sec <= now.tv_sec)
544 next_flush.tv_sec += config_flush_interval;
546 /* unlock the cache while we rotate so we don't block incoming
547 * updates if the fsync() blocks on disk I/O */
548 pthread_mutex_unlock(&cache_lock);
550 pthread_mutex_lock(&cache_lock);
553 /* Now, check if there's something to store away. If not, wait until
554 * something comes in or it's time to do the cache flush. */
555 if (cache_queue_head == NULL)
557 status = pthread_cond_timedwait (&cache_cond, &cache_lock, &next_flush);
558 if ((status != 0) && (status != ETIMEDOUT))
560 RRDD_LOG (LOG_ERR, "queue_thread_main: "
561 "pthread_cond_timedwait returned %i.", status);
565 /* We're about to shut down, so lets flush the entire tree. */
566 if ((do_shutdown != 0) && (cache_queue_head == NULL))
567 flush_old_values (/* max age = */ -1);
569 /* Check if a value has arrived. This may be NULL if we timed out or there
570 * was an interrupt such as a signal. */
571 if (cache_queue_head == NULL)
574 ci = cache_queue_head;
576 /* copy the relevant parts */
577 file = strdup (ci->file);
580 RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
584 assert(ci->values != NULL);
585 assert(ci->values_num > 0);
588 values_num = ci->values_num;
590 _wipe_ci_values(ci, time(NULL));
592 cache_queue_head = ci->next;
593 if (cache_queue_head == NULL)
594 cache_queue_tail = NULL;
597 pthread_mutex_lock (&stats_lock);
598 assert (stats_queue_length > 0);
599 stats_queue_length--;
600 pthread_mutex_unlock (&stats_lock);
602 pthread_mutex_unlock (&cache_lock);
605 status = rrd_update_r (file, NULL, values_num, (void *) values);
608 RRDD_LOG (LOG_NOTICE, "queue_thread_main: "
609 "rrd_update_r (%s) failed with status %i. (%s)",
610 file, status, rrd_get_error());
613 journal_write("wrote", file);
615 for (i = 0; i < values_num; i++)
623 pthread_mutex_lock (&stats_lock);
624 stats_updates_written++;
625 stats_data_sets_written += values_num;
626 pthread_mutex_unlock (&stats_lock);
629 pthread_mutex_lock (&cache_lock);
630 pthread_cond_broadcast (&flush_cond);
632 /* We're about to shut down, so lets flush the entire tree. */
633 if ((do_shutdown != 0) && (cache_queue_head == NULL))
634 flush_old_values (/* max age = */ -1);
635 } /* while ((do_shutdown == 0) || (cache_queue_head != NULL)) */
636 pthread_mutex_unlock (&cache_lock);
638 assert(cache_queue_head == NULL);
639 RRDD_LOG(LOG_INFO, "clean shutdown; all RRDs flushed");
643 } /* }}} void *queue_thread_main */
645 static int buffer_get_field (char **buffer_ret, /* {{{ */
646 size_t *buffer_size_ret, char **field_ret)
655 buffer = *buffer_ret;
657 buffer_size = *buffer_size_ret;
661 if (buffer_size <= 0)
664 /* This is ensured by `handle_request'. */
665 assert (buffer[buffer_size - 1] == '\0');
668 while (buffer_pos < buffer_size)
670 /* Check for end-of-field or end-of-buffer */
671 if (buffer[buffer_pos] == ' ' || buffer[buffer_pos] == '\0')
673 field[field_size] = 0;
679 /* Handle escaped characters. */
680 else if (buffer[buffer_pos] == '\\')
682 if (buffer_pos >= (buffer_size - 1))
685 field[field_size] = buffer[buffer_pos];
689 /* Normal operation */
692 field[field_size] = buffer[buffer_pos];
696 } /* while (buffer_pos < buffer_size) */
701 *buffer_ret = buffer + buffer_pos;
702 *buffer_size_ret = buffer_size - buffer_pos;
706 } /* }}} int buffer_get_field */
708 static int flush_file (const char *filename) /* {{{ */
712 pthread_mutex_lock (&cache_lock);
714 ci = (cache_item_t *) g_tree_lookup (cache_tree, filename);
717 pthread_mutex_unlock (&cache_lock);
721 /* Enqueue at head */
722 enqueue_cache_item (ci, HEAD);
723 pthread_cond_signal (&cache_cond);
725 while ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
729 pthread_cond_wait (&flush_cond, &cache_lock);
731 ci = g_tree_lookup (cache_tree, filename);
734 RRDD_LOG (LOG_ERR, "flush_file: Tree node went away "
735 "while waiting for flush.");
736 pthread_mutex_unlock (&cache_lock);
741 pthread_mutex_unlock (&cache_lock);
743 } /* }}} int flush_file */
745 static int handle_request_help (int fd, /* {{{ */
746 char *buffer, size_t buffer_size)
750 size_t help_text_len;
756 "4 Command overview\n",
757 "FLUSH <filename>\n",
758 "HELP [<command>]\n",
759 "UPDATE <filename> <values> [<values> ...]\n",
762 size_t help_help_len = sizeof (help_help) / sizeof (help_help[0]);
766 "4 Help for FLUSH\n",
767 "Usage: FLUSH <filename>\n",
769 "Adds the given filename to the head of the update queue and returns\n",
770 "after is has been dequeued.\n"
772 size_t help_flush_len = sizeof (help_flush) / sizeof (help_flush[0]);
774 char *help_update[] =
776 "9 Help for UPDATE\n",
777 "Usage: UPDATE <filename> <values> [<values> ...]\n"
779 "Adds the given file to the internal cache if it is not yet known and\n",
780 "appends the given value(s) to the entry. See the rrdcached(1) manpage\n",
783 "Each <values> has the following form:\n",
784 " <values> = <time>:<value>[:<value>[...]]\n",
785 "See the rrdupdate(1) manpage for details.\n"
787 size_t help_update_len = sizeof (help_update) / sizeof (help_update[0]);
791 "4 Help for STATS\n",
794 "Returns some performance counters, see the rrdcached(1) manpage for\n",
795 "a description of the values.\n"
797 size_t help_stats_len = sizeof (help_stats) / sizeof (help_stats[0]);
799 status = buffer_get_field (&buffer, &buffer_size, &command);
802 help_text = help_help;
803 help_text_len = help_help_len;
807 if (strcasecmp (command, "update") == 0)
809 help_text = help_update;
810 help_text_len = help_update_len;
812 else if (strcasecmp (command, "flush") == 0)
814 help_text = help_flush;
815 help_text_len = help_flush_len;
817 else if (strcasecmp (command, "stats") == 0)
819 help_text = help_stats;
820 help_text_len = help_stats_len;
824 help_text = help_help;
825 help_text_len = help_help_len;
829 for (i = 0; i < help_text_len; i++)
831 status = swrite (fd, help_text[i], strlen (help_text[i]));
835 RRDD_LOG (LOG_ERR, "handle_request_help: swrite returned an error.");
841 } /* }}} int handle_request_help */
843 static int handle_request_stats (int fd, /* {{{ */
844 char *buffer __attribute__((unused)),
845 size_t buffer_size __attribute__((unused)))
848 char outbuf[CMD_MAX];
850 uint64_t copy_queue_length;
851 uint64_t copy_updates_received;
852 uint64_t copy_flush_received;
853 uint64_t copy_updates_written;
854 uint64_t copy_data_sets_written;
855 uint64_t copy_journal_bytes;
856 uint64_t copy_journal_rotate;
858 uint64_t tree_nodes_number;
861 pthread_mutex_lock (&stats_lock);
862 copy_queue_length = stats_queue_length;
863 copy_updates_received = stats_updates_received;
864 copy_flush_received = stats_flush_received;
865 copy_updates_written = stats_updates_written;
866 copy_data_sets_written = stats_data_sets_written;
867 copy_journal_bytes = stats_journal_bytes;
868 copy_journal_rotate = stats_journal_rotate;
869 pthread_mutex_unlock (&stats_lock);
871 pthread_mutex_lock (&cache_lock);
872 tree_nodes_number = (uint64_t) g_tree_nnodes (cache_tree);
873 tree_depth = (uint64_t) g_tree_height (cache_tree);
874 pthread_mutex_unlock (&cache_lock);
876 #define RRDD_STATS_SEND \
877 outbuf[sizeof (outbuf) - 1] = 0; \
878 status = swrite (fd, outbuf, strlen (outbuf)); \
882 RRDD_LOG (LOG_INFO, "handle_request_stats: swrite returned an error."); \
886 strncpy (outbuf, "9 Statistics follow\n", sizeof (outbuf));
889 snprintf (outbuf, sizeof (outbuf),
890 "QueueLength: %"PRIu64"\n", copy_queue_length);
893 snprintf (outbuf, sizeof (outbuf),
894 "UpdatesReceived: %"PRIu64"\n", copy_updates_received);
897 snprintf (outbuf, sizeof (outbuf),
898 "FlushesReceived: %"PRIu64"\n", copy_flush_received);
901 snprintf (outbuf, sizeof (outbuf),
902 "UpdatesWritten: %"PRIu64"\n", copy_updates_written);
905 snprintf (outbuf, sizeof (outbuf),
906 "DataSetsWritten: %"PRIu64"\n", copy_data_sets_written);
909 snprintf (outbuf, sizeof (outbuf),
910 "TreeNodesNumber: %"PRIu64"\n", tree_nodes_number);
913 snprintf (outbuf, sizeof (outbuf),
914 "TreeDepth: %"PRIu64"\n", tree_depth);
917 snprintf (outbuf, sizeof(outbuf),
918 "JournalBytes: %"PRIu64"\n", copy_journal_bytes);
921 snprintf (outbuf, sizeof(outbuf),
922 "JournalRotate: %"PRIu64"\n", copy_journal_rotate);
926 #undef RRDD_STATS_SEND
927 } /* }}} int handle_request_stats */
929 static int handle_request_flush (int fd, /* {{{ */
930 char *buffer, size_t buffer_size)
934 char result[CMD_MAX];
936 status = buffer_get_field (&buffer, &buffer_size, &file);
939 strncpy (result, "-1 Usage: flush <filename>\n", sizeof (result));
943 pthread_mutex_lock(&stats_lock);
944 stats_flush_received++;
945 pthread_mutex_unlock(&stats_lock);
947 status = flush_file (file);
949 snprintf (result, sizeof (result), "0 Successfully flushed %s.\n", file);
950 else if (status == ENOENT)
952 /* no file in our tree; see whether it exists at all */
955 memset(&statbuf, 0, sizeof(statbuf));
956 if (stat(file, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
957 snprintf (result, sizeof (result), "0 Nothing to flush: %s.\n", file);
959 snprintf (result, sizeof (result), "-1 No such file: %s.\n", file);
962 strncpy (result, "-1 Internal error.\n", sizeof (result));
964 snprintf (result, sizeof (result), "-1 Failed with status %i.\n", status);
966 result[sizeof (result) - 1] = 0;
968 status = swrite (fd, result, strlen (result));
972 RRDD_LOG (LOG_INFO, "handle_request_flush: swrite returned an error.");
977 } /* }}} int handle_request_flush */
979 static int handle_request_update (int fd, /* {{{ */
980 char *buffer, size_t buffer_size)
989 char answer[CMD_MAX];
991 #define RRDD_UPDATE_SEND \
992 answer[sizeof (answer) - 1] = 0; \
993 status = swrite (fd, answer, strlen (answer)); \
997 RRDD_LOG (LOG_INFO, "handle_request_update: swrite returned an error."); \
1003 status = buffer_get_field (&buffer, &buffer_size, &file);
1006 strncpy (answer, "-1 Usage: UPDATE <filename> <values> [<values> ...]\n",
1012 pthread_mutex_lock(&stats_lock);
1013 stats_updates_received++;
1014 pthread_mutex_unlock(&stats_lock);
1016 pthread_mutex_lock (&cache_lock);
1018 ci = g_tree_lookup (cache_tree, file);
1019 if (ci == NULL) /* {{{ */
1021 struct stat statbuf;
1023 memset (&statbuf, 0, sizeof (statbuf));
1024 status = stat (file, &statbuf);
1027 pthread_mutex_unlock (&cache_lock);
1028 RRDD_LOG (LOG_NOTICE, "handle_request_update: stat (%s) failed.", file);
1031 if (status == ENOENT)
1032 snprintf (answer, sizeof (answer), "-1 No such file: %s\n", file);
1034 snprintf (answer, sizeof (answer), "-1 stat failed with error %i.\n",
1039 if (!S_ISREG (statbuf.st_mode))
1041 pthread_mutex_unlock (&cache_lock);
1043 snprintf (answer, sizeof (answer), "-1 Not a regular file: %s\n", file);
1047 if (access(file, R_OK|W_OK) != 0)
1049 pthread_mutex_unlock (&cache_lock);
1051 snprintf (answer, sizeof (answer), "-1 Cannot read/write %s: %s\n",
1052 file, rrd_strerror(errno));
1057 ci = (cache_item_t *) malloc (sizeof (cache_item_t));
1060 pthread_mutex_unlock (&cache_lock);
1061 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
1063 strncpy (answer, "-1 malloc failed.\n", sizeof (answer));
1067 memset (ci, 0, sizeof (cache_item_t));
1069 ci->file = strdup (file);
1070 if (ci->file == NULL)
1072 pthread_mutex_unlock (&cache_lock);
1074 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
1076 strncpy (answer, "-1 strdup failed.\n", sizeof (answer));
1081 _wipe_ci_values(ci, now);
1082 ci->flags = CI_FLAGS_IN_TREE;
1084 g_tree_insert (cache_tree, (void *) ci->file, (void *) ci);
1086 assert (ci != NULL);
1088 while (buffer_size > 0)
1093 status = buffer_get_field (&buffer, &buffer_size, &value);
1096 RRDD_LOG (LOG_INFO, "handle_request_update: Error reading field.");
1100 temp = (char **) realloc (ci->values,
1101 sizeof (char *) * (ci->values_num + 1));
1104 RRDD_LOG (LOG_ERR, "handle_request_update: realloc failed.");
1109 ci->values[ci->values_num] = strdup (value);
1110 if (ci->values[ci->values_num] == NULL)
1112 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
1120 if (((now - ci->last_flush_time) >= config_write_interval)
1121 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
1122 && (ci->values_num > 0))
1124 enqueue_cache_item (ci, TAIL);
1125 pthread_cond_signal (&cache_cond);
1128 pthread_mutex_unlock (&cache_lock);
1132 strncpy (answer, "-1 No values updated.\n", sizeof (answer));
1136 snprintf (answer, sizeof (answer), "0 Enqueued %i value%s\n", values_num,
1137 (values_num == 1) ? "" : "s");
1141 #undef RRDD_UPDATE_SEND
1142 } /* }}} int handle_request_update */
1144 /* we came across a "WROTE" entry during journal replay.
1145 * throw away any values that we have accumulated for this file
1147 static int handle_request_wrote (int fd __attribute__((unused)), /* {{{ */
1149 size_t buffer_size __attribute__((unused)))
1153 const char *file = buffer;
1155 pthread_mutex_lock(&cache_lock);
1157 ci = g_tree_lookup(cache_tree, file);
1163 for (i=0; i < ci->values_num; i++)
1164 free(ci->values[i]);
1169 _wipe_ci_values(ci, time(NULL));
1172 pthread_mutex_unlock(&cache_lock);
1176 /* if fd < 0, we are in journal replay mode */
1177 static int handle_request (int fd, char *buffer, size_t buffer_size) /* {{{ */
1183 assert (buffer[buffer_size - 1] == '\0');
1185 buffer_ptr = buffer;
1187 status = buffer_get_field (&buffer_ptr, &buffer_size, &command);
1190 RRDD_LOG (LOG_INFO, "handle_request: Unable parse command.");
1194 if (strcasecmp (command, "update") == 0)
1196 /* don't re-write updates in replay mode */
1198 journal_write(command, buffer_ptr);
1200 return (handle_request_update (fd, buffer_ptr, buffer_size));
1202 else if (strcasecmp (command, "wrote") == 0 && fd < 0)
1204 /* this is only valid in replay mode */
1205 return (handle_request_wrote (fd, buffer_ptr, buffer_size));
1207 else if (strcasecmp (command, "flush") == 0)
1209 return (handle_request_flush (fd, buffer_ptr, buffer_size));
1211 else if (strcasecmp (command, "stats") == 0)
1213 return (handle_request_stats (fd, buffer_ptr, buffer_size));
1215 else if (strcasecmp (command, "help") == 0)
1217 return (handle_request_help (fd, buffer_ptr, buffer_size));
1221 char result[CMD_MAX];
1223 snprintf (result, sizeof (result), "-1 Unknown command: %s\n", command);
1224 result[sizeof (result) - 1] = 0;
1226 status = swrite (fd, result, strlen (result));
1229 RRDD_LOG (LOG_ERR, "handle_request: swrite failed.");
1235 } /* }}} int handle_request */
1237 /* MUST NOT hold journal_lock before calling this */
1238 static void journal_rotate(void) /* {{{ */
1240 FILE *old_fh = NULL;
1242 if (journal_cur == NULL || journal_old == NULL)
1245 pthread_mutex_lock(&journal_lock);
1247 /* we rotate this way (rename before close) so that the we can release
1248 * the journal lock as fast as possible. Journal writes to the new
1249 * journal can proceed immediately after the new file is opened. The
1250 * fclose can then block without affecting new updates.
1252 if (journal_fh != NULL)
1254 old_fh = journal_fh;
1255 rename(journal_cur, journal_old);
1256 ++stats_journal_rotate;
1259 journal_fh = fopen(journal_cur, "a");
1260 pthread_mutex_unlock(&journal_lock);
1265 if (journal_fh == NULL)
1267 "JOURNALING DISABLED: Cannot open journal file '%s' : (%s)",
1268 journal_cur, rrd_strerror(errno));
1270 } /* }}} static void journal_rotate */
1272 static void journal_done(void) /* {{{ */
1274 if (journal_cur == NULL)
1277 pthread_mutex_lock(&journal_lock);
1278 if (journal_fh != NULL)
1284 RRDD_LOG(LOG_INFO, "removing journals");
1286 unlink(journal_old);
1287 unlink(journal_cur);
1288 pthread_mutex_unlock(&journal_lock);
1290 } /* }}} static void journal_done */
1292 static int journal_write(char *cmd, char *args) /* {{{ */
1296 if (journal_fh == NULL)
1299 pthread_mutex_lock(&journal_lock);
1300 chars = fprintf(journal_fh, "%s %s\n", cmd, args);
1301 pthread_mutex_unlock(&journal_lock);
1305 pthread_mutex_lock(&stats_lock);
1306 stats_journal_bytes += chars;
1307 pthread_mutex_unlock(&stats_lock);
1311 } /* }}} static int journal_write */
1313 static int journal_replay (const char *file) /* {{{ */
1319 char entry[CMD_MAX];
1321 if (file == NULL) return 0;
1323 fh = fopen(file, "r");
1326 if (errno != ENOENT)
1327 RRDD_LOG(LOG_ERR, "journal_replay: cannot open journal file: '%s' (%s)",
1328 file, rrd_strerror(errno));
1332 RRDD_LOG(LOG_NOTICE, "replaying from journal: %s", file);
1339 fgets(entry, sizeof(entry), fh);
1340 entry_len = strlen(entry);
1342 /* check \n termination in case journal writing crashed mid-line */
1345 else if (entry[entry_len - 1] != '\n')
1347 RRDD_LOG(LOG_NOTICE, "Malformed journal entry at line %"PRIu64, line);
1352 entry[entry_len - 1] = '\0';
1354 if (handle_request(-1, entry, entry_len) == 0)
1364 RRDD_LOG(LOG_INFO, "Replayed %d entries (%d failures)",
1365 entry_cnt, fail_cnt);
1371 } /* }}} static int journal_replay */
1373 static void *connection_thread_main (void *args) /* {{{ */
1379 fd = *((int *) args);
1382 pthread_mutex_lock (&connection_threads_lock);
1386 temp = (pthread_t *) realloc (connection_threads,
1387 sizeof (pthread_t) * (connection_threads_num + 1));
1390 RRDD_LOG (LOG_ERR, "connection_thread_main: realloc failed.");
1394 connection_threads = temp;
1395 connection_threads[connection_threads_num] = pthread_self ();
1396 connection_threads_num++;
1399 pthread_mutex_unlock (&connection_threads_lock);
1401 while (do_shutdown == 0)
1403 char buffer[CMD_MAX];
1405 struct pollfd pollfd;
1409 pollfd.events = POLLIN | POLLPRI;
1412 status = poll (&pollfd, 1, /* timeout = */ 500);
1413 if (status == 0) /* timeout */
1415 else if (status < 0) /* error */
1418 if (status == EINTR)
1420 RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
1424 if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
1429 else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
1431 RRDD_LOG (LOG_WARNING, "connection_thread_main: "
1432 "poll(2) returned something unexpected: %#04hx",
1438 status = (int) sread (fd, buffer, sizeof (buffer));
1444 RRDD_LOG(LOG_ERR, "connection_thread_main: sread failed.");
1449 status = handle_request (fd, buffer, /*buffer_size=*/ status);
1457 self = pthread_self ();
1458 /* Remove this thread from the connection threads list */
1459 pthread_mutex_lock (&connection_threads_lock);
1460 /* Find out own index in the array */
1461 for (i = 0; i < connection_threads_num; i++)
1462 if (pthread_equal (connection_threads[i], self) != 0)
1464 assert (i < connection_threads_num);
1466 /* Move the trailing threads forward. */
1467 if (i < (connection_threads_num - 1))
1469 memmove (connection_threads + i,
1470 connection_threads + i + 1,
1471 sizeof (pthread_t) * (connection_threads_num - i - 1));
1474 connection_threads_num--;
1475 pthread_mutex_unlock (&connection_threads_lock);
1478 } /* }}} void *connection_thread_main */
1480 static int open_listen_socket_unix (const char *path) /* {{{ */
1483 struct sockaddr_un sa;
1484 listen_socket_t *temp;
1487 temp = (listen_socket_t *) realloc (listen_fds,
1488 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1491 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: realloc failed.");
1495 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1497 fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
1500 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: socket(2) failed.");
1504 memset (&sa, 0, sizeof (sa));
1505 sa.sun_family = AF_UNIX;
1506 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
1508 status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
1511 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: bind(2) failed.");
1517 status = listen (fd, /* backlog = */ 10);
1520 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: listen(2) failed.");
1526 listen_fds[listen_fds_num].fd = fd;
1527 snprintf (listen_fds[listen_fds_num].path,
1528 sizeof (listen_fds[listen_fds_num].path) - 1,
1533 } /* }}} int open_listen_socket_unix */
1535 static int open_listen_socket (const char *addr) /* {{{ */
1537 struct addrinfo ai_hints;
1538 struct addrinfo *ai_res;
1539 struct addrinfo *ai_ptr;
1542 assert (addr != NULL);
1544 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
1545 return (open_listen_socket_unix (addr + strlen ("unix:")));
1546 else if (addr[0] == '/')
1547 return (open_listen_socket_unix (addr));
1549 memset (&ai_hints, 0, sizeof (ai_hints));
1550 ai_hints.ai_flags = 0;
1551 #ifdef AI_ADDRCONFIG
1552 ai_hints.ai_flags |= AI_ADDRCONFIG;
1554 ai_hints.ai_family = AF_UNSPEC;
1555 ai_hints.ai_socktype = SOCK_STREAM;
1558 status = getaddrinfo (addr, RRDCACHED_DEFAULT_PORT, &ai_hints, &ai_res);
1561 RRDD_LOG (LOG_ERR, "open_listen_socket: getaddrinfo(%s) failed: "
1562 "%s", addr, gai_strerror (status));
1566 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1569 listen_socket_t *temp;
1571 temp = (listen_socket_t *) realloc (listen_fds,
1572 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1575 RRDD_LOG (LOG_ERR, "open_listen_socket: realloc failed.");
1579 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1581 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1584 RRDD_LOG (LOG_ERR, "open_listen_socket: socket(2) failed.");
1588 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1591 RRDD_LOG (LOG_ERR, "open_listen_socket: bind(2) failed.");
1596 status = listen (fd, /* backlog = */ 10);
1599 RRDD_LOG (LOG_ERR, "open_listen_socket: listen(2) failed.");
1604 listen_fds[listen_fds_num].fd = fd;
1605 strncpy (listen_fds[listen_fds_num].path, addr,
1606 sizeof (listen_fds[listen_fds_num].path) - 1);
1608 } /* for (ai_ptr) */
1611 } /* }}} int open_listen_socket */
1613 static int close_listen_sockets (void) /* {{{ */
1617 for (i = 0; i < listen_fds_num; i++)
1619 close (listen_fds[i].fd);
1620 if (strncmp ("unix:", listen_fds[i].path, strlen ("unix:")) == 0)
1621 unlink (listen_fds[i].path + strlen ("unix:"));
1629 } /* }}} int close_listen_sockets */
1631 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
1633 struct pollfd *pollfds;
1638 for (i = 0; i < config_listen_address_list_len; i++)
1639 open_listen_socket (config_listen_address_list[i]);
1641 if (config_listen_address_list_len < 1)
1642 open_listen_socket (RRDCACHED_DEFAULT_ADDRESS);
1644 if (listen_fds_num < 1)
1646 RRDD_LOG (LOG_ERR, "listen_thread_main: No listen sockets "
1647 "could be opened. Sorry.");
1651 pollfds_num = listen_fds_num;
1652 pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
1653 if (pollfds == NULL)
1655 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1658 memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
1660 RRDD_LOG(LOG_INFO, "listening for connections");
1662 while (do_shutdown == 0)
1664 assert (pollfds_num == ((int) listen_fds_num));
1665 for (i = 0; i < pollfds_num; i++)
1667 pollfds[i].fd = listen_fds[i].fd;
1668 pollfds[i].events = POLLIN | POLLPRI;
1669 pollfds[i].revents = 0;
1672 status = poll (pollfds, pollfds_num, /* timeout = */ -1);
1676 if (status != EINTR)
1678 RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
1683 for (i = 0; i < pollfds_num; i++)
1686 struct sockaddr_storage client_sa;
1687 socklen_t client_sa_size;
1689 pthread_attr_t attr;
1691 if (pollfds[i].revents == 0)
1694 if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
1696 RRDD_LOG (LOG_ERR, "listen_thread_main: "
1697 "poll(2) returned something unexpected for listen FD #%i.",
1702 client_sd = (int *) malloc (sizeof (int));
1703 if (client_sd == NULL)
1705 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1709 client_sa_size = sizeof (client_sa);
1710 *client_sd = accept (pollfds[i].fd,
1711 (struct sockaddr *) &client_sa, &client_sa_size);
1714 RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
1718 pthread_attr_init (&attr);
1719 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
1721 status = pthread_create (&tid, &attr, connection_thread_main,
1722 /* args = */ (void *) client_sd);
1725 RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
1730 } /* for (pollfds_num) */
1731 } /* while (do_shutdown == 0) */
1733 RRDD_LOG(LOG_INFO, "starting shutdown");
1735 close_listen_sockets ();
1737 pthread_mutex_lock (&connection_threads_lock);
1738 while (connection_threads_num > 0)
1742 wait_for = connection_threads[0];
1744 pthread_mutex_unlock (&connection_threads_lock);
1745 pthread_join (wait_for, /* retval = */ NULL);
1746 pthread_mutex_lock (&connection_threads_lock);
1748 pthread_mutex_unlock (&connection_threads_lock);
1751 } /* }}} void *listen_thread_main */
1753 static int daemonize (void) /* {{{ */
1759 /* These structures are static, because `sigaction' behaves weird if the are
1761 static struct sigaction sa_int;
1762 static struct sigaction sa_term;
1763 static struct sigaction sa_pipe;
1765 if (stay_foreground)
1771 fprintf (stderr, "daemonize: fork(2) failed.\n");
1779 /* Change into the /tmp directory. */
1780 base_dir = (config_base_dir != NULL)
1783 status = chdir (base_dir);
1786 fprintf (stderr, "daemonize: chdir (%s) failed.\n", base_dir);
1790 /* Become session leader */
1793 /* Open the first three file descriptors to /dev/null */
1798 open ("/dev/null", O_RDWR);
1803 /* Install signal handlers */
1804 memset (&sa_int, 0, sizeof (sa_int));
1805 sa_int.sa_handler = sig_int_handler;
1806 sigaction (SIGINT, &sa_int, NULL);
1808 memset (&sa_term, 0, sizeof (sa_term));
1809 sa_term.sa_handler = sig_term_handler;
1810 sigaction (SIGTERM, &sa_term, NULL);
1812 memset (&sa_pipe, 0, sizeof (sa_pipe));
1813 sa_pipe.sa_handler = SIG_IGN;
1814 sigaction (SIGPIPE, &sa_pipe, NULL);
1816 openlog ("rrdcached", LOG_PID, LOG_DAEMON);
1817 RRDD_LOG(LOG_INFO, "starting up");
1819 cache_tree = g_tree_new ((GCompareFunc) strcmp);
1820 if (cache_tree == NULL)
1822 RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
1826 status = write_pidfile ();
1828 } /* }}} int daemonize */
1830 static int cleanup (void) /* {{{ */
1834 pthread_cond_signal (&cache_cond);
1835 pthread_join (queue_thread, /* return = */ NULL);
1839 RRDD_LOG(LOG_INFO, "goodbye");
1843 } /* }}} int cleanup */
1845 static int read_options (int argc, char **argv) /* {{{ */
1850 while ((option = getopt(argc, argv, "gl:f:w:b:z:p:j:h?")) != -1)
1862 temp = (char **) realloc (config_listen_address_list,
1863 sizeof (char *) * (config_listen_address_list_len + 1));
1866 fprintf (stderr, "read_options: realloc failed.\n");
1869 config_listen_address_list = temp;
1871 temp[config_listen_address_list_len] = strdup (optarg);
1872 if (temp[config_listen_address_list_len] == NULL)
1874 fprintf (stderr, "read_options: strdup failed.\n");
1877 config_listen_address_list_len++;
1885 temp = atoi (optarg);
1887 config_flush_interval = temp;
1890 fprintf (stderr, "Invalid flush interval: %s\n", optarg);
1900 temp = atoi (optarg);
1902 config_write_interval = temp;
1905 fprintf (stderr, "Invalid write interval: %s\n", optarg);
1915 temp = atoi(optarg);
1917 config_write_jitter = temp;
1920 fprintf (stderr, "Invalid write jitter: -z %s\n", optarg);
1931 if (config_base_dir != NULL)
1932 free (config_base_dir);
1933 config_base_dir = strdup (optarg);
1934 if (config_base_dir == NULL)
1936 fprintf (stderr, "read_options: strdup failed.\n");
1940 len = strlen (config_base_dir);
1941 while ((len > 0) && (config_base_dir[len - 1] == '/'))
1943 config_base_dir[len - 1] = 0;
1949 fprintf (stderr, "Invalid base directory: %s\n", optarg);
1957 if (config_pid_file != NULL)
1958 free (config_pid_file);
1959 config_pid_file = strdup (optarg);
1960 if (config_pid_file == NULL)
1962 fprintf (stderr, "read_options: strdup failed.\n");
1970 struct stat statbuf;
1971 const char *dir = optarg;
1973 status = stat(dir, &statbuf);
1976 fprintf(stderr, "Cannot stat '%s' : %s\n", dir, rrd_strerror(errno));
1980 if (!S_ISDIR(statbuf.st_mode)
1981 || access(dir, R_OK|W_OK|X_OK) != 0)
1983 fprintf(stderr, "Must specify a writable directory with -j! (%s)\n",
1984 errno ? rrd_strerror(errno) : "");
1988 journal_cur = malloc(PATH_MAX + 1);
1989 journal_old = malloc(PATH_MAX + 1);
1990 if (journal_cur == NULL || journal_old == NULL)
1992 fprintf(stderr, "malloc failure for journal files\n");
1997 snprintf(journal_cur, PATH_MAX, "%s/rrd.journal", dir);
1998 snprintf(journal_old, PATH_MAX, "%s/rrd.journal.old", dir);
2005 printf ("RRDd %s Copyright (C) 2008 Florian octo Forster\n"
2007 "Usage: rrdcached [options]\n"
2009 "Valid options are:\n"
2010 " -l <address> Socket address to listen to.\n"
2011 " -w <seconds> Interval in which to write data.\n"
2012 " -z <delay> Delay writes up to <delay> seconds to spread load" \
2013 " -f <seconds> Interval in which to flush dead data.\n"
2014 " -p <file> Location of the PID-file.\n"
2015 " -b <dir> Base directory to change to.\n"
2017 "For more information and a detailed description of all options "
2019 "to the rrdcached(1) manual page.\n",
2023 } /* switch (option) */
2024 } /* while (getopt) */
2026 /* advise the user when values are not sane */
2027 if (config_flush_interval < 2 * config_write_interval)
2028 fprintf(stderr, "WARNING: flush interval (-f) should be at least"
2029 " 2x write interval (-w) !\n");
2030 if (config_write_jitter > config_write_interval)
2031 fprintf(stderr, "WARNING: write delay (-z) should NOT be larger than"
2032 " write interval (-w) !\n");
2035 } /* }}} int read_options */
2037 int main (int argc, char **argv)
2041 status = read_options (argc, argv);
2049 status = daemonize ();
2052 struct sigaction sigchld;
2054 memset (&sigchld, 0, sizeof (sigchld));
2055 sigchld.sa_handler = SIG_IGN;
2056 sigaction (SIGCHLD, &sigchld, NULL);
2060 else if (status != 0)
2062 fprintf (stderr, "daemonize failed, exiting.\n");
2066 if (journal_cur != NULL)
2068 int had_journal = 0;
2070 pthread_mutex_lock(&journal_lock);
2072 RRDD_LOG(LOG_INFO, "checking for journal files");
2074 had_journal += journal_replay(journal_old);
2075 had_journal += journal_replay(journal_cur);
2078 flush_old_values(-1);
2080 pthread_mutex_unlock(&journal_lock);
2083 RRDD_LOG(LOG_INFO, "journal processing complete");
2086 /* start the queue thread */
2087 memset (&queue_thread, 0, sizeof (queue_thread));
2088 status = pthread_create (&queue_thread,
2094 RRDD_LOG (LOG_ERR, "FATAL: cannot create queue thread");
2099 listen_thread_main (NULL);
2106 * vim: set sw=2 sts=2 ts=8 et fdm=marker :