2 * RRDTool - src/rrd_daemon.c
3 * Copyright (C) 2008 Florian octo Forster
4 * Copyright (C) 2008 Kevin Brintnall
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; only version 2 of the License is applicable.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 * Florian octo Forster <octo at verplant.org>
21 * kevin brintnall <kbrint@rufus.net>
26 * First tell the compiler to stick to the C99 and POSIX standards as close as
29 #ifndef __STRICT_ANSI__ /* {{{ */
30 # define __STRICT_ANSI__
33 #ifndef _ISOC99_SOURCE
34 # define _ISOC99_SOURCE
37 #ifdef _POSIX_C_SOURCE
38 # undef _POSIX_C_SOURCE
40 #define _POSIX_C_SOURCE 200112L
42 /* Single UNIX needed for strdup. */
46 #define _XOPEN_SOURCE 500
63 * Now for some includes..
65 #include "rrd.h" /* {{{ */
66 #include "rrd_client.h"
77 #include <sys/types.h>
81 #include <sys/socket.h>
92 #include <glib-2.0/glib.h>
95 #define RRDD_LOG(severity, ...) syslog ((severity), __VA_ARGS__)
98 # define __attribute__(x) /**/
110 struct listen_socket_s
113 char addr[PATH_MAX + 1];
115 socket_privilege privilege;
117 typedef struct listen_socket_s listen_socket_t;
120 typedef struct cache_item_s cache_item_t;
126 time_t last_flush_time;
127 #define CI_FLAGS_IN_TREE (1<<0)
128 #define CI_FLAGS_IN_QUEUE (1<<1)
130 pthread_cond_t flushed;
134 struct callback_flush_data_s
141 typedef struct callback_flush_data_s callback_flush_data_t;
148 typedef enum queue_side_e queue_side_t;
150 /* max length of socket command or response */
156 static int stay_foreground = 0;
158 static listen_socket_t *listen_fds = NULL;
159 static size_t listen_fds_num = 0;
161 static int do_shutdown = 0;
163 static pthread_t queue_thread;
165 static pthread_t *connection_threads = NULL;
166 static pthread_mutex_t connection_threads_lock = PTHREAD_MUTEX_INITIALIZER;
167 static int connection_threads_num = 0;
170 static GTree *cache_tree = NULL;
171 static cache_item_t *cache_queue_head = NULL;
172 static cache_item_t *cache_queue_tail = NULL;
173 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
174 static pthread_cond_t cache_cond = PTHREAD_COND_INITIALIZER;
176 static int config_write_interval = 300;
177 static int config_write_jitter = 0;
178 static int config_flush_interval = 3600;
179 static int config_flush_at_shutdown = 0;
180 static char *config_pid_file = NULL;
181 static char *config_base_dir = NULL;
183 static listen_socket_t **config_listen_address_list = NULL;
184 static int config_listen_address_list_len = 0;
186 static uint64_t stats_queue_length = 0;
187 static uint64_t stats_updates_received = 0;
188 static uint64_t stats_flush_received = 0;
189 static uint64_t stats_updates_written = 0;
190 static uint64_t stats_data_sets_written = 0;
191 static uint64_t stats_journal_bytes = 0;
192 static uint64_t stats_journal_rotate = 0;
193 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
195 /* Journaled updates */
196 static char *journal_cur = NULL;
197 static char *journal_old = NULL;
198 static FILE *journal_fh = NULL;
199 static pthread_mutex_t journal_lock = PTHREAD_MUTEX_INITIALIZER;
200 static int journal_write(char *cmd, char *args);
201 static void journal_done(void);
202 static void journal_rotate(void);
207 static void sig_common (const char *sig) /* {{{ */
209 RRDD_LOG(LOG_NOTICE, "caught SIG%s", sig);
211 pthread_cond_broadcast(&cache_cond);
212 } /* }}} void sig_common */
214 static void sig_int_handler (int s __attribute__((unused))) /* {{{ */
217 } /* }}} void sig_int_handler */
219 static void sig_term_handler (int s __attribute__((unused))) /* {{{ */
222 } /* }}} void sig_term_handler */
224 static void sig_usr1_handler (int s __attribute__((unused))) /* {{{ */
226 config_flush_at_shutdown = 1;
228 } /* }}} void sig_usr1_handler */
230 static void sig_usr2_handler (int s __attribute__((unused))) /* {{{ */
232 config_flush_at_shutdown = 0;
234 } /* }}} void sig_usr2_handler */
236 static void install_signal_handlers(void) /* {{{ */
238 /* These structures are static, because `sigaction' behaves weird if the are
240 static struct sigaction sa_int;
241 static struct sigaction sa_term;
242 static struct sigaction sa_pipe;
243 static struct sigaction sa_usr1;
244 static struct sigaction sa_usr2;
246 /* Install signal handlers */
247 memset (&sa_int, 0, sizeof (sa_int));
248 sa_int.sa_handler = sig_int_handler;
249 sigaction (SIGINT, &sa_int, NULL);
251 memset (&sa_term, 0, sizeof (sa_term));
252 sa_term.sa_handler = sig_term_handler;
253 sigaction (SIGTERM, &sa_term, NULL);
255 memset (&sa_pipe, 0, sizeof (sa_pipe));
256 sa_pipe.sa_handler = SIG_IGN;
257 sigaction (SIGPIPE, &sa_pipe, NULL);
259 memset (&sa_pipe, 0, sizeof (sa_usr1));
260 sa_usr1.sa_handler = sig_usr1_handler;
261 sigaction (SIGUSR1, &sa_usr1, NULL);
263 memset (&sa_usr2, 0, sizeof (sa_usr2));
264 sa_usr2.sa_handler = sig_usr2_handler;
265 sigaction (SIGUSR2, &sa_usr2, NULL);
267 } /* }}} void install_signal_handlers */
269 static int open_pidfile(void) /* {{{ */
274 file = (config_pid_file != NULL)
276 : LOCALSTATEDIR "/run/rrdcached.pid";
278 fd = open(file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IRGRP|S_IROTH);
280 fprintf(stderr, "FATAL: cannot create '%s' (%s)\n",
281 file, rrd_strerror(errno));
284 } /* }}} static int open_pidfile */
286 static int write_pidfile (int fd) /* {{{ */
293 fh = fdopen (fd, "w");
296 RRDD_LOG (LOG_ERR, "write_pidfile: fdopen() failed.");
301 fprintf (fh, "%i\n", (int) pid);
305 } /* }}} int write_pidfile */
307 static int remove_pidfile (void) /* {{{ */
312 file = (config_pid_file != NULL)
314 : LOCALSTATEDIR "/run/rrdcached.pid";
316 status = unlink (file);
320 } /* }}} int remove_pidfile */
322 static ssize_t sread (int fd, void *buffer_void, size_t buffer_size) /* {{{ */
329 buffer = (char *) buffer_void;
331 buffer_free = buffer_size;
333 while (buffer_free > 0)
335 status = read (fd, buffer + buffer_used, buffer_free);
336 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
345 assert ((0 > status) || (buffer_free >= (size_t) status));
347 buffer_free = buffer_free - status;
348 buffer_used = buffer_used + status;
350 if (buffer[buffer_used - 1] == '\n')
354 assert (buffer_used > 0);
356 if (buffer[buffer_used - 1] != '\n')
362 buffer[buffer_used - 1] = 0;
364 /* Fix network line endings. */
365 if ((buffer_used > 1) && (buffer[buffer_used - 2] == '\r'))
368 buffer[buffer_used - 1] = 0;
371 return (buffer_used);
372 } /* }}} ssize_t sread */
374 static ssize_t swrite (int fd, const void *buf, size_t count) /* {{{ */
380 /* special case for journal replay */
381 if (fd < 0) return 0;
383 ptr = (const char *) buf;
388 status = write (fd, (const void *) ptr, nleft);
390 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
401 } /* }}} ssize_t swrite */
403 static void _wipe_ci_values(cache_item_t *ci, time_t when)
408 ci->last_flush_time = when;
409 if (config_write_jitter > 0)
410 ci->last_flush_time += (random() % config_write_jitter);
412 ci->flags &= ~(CI_FLAGS_IN_QUEUE);
416 * enqueue_cache_item:
417 * `cache_lock' must be acquired before calling this function!
419 static int enqueue_cache_item (cache_item_t *ci, /* {{{ */
427 if (ci->values_num == 0)
432 if ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
434 assert (ci->next == NULL);
435 ci->next = cache_queue_head;
436 cache_queue_head = ci;
438 if (cache_queue_tail == NULL)
439 cache_queue_tail = cache_queue_head;
443 else if (cache_queue_head == ci)
447 else /* enqueued, but not first entry */
451 /* find previous entry */
452 for (prev = cache_queue_head; prev != NULL; prev = prev->next)
453 if (prev->next == ci)
455 assert (prev != NULL);
457 /* move to the front */
458 prev->next = ci->next;
459 ci->next = cache_queue_head;
460 cache_queue_head = ci;
462 /* check if we need to adapt the tail */
463 if (cache_queue_tail == ci)
464 cache_queue_tail = prev;
467 else /* (side == TAIL) */
469 /* We don't move values back in the list.. */
470 if ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
473 assert (ci->next == NULL);
475 if (cache_queue_tail == NULL)
476 cache_queue_head = ci;
478 cache_queue_tail->next = ci;
479 cache_queue_tail = ci;
484 ci->flags |= CI_FLAGS_IN_QUEUE;
488 pthread_cond_broadcast(&cache_cond);
489 pthread_mutex_lock (&stats_lock);
490 stats_queue_length++;
491 pthread_mutex_unlock (&stats_lock);
495 } /* }}} int enqueue_cache_item */
498 * tree_callback_flush:
499 * Called via `g_tree_foreach' in `queue_thread_main'. `cache_lock' is held
500 * while this is in progress.
502 static gboolean tree_callback_flush (gpointer key, gpointer value, /* {{{ */
506 callback_flush_data_t *cfd;
508 ci = (cache_item_t *) value;
509 cfd = (callback_flush_data_t *) data;
511 if ((ci->last_flush_time <= cfd->abs_timeout)
512 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
513 && (ci->values_num > 0))
515 enqueue_cache_item (ci, TAIL);
517 else if ((do_shutdown != 0)
518 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
519 && (ci->values_num > 0))
521 enqueue_cache_item (ci, TAIL);
523 else if (((cfd->now - ci->last_flush_time) >= config_flush_interval)
524 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
525 && (ci->values_num <= 0))
529 temp = (char **) realloc (cfd->keys,
530 sizeof (char *) * (cfd->keys_num + 1));
533 RRDD_LOG (LOG_ERR, "tree_callback_flush: realloc failed.");
537 /* Make really sure this points to the _same_ place */
538 assert ((char *) key == ci->file);
539 cfd->keys[cfd->keys_num] = (char *) key;
544 } /* }}} gboolean tree_callback_flush */
546 static int flush_old_values (int max_age)
548 callback_flush_data_t cfd;
551 memset (&cfd, 0, sizeof (cfd));
552 /* Pass the current time as user data so that we don't need to call
553 * `time' for each node. */
554 cfd.now = time (NULL);
559 cfd.abs_timeout = cfd.now - max_age;
561 cfd.abs_timeout = cfd.now + 2*config_write_jitter + 1;
563 /* `tree_callback_flush' will return the keys of all values that haven't
564 * been touched in the last `config_flush_interval' seconds in `cfd'.
565 * The char*'s in this array point to the same memory as ci->file, so we
566 * don't need to free them separately. */
567 g_tree_foreach (cache_tree, tree_callback_flush, (gpointer) &cfd);
569 for (k = 0; k < cfd.keys_num; k++)
573 /* This must not fail. */
574 ci = (cache_item_t *) g_tree_lookup (cache_tree, cfd.keys[k]);
577 /* If we end up here with values available, something's seriously
579 assert (ci->values_num == 0);
581 /* Remove the node from the tree */
582 g_tree_remove (cache_tree, cfd.keys[k]);
585 /* Now free and clean up `ci'. */
590 } /* for (k = 0; k < cfd.keys_num; k++) */
592 if (cfd.keys != NULL)
599 } /* int flush_old_values */
601 static void *queue_thread_main (void *args __attribute__((unused))) /* {{{ */
604 struct timespec next_flush;
605 int final_flush = 0; /* make sure we only flush once on shutdown */
607 gettimeofday (&now, NULL);
608 next_flush.tv_sec = now.tv_sec + config_flush_interval;
609 next_flush.tv_nsec = 1000 * now.tv_usec;
611 pthread_mutex_lock (&cache_lock);
612 while ((do_shutdown == 0) || (cache_queue_head != NULL))
621 /* First, check if it's time to do the cache flush. */
622 gettimeofday (&now, NULL);
623 if ((now.tv_sec > next_flush.tv_sec)
624 || ((now.tv_sec == next_flush.tv_sec)
625 && ((1000 * now.tv_usec) > next_flush.tv_nsec)))
627 /* Flush all values that haven't been written in the last
628 * `config_write_interval' seconds. */
629 flush_old_values (config_write_interval);
631 /* Determine the time of the next cache flush. */
632 while (next_flush.tv_sec <= now.tv_sec)
633 next_flush.tv_sec += config_flush_interval;
635 /* unlock the cache while we rotate so we don't block incoming
636 * updates if the fsync() blocks on disk I/O */
637 pthread_mutex_unlock(&cache_lock);
639 pthread_mutex_lock(&cache_lock);
642 /* Now, check if there's something to store away. If not, wait until
643 * something comes in or it's time to do the cache flush. if we are
644 * shutting down, do not wait around. */
645 if (cache_queue_head == NULL && !do_shutdown)
647 status = pthread_cond_timedwait (&cache_cond, &cache_lock, &next_flush);
648 if ((status != 0) && (status != ETIMEDOUT))
650 RRDD_LOG (LOG_ERR, "queue_thread_main: "
651 "pthread_cond_timedwait returned %i.", status);
655 /* We're about to shut down */
656 if (do_shutdown != 0 && !final_flush++)
658 if (config_flush_at_shutdown)
659 flush_old_values (-1); /* flush everything */
664 /* Check if a value has arrived. This may be NULL if we timed out or there
665 * was an interrupt such as a signal. */
666 if (cache_queue_head == NULL)
669 ci = cache_queue_head;
671 /* copy the relevant parts */
672 file = strdup (ci->file);
675 RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
679 assert(ci->values != NULL);
680 assert(ci->values_num > 0);
683 values_num = ci->values_num;
685 _wipe_ci_values(ci, time(NULL));
687 cache_queue_head = ci->next;
688 if (cache_queue_head == NULL)
689 cache_queue_tail = NULL;
692 pthread_mutex_lock (&stats_lock);
693 assert (stats_queue_length > 0);
694 stats_queue_length--;
695 pthread_mutex_unlock (&stats_lock);
697 pthread_mutex_unlock (&cache_lock);
700 status = rrd_update_r (file, NULL, values_num, (void *) values);
703 RRDD_LOG (LOG_NOTICE, "queue_thread_main: "
704 "rrd_update_r (%s) failed with status %i. (%s)",
705 file, status, rrd_get_error());
708 journal_write("wrote", file);
709 pthread_cond_broadcast(&ci->flushed);
711 for (i = 0; i < values_num; i++)
719 pthread_mutex_lock (&stats_lock);
720 stats_updates_written++;
721 stats_data_sets_written += values_num;
722 pthread_mutex_unlock (&stats_lock);
725 pthread_mutex_lock (&cache_lock);
727 /* We're about to shut down */
728 if (do_shutdown != 0 && !final_flush++)
730 if (config_flush_at_shutdown)
731 flush_old_values (-1); /* flush everything */
735 } /* while ((do_shutdown == 0) || (cache_queue_head != NULL)) */
736 pthread_mutex_unlock (&cache_lock);
738 if (config_flush_at_shutdown)
740 assert(cache_queue_head == NULL);
741 RRDD_LOG(LOG_INFO, "clean shutdown; all RRDs flushed");
747 } /* }}} void *queue_thread_main */
749 static int buffer_get_field (char **buffer_ret, /* {{{ */
750 size_t *buffer_size_ret, char **field_ret)
759 buffer = *buffer_ret;
761 buffer_size = *buffer_size_ret;
765 if (buffer_size <= 0)
768 /* This is ensured by `handle_request'. */
769 assert (buffer[buffer_size - 1] == '\0');
772 while (buffer_pos < buffer_size)
774 /* Check for end-of-field or end-of-buffer */
775 if (buffer[buffer_pos] == ' ' || buffer[buffer_pos] == '\0')
777 field[field_size] = 0;
783 /* Handle escaped characters. */
784 else if (buffer[buffer_pos] == '\\')
786 if (buffer_pos >= (buffer_size - 1))
789 field[field_size] = buffer[buffer_pos];
793 /* Normal operation */
796 field[field_size] = buffer[buffer_pos];
800 } /* while (buffer_pos < buffer_size) */
805 *buffer_ret = buffer + buffer_pos;
806 *buffer_size_ret = buffer_size - buffer_pos;
810 } /* }}} int buffer_get_field */
812 static int flush_file (const char *filename) /* {{{ */
816 pthread_mutex_lock (&cache_lock);
818 ci = (cache_item_t *) g_tree_lookup (cache_tree, filename);
821 pthread_mutex_unlock (&cache_lock);
825 if (ci->values_num > 0)
827 /* Enqueue at head */
828 enqueue_cache_item (ci, HEAD);
829 pthread_cond_wait(&ci->flushed, &cache_lock);
832 pthread_mutex_unlock(&cache_lock);
835 } /* }}} int flush_file */
837 static int handle_request_help (int fd, /* {{{ */
838 char *buffer, size_t buffer_size)
842 size_t help_text_len;
848 "5 Command overview\n",
849 "FLUSH <filename>\n",
851 "HELP [<command>]\n",
852 "UPDATE <filename> <values> [<values> ...]\n",
855 size_t help_help_len = sizeof (help_help) / sizeof (help_help[0]);
859 "4 Help for FLUSH\n",
860 "Usage: FLUSH <filename>\n",
862 "Adds the given filename to the head of the update queue and returns\n",
863 "after is has been dequeued.\n"
865 size_t help_flush_len = sizeof (help_flush) / sizeof (help_flush[0]);
867 char *help_flushall[] =
869 "3 Help for FLUSHALL\n",
872 "Triggers writing of all pending updates. Returns immediately.\n"
874 size_t help_flushall_len = sizeof(help_flushall) / sizeof(help_flushall[0]);
876 char *help_update[] =
878 "9 Help for UPDATE\n",
879 "Usage: UPDATE <filename> <values> [<values> ...]\n"
881 "Adds the given file to the internal cache if it is not yet known and\n",
882 "appends the given value(s) to the entry. See the rrdcached(1) manpage\n",
885 "Each <values> has the following form:\n",
886 " <values> = <time>:<value>[:<value>[...]]\n",
887 "See the rrdupdate(1) manpage for details.\n"
889 size_t help_update_len = sizeof (help_update) / sizeof (help_update[0]);
893 "4 Help for STATS\n",
896 "Returns some performance counters, see the rrdcached(1) manpage for\n",
897 "a description of the values.\n"
899 size_t help_stats_len = sizeof (help_stats) / sizeof (help_stats[0]);
901 status = buffer_get_field (&buffer, &buffer_size, &command);
904 help_text = help_help;
905 help_text_len = help_help_len;
909 if (strcasecmp (command, "update") == 0)
911 help_text = help_update;
912 help_text_len = help_update_len;
914 else if (strcasecmp (command, "flush") == 0)
916 help_text = help_flush;
917 help_text_len = help_flush_len;
919 else if (strcasecmp (command, "flushall") == 0)
921 help_text = help_flushall;
922 help_text_len = help_flushall_len;
924 else if (strcasecmp (command, "stats") == 0)
926 help_text = help_stats;
927 help_text_len = help_stats_len;
931 help_text = help_help;
932 help_text_len = help_help_len;
936 for (i = 0; i < help_text_len; i++)
938 status = swrite (fd, help_text[i], strlen (help_text[i]));
942 RRDD_LOG (LOG_ERR, "handle_request_help: swrite returned an error.");
948 } /* }}} int handle_request_help */
950 static int handle_request_stats (int fd, /* {{{ */
951 char *buffer __attribute__((unused)),
952 size_t buffer_size __attribute__((unused)))
955 char outbuf[CMD_MAX];
957 uint64_t copy_queue_length;
958 uint64_t copy_updates_received;
959 uint64_t copy_flush_received;
960 uint64_t copy_updates_written;
961 uint64_t copy_data_sets_written;
962 uint64_t copy_journal_bytes;
963 uint64_t copy_journal_rotate;
965 uint64_t tree_nodes_number;
968 pthread_mutex_lock (&stats_lock);
969 copy_queue_length = stats_queue_length;
970 copy_updates_received = stats_updates_received;
971 copy_flush_received = stats_flush_received;
972 copy_updates_written = stats_updates_written;
973 copy_data_sets_written = stats_data_sets_written;
974 copy_journal_bytes = stats_journal_bytes;
975 copy_journal_rotate = stats_journal_rotate;
976 pthread_mutex_unlock (&stats_lock);
978 pthread_mutex_lock (&cache_lock);
979 tree_nodes_number = (uint64_t) g_tree_nnodes (cache_tree);
980 tree_depth = (uint64_t) g_tree_height (cache_tree);
981 pthread_mutex_unlock (&cache_lock);
983 #define RRDD_STATS_SEND \
984 outbuf[sizeof (outbuf) - 1] = 0; \
985 status = swrite (fd, outbuf, strlen (outbuf)); \
989 RRDD_LOG (LOG_INFO, "handle_request_stats: swrite returned an error."); \
993 strncpy (outbuf, "9 Statistics follow\n", sizeof (outbuf));
996 snprintf (outbuf, sizeof (outbuf),
997 "QueueLength: %"PRIu64"\n", copy_queue_length);
1000 snprintf (outbuf, sizeof (outbuf),
1001 "UpdatesReceived: %"PRIu64"\n", copy_updates_received);
1004 snprintf (outbuf, sizeof (outbuf),
1005 "FlushesReceived: %"PRIu64"\n", copy_flush_received);
1008 snprintf (outbuf, sizeof (outbuf),
1009 "UpdatesWritten: %"PRIu64"\n", copy_updates_written);
1012 snprintf (outbuf, sizeof (outbuf),
1013 "DataSetsWritten: %"PRIu64"\n", copy_data_sets_written);
1016 snprintf (outbuf, sizeof (outbuf),
1017 "TreeNodesNumber: %"PRIu64"\n", tree_nodes_number);
1020 snprintf (outbuf, sizeof (outbuf),
1021 "TreeDepth: %"PRIu64"\n", tree_depth);
1024 snprintf (outbuf, sizeof(outbuf),
1025 "JournalBytes: %"PRIu64"\n", copy_journal_bytes);
1028 snprintf (outbuf, sizeof(outbuf),
1029 "JournalRotate: %"PRIu64"\n", copy_journal_rotate);
1033 #undef RRDD_STATS_SEND
1034 } /* }}} int handle_request_stats */
1036 static int handle_request_flush (int fd, /* {{{ */
1037 char *buffer, size_t buffer_size)
1041 char result[CMD_MAX];
1043 status = buffer_get_field (&buffer, &buffer_size, &file);
1046 strncpy (result, "-1 Usage: flush <filename>\n", sizeof (result));
1050 pthread_mutex_lock(&stats_lock);
1051 stats_flush_received++;
1052 pthread_mutex_unlock(&stats_lock);
1054 status = flush_file (file);
1056 snprintf (result, sizeof (result), "0 Successfully flushed %s.\n", file);
1057 else if (status == ENOENT)
1059 /* no file in our tree; see whether it exists at all */
1060 struct stat statbuf;
1062 memset(&statbuf, 0, sizeof(statbuf));
1063 if (stat(file, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
1064 snprintf (result, sizeof (result), "0 Nothing to flush: %s.\n", file);
1066 snprintf (result, sizeof (result), "-1 No such file: %s.\n", file);
1068 else if (status < 0)
1069 strncpy (result, "-1 Internal error.\n", sizeof (result));
1071 snprintf (result, sizeof (result), "-1 Failed with status %i.\n", status);
1073 result[sizeof (result) - 1] = 0;
1075 status = swrite (fd, result, strlen (result));
1079 RRDD_LOG (LOG_INFO, "handle_request_flush: swrite returned an error.");
1084 } /* }}} int handle_request_flush */
1086 static int handle_request_flushall(int fd) /* {{{ */
1089 char answer[] ="0 Started flush.\n";
1091 RRDD_LOG(LOG_DEBUG, "Received FLUSHALL");
1093 pthread_mutex_lock(&cache_lock);
1094 flush_old_values(-1);
1095 pthread_mutex_unlock(&cache_lock);
1097 status = swrite(fd, answer, strlen(answer));
1101 RRDD_LOG(LOG_INFO, "handle_request_flushall: swrite returned an error.");
1105 } /* }}} static int handle_request_flushall */
1107 static int handle_request_update (int fd, /* {{{ */
1108 char *buffer, size_t buffer_size)
1117 char answer[CMD_MAX];
1119 #define RRDD_UPDATE_SEND \
1120 answer[sizeof (answer) - 1] = 0; \
1121 status = swrite (fd, answer, strlen (answer)); \
1125 RRDD_LOG (LOG_INFO, "handle_request_update: swrite returned an error."); \
1131 status = buffer_get_field (&buffer, &buffer_size, &file);
1134 strncpy (answer, "-1 Usage: UPDATE <filename> <values> [<values> ...]\n",
1140 pthread_mutex_lock(&stats_lock);
1141 stats_updates_received++;
1142 pthread_mutex_unlock(&stats_lock);
1144 pthread_mutex_lock (&cache_lock);
1145 ci = g_tree_lookup (cache_tree, file);
1147 if (ci == NULL) /* {{{ */
1149 struct stat statbuf;
1151 /* don't hold the lock while we setup; stat(2) might block */
1152 pthread_mutex_unlock(&cache_lock);
1154 memset (&statbuf, 0, sizeof (statbuf));
1155 status = stat (file, &statbuf);
1158 RRDD_LOG (LOG_NOTICE, "handle_request_update: stat (%s) failed.", file);
1161 if (status == ENOENT)
1162 snprintf (answer, sizeof (answer), "-1 No such file: %s\n", file);
1164 snprintf (answer, sizeof (answer), "-1 stat failed with error %i.\n",
1169 if (!S_ISREG (statbuf.st_mode))
1171 snprintf (answer, sizeof (answer), "-1 Not a regular file: %s\n", file);
1175 if (access(file, R_OK|W_OK) != 0)
1177 snprintf (answer, sizeof (answer), "-1 Cannot read/write %s: %s\n",
1178 file, rrd_strerror(errno));
1183 ci = (cache_item_t *) malloc (sizeof (cache_item_t));
1186 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
1188 strncpy (answer, "-1 malloc failed.\n", sizeof (answer));
1192 memset (ci, 0, sizeof (cache_item_t));
1194 ci->file = strdup (file);
1195 if (ci->file == NULL)
1198 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
1200 strncpy (answer, "-1 strdup failed.\n", sizeof (answer));
1205 _wipe_ci_values(ci, now);
1206 ci->flags = CI_FLAGS_IN_TREE;
1208 pthread_mutex_lock(&cache_lock);
1209 g_tree_insert (cache_tree, (void *) ci->file, (void *) ci);
1211 assert (ci != NULL);
1213 while (buffer_size > 0)
1218 status = buffer_get_field (&buffer, &buffer_size, &value);
1221 RRDD_LOG (LOG_INFO, "handle_request_update: Error reading field.");
1225 temp = (char **) realloc (ci->values,
1226 sizeof (char *) * (ci->values_num + 1));
1229 RRDD_LOG (LOG_ERR, "handle_request_update: realloc failed.");
1234 ci->values[ci->values_num] = strdup (value);
1235 if (ci->values[ci->values_num] == NULL)
1237 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
1245 if (((now - ci->last_flush_time) >= config_write_interval)
1246 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
1247 && (ci->values_num > 0))
1249 enqueue_cache_item (ci, TAIL);
1252 pthread_mutex_unlock (&cache_lock);
1256 strncpy (answer, "-1 No values updated.\n", sizeof (answer));
1260 snprintf (answer, sizeof (answer), "0 Enqueued %i value%s\n", values_num,
1261 (values_num == 1) ? "" : "s");
1265 #undef RRDD_UPDATE_SEND
1266 } /* }}} int handle_request_update */
1268 /* we came across a "WROTE" entry during journal replay.
1269 * throw away any values that we have accumulated for this file
1271 static int handle_request_wrote (int fd __attribute__((unused)), /* {{{ */
1273 size_t buffer_size __attribute__((unused)))
1277 const char *file = buffer;
1279 pthread_mutex_lock(&cache_lock);
1281 ci = g_tree_lookup(cache_tree, file);
1284 pthread_mutex_unlock(&cache_lock);
1290 for (i=0; i < ci->values_num; i++)
1291 free(ci->values[i]);
1296 _wipe_ci_values(ci, time(NULL));
1298 pthread_mutex_unlock(&cache_lock);
1300 } /* }}} int handle_request_wrote */
1302 /* returns 1 if we have the required privilege level */
1303 static int has_privilege (socket_privilege priv, /* {{{ */
1304 socket_privilege required, int fd)
1307 char error[CMD_MAX];
1309 if (priv >= required)
1312 sprintf(error, "-1 %s\n", rrd_strerror(EACCES));
1313 status = swrite(fd, error, strlen(error));
1319 } /* }}} static int has_privilege */
1321 /* if fd < 0, we are in journal replay mode */
1322 static int handle_request (int fd, socket_privilege privilege, /* {{{ */
1323 char *buffer, size_t buffer_size)
1329 assert (buffer[buffer_size - 1] == '\0');
1331 buffer_ptr = buffer;
1333 status = buffer_get_field (&buffer_ptr, &buffer_size, &command);
1336 RRDD_LOG (LOG_INFO, "handle_request: Unable parse command.");
1340 if (strcasecmp (command, "update") == 0)
1342 /* don't re-write updates in replay mode */
1344 journal_write(command, buffer_ptr);
1346 status = has_privilege(privilege, PRIV_HIGH, fd);
1350 return (handle_request_update (fd, buffer_ptr, buffer_size));
1352 else if (strcasecmp (command, "wrote") == 0 && fd < 0)
1354 /* this is only valid in replay mode */
1355 return (handle_request_wrote (fd, buffer_ptr, buffer_size));
1357 else if (strcasecmp (command, "flush") == 0)
1359 return (handle_request_flush (fd, buffer_ptr, buffer_size));
1361 else if (strcasecmp (command, "flushall") == 0)
1363 status = has_privilege(privilege, PRIV_HIGH, fd);
1367 return (handle_request_flushall(fd));
1369 else if (strcasecmp (command, "stats") == 0)
1371 return (handle_request_stats (fd, buffer_ptr, buffer_size));
1373 else if (strcasecmp (command, "help") == 0)
1375 return (handle_request_help (fd, buffer_ptr, buffer_size));
1379 char result[CMD_MAX];
1381 snprintf (result, sizeof (result), "-1 Unknown command: %s\n", command);
1382 result[sizeof (result) - 1] = 0;
1384 status = swrite (fd, result, strlen (result));
1387 RRDD_LOG (LOG_ERR, "handle_request: swrite failed.");
1393 } /* }}} int handle_request */
1395 /* MUST NOT hold journal_lock before calling this */
1396 static void journal_rotate(void) /* {{{ */
1398 FILE *old_fh = NULL;
1400 if (journal_cur == NULL || journal_old == NULL)
1403 pthread_mutex_lock(&journal_lock);
1405 /* we rotate this way (rename before close) so that the we can release
1406 * the journal lock as fast as possible. Journal writes to the new
1407 * journal can proceed immediately after the new file is opened. The
1408 * fclose can then block without affecting new updates.
1410 if (journal_fh != NULL)
1412 old_fh = journal_fh;
1413 rename(journal_cur, journal_old);
1414 ++stats_journal_rotate;
1417 journal_fh = fopen(journal_cur, "a");
1418 pthread_mutex_unlock(&journal_lock);
1423 if (journal_fh == NULL)
1426 "JOURNALING DISABLED: Cannot open journal file '%s' : (%s)",
1427 journal_cur, rrd_strerror(errno));
1430 "JOURNALING DISABLED: All values will be flushed at shutdown");
1431 config_flush_at_shutdown = 1;
1434 } /* }}} static void journal_rotate */
1436 static void journal_done(void) /* {{{ */
1438 if (journal_cur == NULL)
1441 pthread_mutex_lock(&journal_lock);
1442 if (journal_fh != NULL)
1448 if (config_flush_at_shutdown)
1450 RRDD_LOG(LOG_INFO, "removing journals");
1451 unlink(journal_old);
1452 unlink(journal_cur);
1456 RRDD_LOG(LOG_INFO, "expedited shutdown; "
1457 "journals will be used at next startup");
1460 pthread_mutex_unlock(&journal_lock);
1462 } /* }}} static void journal_done */
1464 static int journal_write(char *cmd, char *args) /* {{{ */
1468 if (journal_fh == NULL)
1471 pthread_mutex_lock(&journal_lock);
1472 chars = fprintf(journal_fh, "%s %s\n", cmd, args);
1473 pthread_mutex_unlock(&journal_lock);
1477 pthread_mutex_lock(&stats_lock);
1478 stats_journal_bytes += chars;
1479 pthread_mutex_unlock(&stats_lock);
1483 } /* }}} static int journal_write */
1485 static int journal_replay (const char *file) /* {{{ */
1491 char entry[CMD_MAX];
1493 if (file == NULL) return 0;
1495 fh = fopen(file, "r");
1498 if (errno != ENOENT)
1499 RRDD_LOG(LOG_ERR, "journal_replay: cannot open journal file: '%s' (%s)",
1500 file, rrd_strerror(errno));
1504 RRDD_LOG(LOG_NOTICE, "replaying from journal: %s", file);
1511 if (fgets(entry, sizeof(entry), fh) == NULL)
1513 entry_len = strlen(entry);
1515 /* check \n termination in case journal writing crashed mid-line */
1518 else if (entry[entry_len - 1] != '\n')
1520 RRDD_LOG(LOG_NOTICE, "Malformed journal entry at line %"PRIu64, line);
1525 entry[entry_len - 1] = '\0';
1527 if (handle_request(-1, PRIV_HIGH, entry, entry_len) == 0)
1537 RRDD_LOG(LOG_INFO, "Replayed %d entries (%d failures)",
1538 entry_cnt, fail_cnt);
1544 } /* }}} static int journal_replay */
1546 static void *connection_thread_main (void *args) /* {{{ */
1549 listen_socket_t *sock;
1553 sock = (listen_socket_t *) args;
1556 pthread_mutex_lock (&connection_threads_lock);
1560 temp = (pthread_t *) realloc (connection_threads,
1561 sizeof (pthread_t) * (connection_threads_num + 1));
1564 RRDD_LOG (LOG_ERR, "connection_thread_main: realloc failed.");
1568 connection_threads = temp;
1569 connection_threads[connection_threads_num] = pthread_self ();
1570 connection_threads_num++;
1573 pthread_mutex_unlock (&connection_threads_lock);
1575 while (do_shutdown == 0)
1577 char buffer[CMD_MAX];
1579 struct pollfd pollfd;
1583 pollfd.events = POLLIN | POLLPRI;
1586 status = poll (&pollfd, 1, /* timeout = */ 500);
1589 else if (status == 0) /* timeout */
1591 else if (status < 0) /* error */
1594 if (status == EINTR)
1596 RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
1600 if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
1605 else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
1607 RRDD_LOG (LOG_WARNING, "connection_thread_main: "
1608 "poll(2) returned something unexpected: %#04hx",
1614 status = (int) sread (fd, buffer, sizeof (buffer));
1620 RRDD_LOG(LOG_ERR, "connection_thread_main: sread failed.");
1625 status = handle_request (fd, sock->privilege, buffer, status);
1633 self = pthread_self ();
1634 /* Remove this thread from the connection threads list */
1635 pthread_mutex_lock (&connection_threads_lock);
1636 /* Find out own index in the array */
1637 for (i = 0; i < connection_threads_num; i++)
1638 if (pthread_equal (connection_threads[i], self) != 0)
1640 assert (i < connection_threads_num);
1642 /* Move the trailing threads forward. */
1643 if (i < (connection_threads_num - 1))
1645 memmove (connection_threads + i,
1646 connection_threads + i + 1,
1647 sizeof (pthread_t) * (connection_threads_num - i - 1));
1650 connection_threads_num--;
1651 pthread_mutex_unlock (&connection_threads_lock);
1654 } /* }}} void *connection_thread_main */
1656 static int open_listen_socket_unix (const listen_socket_t *sock) /* {{{ */
1659 struct sockaddr_un sa;
1660 listen_socket_t *temp;
1665 if (strncmp(path, "unix:", strlen("unix:")) == 0)
1666 path += strlen("unix:");
1668 temp = (listen_socket_t *) realloc (listen_fds,
1669 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1672 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: realloc failed.");
1676 memcpy (listen_fds + listen_fds_num, sock, sizeof (listen_fds[0]));
1678 fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
1681 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: socket(2) failed.");
1685 memset (&sa, 0, sizeof (sa));
1686 sa.sun_family = AF_UNIX;
1687 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
1689 status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
1692 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: bind(2) failed.");
1698 status = listen (fd, /* backlog = */ 10);
1701 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: listen(2) failed.");
1707 listen_fds[listen_fds_num].fd = fd;
1708 listen_fds[listen_fds_num].family = PF_UNIX;
1709 strncpy(listen_fds[listen_fds_num].addr, path,
1710 sizeof (listen_fds[listen_fds_num].addr) - 1);
1714 } /* }}} int open_listen_socket_unix */
1716 static int open_listen_socket_network(const listen_socket_t *sock) /* {{{ */
1718 struct addrinfo ai_hints;
1719 struct addrinfo *ai_res;
1720 struct addrinfo *ai_ptr;
1721 char addr_copy[NI_MAXHOST];
1726 strncpy (addr_copy, sock->addr, sizeof (addr_copy));
1727 addr_copy[sizeof (addr_copy) - 1] = 0;
1730 memset (&ai_hints, 0, sizeof (ai_hints));
1731 ai_hints.ai_flags = 0;
1732 #ifdef AI_ADDRCONFIG
1733 ai_hints.ai_flags |= AI_ADDRCONFIG;
1735 ai_hints.ai_family = AF_UNSPEC;
1736 ai_hints.ai_socktype = SOCK_STREAM;
1739 if (*addr == '[') /* IPv6+port format */
1741 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
1744 port = strchr (addr, ']');
1747 RRDD_LOG (LOG_ERR, "open_listen_socket_network: Malformed address: %s",
1756 else if (*port == 0)
1760 RRDD_LOG (LOG_ERR, "open_listen_socket_network: Garbage after address: %s",
1764 } /* if (*addr = ']') */
1765 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
1767 port = rindex(addr, ':');
1775 status = getaddrinfo (addr,
1776 port == NULL ? RRDCACHED_DEFAULT_PORT : port,
1777 &ai_hints, &ai_res);
1780 RRDD_LOG (LOG_ERR, "open_listen_socket_network: getaddrinfo(%s) failed: "
1781 "%s", addr, gai_strerror (status));
1785 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1788 listen_socket_t *temp;
1791 temp = (listen_socket_t *) realloc (listen_fds,
1792 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1795 RRDD_LOG (LOG_ERR, "open_listen_socket_network: realloc failed.");
1799 memcpy (listen_fds + listen_fds_num, sock, sizeof (listen_fds[0]));
1801 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1804 RRDD_LOG (LOG_ERR, "open_listen_socket_network: socket(2) failed.");
1808 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1810 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1813 RRDD_LOG (LOG_ERR, "open_listen_socket_network: bind(2) failed.");
1818 status = listen (fd, /* backlog = */ 10);
1821 RRDD_LOG (LOG_ERR, "open_listen_socket_network: listen(2) failed.");
1826 listen_fds[listen_fds_num].fd = fd;
1827 listen_fds[listen_fds_num].family = ai_ptr->ai_family;
1829 } /* for (ai_ptr) */
1832 } /* }}} static int open_listen_socket_network */
1834 static int open_listen_socket (const listen_socket_t *sock) /* {{{ */
1836 assert(sock != NULL);
1837 assert(sock->addr != NULL);
1839 if (strncmp ("unix:", sock->addr, strlen ("unix:")) == 0
1840 || sock->addr[0] == '/')
1841 return (open_listen_socket_unix(sock));
1843 return (open_listen_socket_network(sock));
1844 } /* }}} int open_listen_socket */
1846 static int close_listen_sockets (void) /* {{{ */
1850 for (i = 0; i < listen_fds_num; i++)
1852 close (listen_fds[i].fd);
1854 if (listen_fds[i].family == PF_UNIX)
1855 unlink(listen_fds[i].addr);
1863 } /* }}} int close_listen_sockets */
1865 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
1867 struct pollfd *pollfds;
1872 for (i = 0; i < config_listen_address_list_len; i++)
1873 open_listen_socket (config_listen_address_list[i]);
1875 if (config_listen_address_list_len < 1)
1877 listen_socket_t sock;
1878 memset(&sock, 0, sizeof(sock));
1879 strncpy(sock.addr, RRDCACHED_DEFAULT_ADDRESS, sizeof(sock.addr));
1880 open_listen_socket (&sock);
1883 if (listen_fds_num < 1)
1885 RRDD_LOG (LOG_ERR, "listen_thread_main: No listen sockets "
1886 "could be opened. Sorry.");
1890 pollfds_num = listen_fds_num;
1891 pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
1892 if (pollfds == NULL)
1894 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1897 memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
1899 RRDD_LOG(LOG_INFO, "listening for connections");
1901 while (do_shutdown == 0)
1903 assert (pollfds_num == ((int) listen_fds_num));
1904 for (i = 0; i < pollfds_num; i++)
1906 pollfds[i].fd = listen_fds[i].fd;
1907 pollfds[i].events = POLLIN | POLLPRI;
1908 pollfds[i].revents = 0;
1911 status = poll (pollfds, pollfds_num, /* timeout = */ 1000);
1914 else if (status == 0) /* timeout */
1916 else if (status < 0) /* error */
1919 if (status != EINTR)
1921 RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
1926 for (i = 0; i < pollfds_num; i++)
1928 listen_socket_t *client_sock;
1929 struct sockaddr_storage client_sa;
1930 socklen_t client_sa_size;
1932 pthread_attr_t attr;
1934 if (pollfds[i].revents == 0)
1937 if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
1939 RRDD_LOG (LOG_ERR, "listen_thread_main: "
1940 "poll(2) returned something unexpected for listen FD #%i.",
1945 client_sock = (listen_socket_t *) malloc (sizeof (listen_socket_t));
1946 if (client_sock == NULL)
1948 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1951 memcpy(client_sock, &listen_fds[i], sizeof(listen_fds[0]));
1953 client_sa_size = sizeof (client_sa);
1954 client_sock->fd = accept (pollfds[i].fd,
1955 (struct sockaddr *) &client_sa, &client_sa_size);
1956 if (client_sock->fd < 0)
1958 RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
1963 pthread_attr_init (&attr);
1964 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
1966 status = pthread_create (&tid, &attr, connection_thread_main,
1970 RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
1971 close (client_sock->fd);
1975 } /* for (pollfds_num) */
1976 } /* while (do_shutdown == 0) */
1978 RRDD_LOG(LOG_INFO, "starting shutdown");
1980 close_listen_sockets ();
1982 pthread_mutex_lock (&connection_threads_lock);
1983 while (connection_threads_num > 0)
1987 wait_for = connection_threads[0];
1989 pthread_mutex_unlock (&connection_threads_lock);
1990 pthread_join (wait_for, /* retval = */ NULL);
1991 pthread_mutex_lock (&connection_threads_lock);
1993 pthread_mutex_unlock (&connection_threads_lock);
1996 } /* }}} void *listen_thread_main */
1998 static int daemonize (void) /* {{{ */
2004 fd = open_pidfile();
2005 if (fd < 0) return fd;
2007 if (!stay_foreground)
2014 fprintf (stderr, "daemonize: fork(2) failed.\n");
2022 /* Become session leader */
2025 /* Open the first three file descriptors to /dev/null */
2030 open ("/dev/null", O_RDWR);
2033 } /* if (!stay_foreground) */
2035 /* Change into the /tmp directory. */
2036 base_dir = (config_base_dir != NULL)
2039 status = chdir (base_dir);
2042 fprintf (stderr, "daemonize: chdir (%s) failed.\n", base_dir);
2046 install_signal_handlers();
2048 openlog ("rrdcached", LOG_PID, LOG_DAEMON);
2049 RRDD_LOG(LOG_INFO, "starting up");
2051 cache_tree = g_tree_new ((GCompareFunc) strcmp);
2052 if (cache_tree == NULL)
2054 RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
2058 status = write_pidfile (fd);
2060 } /* }}} int daemonize */
2062 static int cleanup (void) /* {{{ */
2066 pthread_cond_signal (&cache_cond);
2067 pthread_join (queue_thread, /* return = */ NULL);
2071 RRDD_LOG(LOG_INFO, "goodbye");
2075 } /* }}} int cleanup */
2077 static int read_options (int argc, char **argv) /* {{{ */
2082 while ((option = getopt(argc, argv, "gl:L:f:w:b:z:p:j:h?F")) != -1)
2093 listen_socket_t **temp;
2094 listen_socket_t *new;
2096 new = malloc(sizeof(listen_socket_t));
2099 fprintf(stderr, "read_options: malloc failed.\n");
2102 memset(new, 0, sizeof(listen_socket_t));
2104 temp = (listen_socket_t **) realloc (config_listen_address_list,
2105 sizeof (listen_socket_t *) * (config_listen_address_list_len + 1));
2108 fprintf (stderr, "read_options: realloc failed.\n");
2111 config_listen_address_list = temp;
2113 strncpy(new->addr, optarg, sizeof(new->addr)-1);
2114 new->privilege = (option == 'l') ? PRIV_HIGH : PRIV_LOW;
2116 temp[config_listen_address_list_len] = new;
2117 config_listen_address_list_len++;
2125 temp = atoi (optarg);
2127 config_flush_interval = temp;
2130 fprintf (stderr, "Invalid flush interval: %s\n", optarg);
2140 temp = atoi (optarg);
2142 config_write_interval = temp;
2145 fprintf (stderr, "Invalid write interval: %s\n", optarg);
2155 temp = atoi(optarg);
2157 config_write_jitter = temp;
2160 fprintf (stderr, "Invalid write jitter: -z %s\n", optarg);
2171 if (config_base_dir != NULL)
2172 free (config_base_dir);
2173 config_base_dir = strdup (optarg);
2174 if (config_base_dir == NULL)
2176 fprintf (stderr, "read_options: strdup failed.\n");
2180 len = strlen (config_base_dir);
2181 while ((len > 0) && (config_base_dir[len - 1] == '/'))
2183 config_base_dir[len - 1] = 0;
2189 fprintf (stderr, "Invalid base directory: %s\n", optarg);
2197 if (config_pid_file != NULL)
2198 free (config_pid_file);
2199 config_pid_file = strdup (optarg);
2200 if (config_pid_file == NULL)
2202 fprintf (stderr, "read_options: strdup failed.\n");
2209 config_flush_at_shutdown = 1;
2214 struct stat statbuf;
2215 const char *dir = optarg;
2217 status = stat(dir, &statbuf);
2220 fprintf(stderr, "Cannot stat '%s' : %s\n", dir, rrd_strerror(errno));
2224 if (!S_ISDIR(statbuf.st_mode)
2225 || access(dir, R_OK|W_OK|X_OK) != 0)
2227 fprintf(stderr, "Must specify a writable directory with -j! (%s)\n",
2228 errno ? rrd_strerror(errno) : "");
2232 journal_cur = malloc(PATH_MAX + 1);
2233 journal_old = malloc(PATH_MAX + 1);
2234 if (journal_cur == NULL || journal_old == NULL)
2236 fprintf(stderr, "malloc failure for journal files\n");
2241 snprintf(journal_cur, PATH_MAX, "%s/rrd.journal", dir);
2242 snprintf(journal_old, PATH_MAX, "%s/rrd.journal.old", dir);
2249 printf ("RRDCacheD %s Copyright (C) 2008 Florian octo Forster\n"
2251 "Usage: rrdcached [options]\n"
2253 "Valid options are:\n"
2254 " -l <address> Socket address to listen to.\n"
2255 " -L <address> Socket address to listen to ('FLUSH' only).\n"
2256 " -w <seconds> Interval in which to write data.\n"
2257 " -z <delay> Delay writes up to <delay> seconds to spread load\n"
2258 " -f <seconds> Interval in which to flush dead data.\n"
2259 " -p <file> Location of the PID-file.\n"
2260 " -b <dir> Base directory to change to.\n"
2261 " -g Do not fork and run in the foreground.\n"
2262 " -j <dir> Directory in which to create the journal files.\n"
2263 " -F Always flush all updates at shutdown\n"
2265 "For more information and a detailed description of all options "
2267 "to the rrdcached(1) manual page.\n",
2271 } /* switch (option) */
2272 } /* while (getopt) */
2274 /* advise the user when values are not sane */
2275 if (config_flush_interval < 2 * config_write_interval)
2276 fprintf(stderr, "WARNING: flush interval (-f) should be at least"
2277 " 2x write interval (-w) !\n");
2278 if (config_write_jitter > config_write_interval)
2279 fprintf(stderr, "WARNING: write delay (-z) should NOT be larger than"
2280 " write interval (-w) !\n");
2282 if (journal_cur == NULL)
2283 config_flush_at_shutdown = 1;
2286 } /* }}} int read_options */
2288 int main (int argc, char **argv)
2292 status = read_options (argc, argv);
2300 status = daemonize ();
2303 struct sigaction sigchld;
2305 memset (&sigchld, 0, sizeof (sigchld));
2306 sigchld.sa_handler = SIG_IGN;
2307 sigaction (SIGCHLD, &sigchld, NULL);
2311 else if (status != 0)
2313 fprintf (stderr, "daemonize failed, exiting.\n");
2317 if (journal_cur != NULL)
2319 int had_journal = 0;
2321 pthread_mutex_lock(&journal_lock);
2323 RRDD_LOG(LOG_INFO, "checking for journal files");
2325 had_journal += journal_replay(journal_old);
2326 had_journal += journal_replay(journal_cur);
2329 flush_old_values(-1);
2331 pthread_mutex_unlock(&journal_lock);
2334 RRDD_LOG(LOG_INFO, "journal processing complete");
2337 /* start the queue thread */
2338 memset (&queue_thread, 0, sizeof (queue_thread));
2339 status = pthread_create (&queue_thread,
2345 RRDD_LOG (LOG_ERR, "FATAL: cannot create queue thread");
2350 listen_thread_main (NULL);
2357 * vim: set sw=2 sts=2 ts=8 et fdm=marker :