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);
1160 pthread_mutex_unlock(&cache_lock);
1166 for (i=0; i < ci->values_num; i++)
1167 free(ci->values[i]);
1172 _wipe_ci_values(ci, time(NULL));
1174 pthread_mutex_unlock(&cache_lock);
1178 /* if fd < 0, we are in journal replay mode */
1179 static int handle_request (int fd, char *buffer, size_t buffer_size) /* {{{ */
1185 assert (buffer[buffer_size - 1] == '\0');
1187 buffer_ptr = buffer;
1189 status = buffer_get_field (&buffer_ptr, &buffer_size, &command);
1192 RRDD_LOG (LOG_INFO, "handle_request: Unable parse command.");
1196 if (strcasecmp (command, "update") == 0)
1198 /* don't re-write updates in replay mode */
1200 journal_write(command, buffer_ptr);
1202 return (handle_request_update (fd, buffer_ptr, buffer_size));
1204 else if (strcasecmp (command, "wrote") == 0 && fd < 0)
1206 /* this is only valid in replay mode */
1207 return (handle_request_wrote (fd, buffer_ptr, buffer_size));
1209 else if (strcasecmp (command, "flush") == 0)
1211 return (handle_request_flush (fd, buffer_ptr, buffer_size));
1213 else if (strcasecmp (command, "stats") == 0)
1215 return (handle_request_stats (fd, buffer_ptr, buffer_size));
1217 else if (strcasecmp (command, "help") == 0)
1219 return (handle_request_help (fd, buffer_ptr, buffer_size));
1223 char result[CMD_MAX];
1225 snprintf (result, sizeof (result), "-1 Unknown command: %s\n", command);
1226 result[sizeof (result) - 1] = 0;
1228 status = swrite (fd, result, strlen (result));
1231 RRDD_LOG (LOG_ERR, "handle_request: swrite failed.");
1237 } /* }}} int handle_request */
1239 /* MUST NOT hold journal_lock before calling this */
1240 static void journal_rotate(void) /* {{{ */
1242 FILE *old_fh = NULL;
1244 if (journal_cur == NULL || journal_old == NULL)
1247 pthread_mutex_lock(&journal_lock);
1249 /* we rotate this way (rename before close) so that the we can release
1250 * the journal lock as fast as possible. Journal writes to the new
1251 * journal can proceed immediately after the new file is opened. The
1252 * fclose can then block without affecting new updates.
1254 if (journal_fh != NULL)
1256 old_fh = journal_fh;
1257 rename(journal_cur, journal_old);
1258 ++stats_journal_rotate;
1261 journal_fh = fopen(journal_cur, "a");
1262 pthread_mutex_unlock(&journal_lock);
1267 if (journal_fh == NULL)
1269 "JOURNALING DISABLED: Cannot open journal file '%s' : (%s)",
1270 journal_cur, rrd_strerror(errno));
1272 } /* }}} static void journal_rotate */
1274 static void journal_done(void) /* {{{ */
1276 if (journal_cur == NULL)
1279 pthread_mutex_lock(&journal_lock);
1280 if (journal_fh != NULL)
1286 RRDD_LOG(LOG_INFO, "removing journals");
1288 unlink(journal_old);
1289 unlink(journal_cur);
1290 pthread_mutex_unlock(&journal_lock);
1292 } /* }}} static void journal_done */
1294 static int journal_write(char *cmd, char *args) /* {{{ */
1298 if (journal_fh == NULL)
1301 pthread_mutex_lock(&journal_lock);
1302 chars = fprintf(journal_fh, "%s %s\n", cmd, args);
1303 pthread_mutex_unlock(&journal_lock);
1307 pthread_mutex_lock(&stats_lock);
1308 stats_journal_bytes += chars;
1309 pthread_mutex_unlock(&stats_lock);
1313 } /* }}} static int journal_write */
1315 static int journal_replay (const char *file) /* {{{ */
1321 char entry[CMD_MAX];
1323 if (file == NULL) return 0;
1325 fh = fopen(file, "r");
1328 if (errno != ENOENT)
1329 RRDD_LOG(LOG_ERR, "journal_replay: cannot open journal file: '%s' (%s)",
1330 file, rrd_strerror(errno));
1334 RRDD_LOG(LOG_NOTICE, "replaying from journal: %s", file);
1341 fgets(entry, sizeof(entry), fh);
1342 entry_len = strlen(entry);
1344 /* check \n termination in case journal writing crashed mid-line */
1347 else if (entry[entry_len - 1] != '\n')
1349 RRDD_LOG(LOG_NOTICE, "Malformed journal entry at line %"PRIu64, line);
1354 entry[entry_len - 1] = '\0';
1356 if (handle_request(-1, entry, entry_len) == 0)
1366 RRDD_LOG(LOG_INFO, "Replayed %d entries (%d failures)",
1367 entry_cnt, fail_cnt);
1373 } /* }}} static int journal_replay */
1375 static void *connection_thread_main (void *args) /* {{{ */
1381 fd = *((int *) args);
1384 pthread_mutex_lock (&connection_threads_lock);
1388 temp = (pthread_t *) realloc (connection_threads,
1389 sizeof (pthread_t) * (connection_threads_num + 1));
1392 RRDD_LOG (LOG_ERR, "connection_thread_main: realloc failed.");
1396 connection_threads = temp;
1397 connection_threads[connection_threads_num] = pthread_self ();
1398 connection_threads_num++;
1401 pthread_mutex_unlock (&connection_threads_lock);
1403 while (do_shutdown == 0)
1405 char buffer[CMD_MAX];
1407 struct pollfd pollfd;
1411 pollfd.events = POLLIN | POLLPRI;
1414 status = poll (&pollfd, 1, /* timeout = */ 500);
1415 if (status == 0) /* timeout */
1417 else if (status < 0) /* error */
1420 if (status == EINTR)
1422 RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
1426 if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
1431 else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
1433 RRDD_LOG (LOG_WARNING, "connection_thread_main: "
1434 "poll(2) returned something unexpected: %#04hx",
1440 status = (int) sread (fd, buffer, sizeof (buffer));
1446 RRDD_LOG(LOG_ERR, "connection_thread_main: sread failed.");
1451 status = handle_request (fd, buffer, /*buffer_size=*/ status);
1459 self = pthread_self ();
1460 /* Remove this thread from the connection threads list */
1461 pthread_mutex_lock (&connection_threads_lock);
1462 /* Find out own index in the array */
1463 for (i = 0; i < connection_threads_num; i++)
1464 if (pthread_equal (connection_threads[i], self) != 0)
1466 assert (i < connection_threads_num);
1468 /* Move the trailing threads forward. */
1469 if (i < (connection_threads_num - 1))
1471 memmove (connection_threads + i,
1472 connection_threads + i + 1,
1473 sizeof (pthread_t) * (connection_threads_num - i - 1));
1476 connection_threads_num--;
1477 pthread_mutex_unlock (&connection_threads_lock);
1480 } /* }}} void *connection_thread_main */
1482 static int open_listen_socket_unix (const char *path) /* {{{ */
1485 struct sockaddr_un sa;
1486 listen_socket_t *temp;
1489 temp = (listen_socket_t *) realloc (listen_fds,
1490 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1493 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: realloc failed.");
1497 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1499 fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
1502 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: socket(2) failed.");
1506 memset (&sa, 0, sizeof (sa));
1507 sa.sun_family = AF_UNIX;
1508 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
1510 status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
1513 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: bind(2) failed.");
1519 status = listen (fd, /* backlog = */ 10);
1522 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: listen(2) failed.");
1528 listen_fds[listen_fds_num].fd = fd;
1529 snprintf (listen_fds[listen_fds_num].path,
1530 sizeof (listen_fds[listen_fds_num].path) - 1,
1535 } /* }}} int open_listen_socket_unix */
1537 static int open_listen_socket (const char *addr) /* {{{ */
1539 struct addrinfo ai_hints;
1540 struct addrinfo *ai_res;
1541 struct addrinfo *ai_ptr;
1544 assert (addr != NULL);
1546 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
1547 return (open_listen_socket_unix (addr + strlen ("unix:")));
1548 else if (addr[0] == '/')
1549 return (open_listen_socket_unix (addr));
1551 memset (&ai_hints, 0, sizeof (ai_hints));
1552 ai_hints.ai_flags = 0;
1553 #ifdef AI_ADDRCONFIG
1554 ai_hints.ai_flags |= AI_ADDRCONFIG;
1556 ai_hints.ai_family = AF_UNSPEC;
1557 ai_hints.ai_socktype = SOCK_STREAM;
1560 status = getaddrinfo (addr, RRDCACHED_DEFAULT_PORT, &ai_hints, &ai_res);
1563 RRDD_LOG (LOG_ERR, "open_listen_socket: getaddrinfo(%s) failed: "
1564 "%s", addr, gai_strerror (status));
1568 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1571 listen_socket_t *temp;
1573 temp = (listen_socket_t *) realloc (listen_fds,
1574 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1577 RRDD_LOG (LOG_ERR, "open_listen_socket: realloc failed.");
1581 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1583 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1586 RRDD_LOG (LOG_ERR, "open_listen_socket: socket(2) failed.");
1590 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1593 RRDD_LOG (LOG_ERR, "open_listen_socket: bind(2) failed.");
1598 status = listen (fd, /* backlog = */ 10);
1601 RRDD_LOG (LOG_ERR, "open_listen_socket: listen(2) failed.");
1606 listen_fds[listen_fds_num].fd = fd;
1607 strncpy (listen_fds[listen_fds_num].path, addr,
1608 sizeof (listen_fds[listen_fds_num].path) - 1);
1610 } /* for (ai_ptr) */
1613 } /* }}} int open_listen_socket */
1615 static int close_listen_sockets (void) /* {{{ */
1619 for (i = 0; i < listen_fds_num; i++)
1621 close (listen_fds[i].fd);
1622 if (strncmp ("unix:", listen_fds[i].path, strlen ("unix:")) == 0)
1623 unlink (listen_fds[i].path + strlen ("unix:"));
1631 } /* }}} int close_listen_sockets */
1633 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
1635 struct pollfd *pollfds;
1640 for (i = 0; i < config_listen_address_list_len; i++)
1641 open_listen_socket (config_listen_address_list[i]);
1643 if (config_listen_address_list_len < 1)
1644 open_listen_socket (RRDCACHED_DEFAULT_ADDRESS);
1646 if (listen_fds_num < 1)
1648 RRDD_LOG (LOG_ERR, "listen_thread_main: No listen sockets "
1649 "could be opened. Sorry.");
1653 pollfds_num = listen_fds_num;
1654 pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
1655 if (pollfds == NULL)
1657 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1660 memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
1662 RRDD_LOG(LOG_INFO, "listening for connections");
1664 while (do_shutdown == 0)
1666 assert (pollfds_num == ((int) listen_fds_num));
1667 for (i = 0; i < pollfds_num; i++)
1669 pollfds[i].fd = listen_fds[i].fd;
1670 pollfds[i].events = POLLIN | POLLPRI;
1671 pollfds[i].revents = 0;
1674 status = poll (pollfds, pollfds_num, /* timeout = */ -1);
1678 if (status != EINTR)
1680 RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
1685 for (i = 0; i < pollfds_num; i++)
1688 struct sockaddr_storage client_sa;
1689 socklen_t client_sa_size;
1691 pthread_attr_t attr;
1693 if (pollfds[i].revents == 0)
1696 if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
1698 RRDD_LOG (LOG_ERR, "listen_thread_main: "
1699 "poll(2) returned something unexpected for listen FD #%i.",
1704 client_sd = (int *) malloc (sizeof (int));
1705 if (client_sd == NULL)
1707 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1711 client_sa_size = sizeof (client_sa);
1712 *client_sd = accept (pollfds[i].fd,
1713 (struct sockaddr *) &client_sa, &client_sa_size);
1716 RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
1720 pthread_attr_init (&attr);
1721 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
1723 status = pthread_create (&tid, &attr, connection_thread_main,
1724 /* args = */ (void *) client_sd);
1727 RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
1732 } /* for (pollfds_num) */
1733 } /* while (do_shutdown == 0) */
1735 RRDD_LOG(LOG_INFO, "starting shutdown");
1737 close_listen_sockets ();
1739 pthread_mutex_lock (&connection_threads_lock);
1740 while (connection_threads_num > 0)
1744 wait_for = connection_threads[0];
1746 pthread_mutex_unlock (&connection_threads_lock);
1747 pthread_join (wait_for, /* retval = */ NULL);
1748 pthread_mutex_lock (&connection_threads_lock);
1750 pthread_mutex_unlock (&connection_threads_lock);
1753 } /* }}} void *listen_thread_main */
1755 static int daemonize (void) /* {{{ */
1761 /* These structures are static, because `sigaction' behaves weird if the are
1763 static struct sigaction sa_int;
1764 static struct sigaction sa_term;
1765 static struct sigaction sa_pipe;
1767 if (stay_foreground)
1773 fprintf (stderr, "daemonize: fork(2) failed.\n");
1781 /* Change into the /tmp directory. */
1782 base_dir = (config_base_dir != NULL)
1785 status = chdir (base_dir);
1788 fprintf (stderr, "daemonize: chdir (%s) failed.\n", base_dir);
1792 /* Become session leader */
1795 /* Open the first three file descriptors to /dev/null */
1800 open ("/dev/null", O_RDWR);
1805 /* Install signal handlers */
1806 memset (&sa_int, 0, sizeof (sa_int));
1807 sa_int.sa_handler = sig_int_handler;
1808 sigaction (SIGINT, &sa_int, NULL);
1810 memset (&sa_term, 0, sizeof (sa_term));
1811 sa_term.sa_handler = sig_term_handler;
1812 sigaction (SIGTERM, &sa_term, NULL);
1814 memset (&sa_pipe, 0, sizeof (sa_pipe));
1815 sa_pipe.sa_handler = SIG_IGN;
1816 sigaction (SIGPIPE, &sa_pipe, NULL);
1818 openlog ("rrdcached", LOG_PID, LOG_DAEMON);
1819 RRDD_LOG(LOG_INFO, "starting up");
1821 cache_tree = g_tree_new ((GCompareFunc) strcmp);
1822 if (cache_tree == NULL)
1824 RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
1828 status = write_pidfile ();
1830 } /* }}} int daemonize */
1832 static int cleanup (void) /* {{{ */
1836 pthread_cond_signal (&cache_cond);
1837 pthread_join (queue_thread, /* return = */ NULL);
1841 RRDD_LOG(LOG_INFO, "goodbye");
1845 } /* }}} int cleanup */
1847 static int read_options (int argc, char **argv) /* {{{ */
1852 while ((option = getopt(argc, argv, "gl:f:w:b:z:p:j:h?")) != -1)
1864 temp = (char **) realloc (config_listen_address_list,
1865 sizeof (char *) * (config_listen_address_list_len + 1));
1868 fprintf (stderr, "read_options: realloc failed.\n");
1871 config_listen_address_list = temp;
1873 temp[config_listen_address_list_len] = strdup (optarg);
1874 if (temp[config_listen_address_list_len] == NULL)
1876 fprintf (stderr, "read_options: strdup failed.\n");
1879 config_listen_address_list_len++;
1887 temp = atoi (optarg);
1889 config_flush_interval = temp;
1892 fprintf (stderr, "Invalid flush interval: %s\n", optarg);
1902 temp = atoi (optarg);
1904 config_write_interval = temp;
1907 fprintf (stderr, "Invalid write interval: %s\n", optarg);
1917 temp = atoi(optarg);
1919 config_write_jitter = temp;
1922 fprintf (stderr, "Invalid write jitter: -z %s\n", optarg);
1933 if (config_base_dir != NULL)
1934 free (config_base_dir);
1935 config_base_dir = strdup (optarg);
1936 if (config_base_dir == NULL)
1938 fprintf (stderr, "read_options: strdup failed.\n");
1942 len = strlen (config_base_dir);
1943 while ((len > 0) && (config_base_dir[len - 1] == '/'))
1945 config_base_dir[len - 1] = 0;
1951 fprintf (stderr, "Invalid base directory: %s\n", optarg);
1959 if (config_pid_file != NULL)
1960 free (config_pid_file);
1961 config_pid_file = strdup (optarg);
1962 if (config_pid_file == NULL)
1964 fprintf (stderr, "read_options: strdup failed.\n");
1972 struct stat statbuf;
1973 const char *dir = optarg;
1975 status = stat(dir, &statbuf);
1978 fprintf(stderr, "Cannot stat '%s' : %s\n", dir, rrd_strerror(errno));
1982 if (!S_ISDIR(statbuf.st_mode)
1983 || access(dir, R_OK|W_OK|X_OK) != 0)
1985 fprintf(stderr, "Must specify a writable directory with -j! (%s)\n",
1986 errno ? rrd_strerror(errno) : "");
1990 journal_cur = malloc(PATH_MAX + 1);
1991 journal_old = malloc(PATH_MAX + 1);
1992 if (journal_cur == NULL || journal_old == NULL)
1994 fprintf(stderr, "malloc failure for journal files\n");
1999 snprintf(journal_cur, PATH_MAX, "%s/rrd.journal", dir);
2000 snprintf(journal_old, PATH_MAX, "%s/rrd.journal.old", dir);
2007 printf ("RRDd %s Copyright (C) 2008 Florian octo Forster\n"
2009 "Usage: rrdcached [options]\n"
2011 "Valid options are:\n"
2012 " -l <address> Socket address to listen to.\n"
2013 " -w <seconds> Interval in which to write data.\n"
2014 " -z <delay> Delay writes up to <delay> seconds to spread load" \
2015 " -f <seconds> Interval in which to flush dead data.\n"
2016 " -p <file> Location of the PID-file.\n"
2017 " -b <dir> Base directory to change to.\n"
2019 "For more information and a detailed description of all options "
2021 "to the rrdcached(1) manual page.\n",
2025 } /* switch (option) */
2026 } /* while (getopt) */
2028 /* advise the user when values are not sane */
2029 if (config_flush_interval < 2 * config_write_interval)
2030 fprintf(stderr, "WARNING: flush interval (-f) should be at least"
2031 " 2x write interval (-w) !\n");
2032 if (config_write_jitter > config_write_interval)
2033 fprintf(stderr, "WARNING: write delay (-z) should NOT be larger than"
2034 " write interval (-w) !\n");
2037 } /* }}} int read_options */
2039 int main (int argc, char **argv)
2043 status = read_options (argc, argv);
2051 status = daemonize ();
2054 struct sigaction sigchld;
2056 memset (&sigchld, 0, sizeof (sigchld));
2057 sigchld.sa_handler = SIG_IGN;
2058 sigaction (SIGCHLD, &sigchld, NULL);
2062 else if (status != 0)
2064 fprintf (stderr, "daemonize failed, exiting.\n");
2068 if (journal_cur != NULL)
2070 int had_journal = 0;
2072 pthread_mutex_lock(&journal_lock);
2074 RRDD_LOG(LOG_INFO, "checking for journal files");
2076 had_journal += journal_replay(journal_old);
2077 had_journal += journal_replay(journal_cur);
2080 flush_old_values(-1);
2082 pthread_mutex_unlock(&journal_lock);
2085 RRDD_LOG(LOG_INFO, "journal processing complete");
2088 /* start the queue thread */
2089 memset (&queue_thread, 0, sizeof (queue_thread));
2090 status = pthread_create (&queue_thread,
2096 RRDD_LOG (LOG_ERR, "FATAL: cannot create queue thread");
2101 listen_thread_main (NULL);
2108 * vim: set sw=2 sts=2 ts=8 et fdm=marker :