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 typedef enum { RESP_ERR = -1, RESP_OK = 0 } response_code;
112 struct listen_socket_s
115 char addr[PATH_MAX + 1];
117 socket_privilege privilege;
127 typedef struct listen_socket_s listen_socket_t;
130 typedef struct cache_item_s cache_item_t;
136 time_t last_flush_time;
137 #define CI_FLAGS_IN_TREE (1<<0)
138 #define CI_FLAGS_IN_QUEUE (1<<1)
140 pthread_cond_t flushed;
145 struct callback_flush_data_s
152 typedef struct callback_flush_data_s callback_flush_data_t;
159 typedef enum queue_side_e queue_side_t;
161 /* max length of socket command or response */
163 #define RBUF_SIZE (CMD_MAX*2)
168 static int stay_foreground = 0;
170 static listen_socket_t *listen_fds = NULL;
171 static size_t listen_fds_num = 0;
173 static int do_shutdown = 0;
175 static pthread_t queue_thread;
177 static pthread_t *connection_threads = NULL;
178 static pthread_mutex_t connection_threads_lock = PTHREAD_MUTEX_INITIALIZER;
179 static int connection_threads_num = 0;
182 static GTree *cache_tree = NULL;
183 static cache_item_t *cache_queue_head = NULL;
184 static cache_item_t *cache_queue_tail = NULL;
185 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
186 static pthread_cond_t cache_cond = PTHREAD_COND_INITIALIZER;
188 static int config_write_interval = 300;
189 static int config_write_jitter = 0;
190 static int config_flush_interval = 3600;
191 static int config_flush_at_shutdown = 0;
192 static char *config_pid_file = NULL;
193 static char *config_base_dir = NULL;
194 static size_t _config_base_dir_len = 0;
195 static int config_write_base_only = 0;
197 static listen_socket_t **config_listen_address_list = NULL;
198 static int config_listen_address_list_len = 0;
200 static uint64_t stats_queue_length = 0;
201 static uint64_t stats_updates_received = 0;
202 static uint64_t stats_flush_received = 0;
203 static uint64_t stats_updates_written = 0;
204 static uint64_t stats_data_sets_written = 0;
205 static uint64_t stats_journal_bytes = 0;
206 static uint64_t stats_journal_rotate = 0;
207 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
209 /* Journaled updates */
210 static char *journal_cur = NULL;
211 static char *journal_old = NULL;
212 static FILE *journal_fh = NULL;
213 static pthread_mutex_t journal_lock = PTHREAD_MUTEX_INITIALIZER;
214 static int journal_write(char *cmd, char *args);
215 static void journal_done(void);
216 static void journal_rotate(void);
221 static void sig_common (const char *sig) /* {{{ */
223 RRDD_LOG(LOG_NOTICE, "caught SIG%s", sig);
225 pthread_cond_broadcast(&cache_cond);
226 } /* }}} void sig_common */
228 static void sig_int_handler (int s __attribute__((unused))) /* {{{ */
231 } /* }}} void sig_int_handler */
233 static void sig_term_handler (int s __attribute__((unused))) /* {{{ */
236 } /* }}} void sig_term_handler */
238 static void sig_usr1_handler (int s __attribute__((unused))) /* {{{ */
240 config_flush_at_shutdown = 1;
242 } /* }}} void sig_usr1_handler */
244 static void sig_usr2_handler (int s __attribute__((unused))) /* {{{ */
246 config_flush_at_shutdown = 0;
248 } /* }}} void sig_usr2_handler */
250 static void install_signal_handlers(void) /* {{{ */
252 /* These structures are static, because `sigaction' behaves weird if the are
254 static struct sigaction sa_int;
255 static struct sigaction sa_term;
256 static struct sigaction sa_pipe;
257 static struct sigaction sa_usr1;
258 static struct sigaction sa_usr2;
260 /* Install signal handlers */
261 memset (&sa_int, 0, sizeof (sa_int));
262 sa_int.sa_handler = sig_int_handler;
263 sigaction (SIGINT, &sa_int, NULL);
265 memset (&sa_term, 0, sizeof (sa_term));
266 sa_term.sa_handler = sig_term_handler;
267 sigaction (SIGTERM, &sa_term, NULL);
269 memset (&sa_pipe, 0, sizeof (sa_pipe));
270 sa_pipe.sa_handler = SIG_IGN;
271 sigaction (SIGPIPE, &sa_pipe, NULL);
273 memset (&sa_pipe, 0, sizeof (sa_usr1));
274 sa_usr1.sa_handler = sig_usr1_handler;
275 sigaction (SIGUSR1, &sa_usr1, NULL);
277 memset (&sa_usr2, 0, sizeof (sa_usr2));
278 sa_usr2.sa_handler = sig_usr2_handler;
279 sigaction (SIGUSR2, &sa_usr2, NULL);
281 } /* }}} void install_signal_handlers */
283 static int open_pidfile(void) /* {{{ */
288 file = (config_pid_file != NULL)
290 : LOCALSTATEDIR "/run/rrdcached.pid";
292 fd = open(file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IRGRP|S_IROTH);
294 fprintf(stderr, "FATAL: cannot create '%s' (%s)\n",
295 file, rrd_strerror(errno));
298 } /* }}} static int open_pidfile */
300 static int write_pidfile (int fd) /* {{{ */
307 fh = fdopen (fd, "w");
310 RRDD_LOG (LOG_ERR, "write_pidfile: fdopen() failed.");
315 fprintf (fh, "%i\n", (int) pid);
319 } /* }}} int write_pidfile */
321 static int remove_pidfile (void) /* {{{ */
326 file = (config_pid_file != NULL)
328 : LOCALSTATEDIR "/run/rrdcached.pid";
330 status = unlink (file);
334 } /* }}} int remove_pidfile */
336 static char *next_cmd (listen_socket_t *sock, ssize_t *len) /* {{{ */
340 eol = memchr(sock->rbuf + sock->next_cmd, '\n',
341 sock->next_read - sock->next_cmd);
345 /* no commands left, move remainder back to front of rbuf */
346 memmove(sock->rbuf, sock->rbuf + sock->next_cmd,
347 sock->next_read - sock->next_cmd);
348 sock->next_read -= sock->next_cmd;
355 char *cmd = sock->rbuf + sock->next_cmd;
358 sock->next_cmd = eol - sock->rbuf + 1;
360 if (eol > sock->rbuf && *(eol-1) == '\r')
361 *(--eol) = '\0'; /* handle "\r\n" EOL */
372 /* add the characters directly to the write buffer */
373 static int add_to_wbuf(listen_socket_t *sock, char *str, size_t len) /* {{{ */
377 assert(sock != NULL);
379 new_buf = realloc(sock->wbuf, sock->wbuf_len + len + 1);
382 RRDD_LOG(LOG_ERR, "add_to_wbuf: realloc failed");
386 strncpy(new_buf + sock->wbuf_len, str, len + 1);
388 sock->wbuf = new_buf;
389 sock->wbuf_len += len;
392 } /* }}} static int add_to_wbuf */
394 /* add the text to the "extra" info that's sent after the status line */
395 static int add_response_info(listen_socket_t *sock, char *fmt, ...) /* {{{ */
398 char buffer[CMD_MAX];
401 if (sock == NULL) return 0; /* journal replay mode */
404 #ifdef HAVE_VSNPRINTF
405 len = vsnprintf(buffer, sizeof(buffer)-1, fmt, argp);
407 len = vsprintf(buffer, fmt, argp);
412 RRDD_LOG(LOG_ERR, "add_response_info: vnsprintf failed");
416 return add_to_wbuf(sock, buffer, len);
417 } /* }}} static int add_response_info */
419 static int count_lines(char *str) /* {{{ */
425 while ((str = strchr(str, '\n')) != NULL)
433 } /* }}} static int count_lines */
435 /* send the response back to the user.
436 * returns 0 on success, -1 on error
437 * write buffer is always zeroed after this call */
438 static int send_response (listen_socket_t *sock, response_code rc,
439 char *fmt, ...) /* {{{ */
442 char buffer[CMD_MAX];
447 if (sock == NULL) return rc; /* journal replay mode */
451 lines = count_lines(sock->wbuf);
456 rclen = sprintf(buffer, "%d ", lines);
458 #ifdef HAVE_VSNPRINTF
459 len = vsnprintf(buffer+rclen, sizeof(buffer)-rclen-1, fmt, argp);
461 len = vsprintf(buffer+rclen, fmt, argp);
469 /* first write must be complete */
470 if (len != write(sock->fd, buffer, len))
472 RRDD_LOG(LOG_INFO, "send_response: could not write status message");
476 if (sock->wbuf != NULL)
479 while (wrote < sock->wbuf_len)
481 ssize_t wb = write(sock->fd, sock->wbuf + wrote, sock->wbuf_len - wrote);
484 RRDD_LOG(LOG_INFO, "send_response: could not write results");
491 free(sock->wbuf); sock->wbuf = NULL;
497 static void wipe_ci_values(cache_item_t *ci, time_t when)
502 ci->last_flush_time = when;
503 if (config_write_jitter > 0)
504 ci->last_flush_time += (random() % config_write_jitter);
508 * remove a "cache_item_t" item from the queue.
509 * must hold 'cache_lock' when calling this
511 static void remove_from_queue(cache_item_t *ci) /* {{{ */
513 if (ci == NULL) return;
515 if (ci->prev == NULL)
516 cache_queue_head = ci->next; /* reset head */
518 ci->prev->next = ci->next;
520 if (ci->next == NULL)
521 cache_queue_tail = ci->prev; /* reset the tail */
523 ci->next->prev = ci->prev;
525 ci->next = ci->prev = NULL;
526 ci->flags &= ~CI_FLAGS_IN_QUEUE;
527 } /* }}} static void remove_from_queue */
530 * enqueue_cache_item:
531 * `cache_lock' must be acquired before calling this function!
533 static int enqueue_cache_item (cache_item_t *ci, /* {{{ */
539 if (ci->values_num == 0)
544 if (cache_queue_head == ci)
547 /* remove from the double linked list */
548 if (ci->flags & CI_FLAGS_IN_QUEUE)
549 remove_from_queue(ci);
552 ci->next = cache_queue_head;
553 if (ci->next != NULL)
555 cache_queue_head = ci;
557 if (cache_queue_tail == NULL)
558 cache_queue_tail = cache_queue_head;
560 else /* (side == TAIL) */
562 /* We don't move values back in the list.. */
563 if (ci->flags & CI_FLAGS_IN_QUEUE)
566 assert (ci->next == NULL);
567 assert (ci->prev == NULL);
569 ci->prev = cache_queue_tail;
571 if (cache_queue_tail == NULL)
572 cache_queue_head = ci;
574 cache_queue_tail->next = ci;
576 cache_queue_tail = ci;
579 ci->flags |= CI_FLAGS_IN_QUEUE;
581 pthread_cond_broadcast(&cache_cond);
582 pthread_mutex_lock (&stats_lock);
583 stats_queue_length++;
584 pthread_mutex_unlock (&stats_lock);
587 } /* }}} int enqueue_cache_item */
590 * tree_callback_flush:
591 * Called via `g_tree_foreach' in `queue_thread_main'. `cache_lock' is held
592 * while this is in progress.
594 static gboolean tree_callback_flush (gpointer key, gpointer value, /* {{{ */
598 callback_flush_data_t *cfd;
600 ci = (cache_item_t *) value;
601 cfd = (callback_flush_data_t *) data;
603 if ((ci->last_flush_time <= cfd->abs_timeout)
604 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
605 && (ci->values_num > 0))
607 enqueue_cache_item (ci, TAIL);
609 else if ((do_shutdown != 0)
610 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
611 && (ci->values_num > 0))
613 enqueue_cache_item (ci, TAIL);
615 else if (((cfd->now - ci->last_flush_time) >= config_flush_interval)
616 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
617 && (ci->values_num <= 0))
621 temp = (char **) realloc (cfd->keys,
622 sizeof (char *) * (cfd->keys_num + 1));
625 RRDD_LOG (LOG_ERR, "tree_callback_flush: realloc failed.");
629 /* Make really sure this points to the _same_ place */
630 assert ((char *) key == ci->file);
631 cfd->keys[cfd->keys_num] = (char *) key;
636 } /* }}} gboolean tree_callback_flush */
638 static int flush_old_values (int max_age)
640 callback_flush_data_t cfd;
643 memset (&cfd, 0, sizeof (cfd));
644 /* Pass the current time as user data so that we don't need to call
645 * `time' for each node. */
646 cfd.now = time (NULL);
651 cfd.abs_timeout = cfd.now - max_age;
653 cfd.abs_timeout = cfd.now + 2*config_write_jitter + 1;
655 /* `tree_callback_flush' will return the keys of all values that haven't
656 * been touched in the last `config_flush_interval' seconds in `cfd'.
657 * The char*'s in this array point to the same memory as ci->file, so we
658 * don't need to free them separately. */
659 g_tree_foreach (cache_tree, tree_callback_flush, (gpointer) &cfd);
661 for (k = 0; k < cfd.keys_num; k++)
665 /* This must not fail. */
666 ci = (cache_item_t *) g_tree_lookup (cache_tree, cfd.keys[k]);
669 /* If we end up here with values available, something's seriously
671 assert (ci->values_num == 0);
673 /* Remove the node from the tree */
674 g_tree_remove (cache_tree, cfd.keys[k]);
677 /* Now free and clean up `ci'. */
682 } /* for (k = 0; k < cfd.keys_num; k++) */
684 if (cfd.keys != NULL)
691 } /* int flush_old_values */
693 static void *queue_thread_main (void *args __attribute__((unused))) /* {{{ */
696 struct timespec next_flush;
697 int final_flush = 0; /* make sure we only flush once on shutdown */
699 gettimeofday (&now, NULL);
700 next_flush.tv_sec = now.tv_sec + config_flush_interval;
701 next_flush.tv_nsec = 1000 * now.tv_usec;
703 pthread_mutex_lock (&cache_lock);
704 while ((do_shutdown == 0) || (cache_queue_head != NULL))
713 /* First, check if it's time to do the cache flush. */
714 gettimeofday (&now, NULL);
715 if ((now.tv_sec > next_flush.tv_sec)
716 || ((now.tv_sec == next_flush.tv_sec)
717 && ((1000 * now.tv_usec) > next_flush.tv_nsec)))
719 /* Flush all values that haven't been written in the last
720 * `config_write_interval' seconds. */
721 flush_old_values (config_write_interval);
723 /* Determine the time of the next cache flush. */
724 while (next_flush.tv_sec <= now.tv_sec)
725 next_flush.tv_sec += config_flush_interval;
727 /* unlock the cache while we rotate so we don't block incoming
728 * updates if the fsync() blocks on disk I/O */
729 pthread_mutex_unlock(&cache_lock);
731 pthread_mutex_lock(&cache_lock);
734 /* Now, check if there's something to store away. If not, wait until
735 * something comes in or it's time to do the cache flush. if we are
736 * shutting down, do not wait around. */
737 if (cache_queue_head == NULL && !do_shutdown)
739 status = pthread_cond_timedwait (&cache_cond, &cache_lock, &next_flush);
740 if ((status != 0) && (status != ETIMEDOUT))
742 RRDD_LOG (LOG_ERR, "queue_thread_main: "
743 "pthread_cond_timedwait returned %i.", status);
747 /* We're about to shut down */
748 if (do_shutdown != 0 && !final_flush++)
750 if (config_flush_at_shutdown)
751 flush_old_values (-1); /* flush everything */
756 /* Check if a value has arrived. This may be NULL if we timed out or there
757 * was an interrupt such as a signal. */
758 if (cache_queue_head == NULL)
761 ci = cache_queue_head;
763 /* copy the relevant parts */
764 file = strdup (ci->file);
767 RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
771 assert(ci->values != NULL);
772 assert(ci->values_num > 0);
775 values_num = ci->values_num;
777 wipe_ci_values(ci, time(NULL));
778 remove_from_queue(ci);
780 pthread_mutex_lock (&stats_lock);
781 assert (stats_queue_length > 0);
782 stats_queue_length--;
783 pthread_mutex_unlock (&stats_lock);
785 pthread_mutex_unlock (&cache_lock);
788 status = rrd_update_r (file, NULL, values_num, (void *) values);
791 RRDD_LOG (LOG_NOTICE, "queue_thread_main: "
792 "rrd_update_r (%s) failed with status %i. (%s)",
793 file, status, rrd_get_error());
796 journal_write("wrote", file);
797 pthread_cond_broadcast(&ci->flushed);
799 for (i = 0; i < values_num; i++)
807 pthread_mutex_lock (&stats_lock);
808 stats_updates_written++;
809 stats_data_sets_written += values_num;
810 pthread_mutex_unlock (&stats_lock);
813 pthread_mutex_lock (&cache_lock);
815 /* We're about to shut down */
816 if (do_shutdown != 0 && !final_flush++)
818 if (config_flush_at_shutdown)
819 flush_old_values (-1); /* flush everything */
823 } /* while ((do_shutdown == 0) || (cache_queue_head != NULL)) */
824 pthread_mutex_unlock (&cache_lock);
826 if (config_flush_at_shutdown)
828 assert(cache_queue_head == NULL);
829 RRDD_LOG(LOG_INFO, "clean shutdown; all RRDs flushed");
835 } /* }}} void *queue_thread_main */
837 static int buffer_get_field (char **buffer_ret, /* {{{ */
838 size_t *buffer_size_ret, char **field_ret)
847 buffer = *buffer_ret;
849 buffer_size = *buffer_size_ret;
853 if (buffer_size <= 0)
856 /* This is ensured by `handle_request'. */
857 assert (buffer[buffer_size - 1] == '\0');
860 while (buffer_pos < buffer_size)
862 /* Check for end-of-field or end-of-buffer */
863 if (buffer[buffer_pos] == ' ' || buffer[buffer_pos] == '\0')
865 field[field_size] = 0;
871 /* Handle escaped characters. */
872 else if (buffer[buffer_pos] == '\\')
874 if (buffer_pos >= (buffer_size - 1))
877 field[field_size] = buffer[buffer_pos];
881 /* Normal operation */
884 field[field_size] = buffer[buffer_pos];
888 } /* while (buffer_pos < buffer_size) */
893 *buffer_ret = buffer + buffer_pos;
894 *buffer_size_ret = buffer_size - buffer_pos;
898 } /* }}} int buffer_get_field */
900 /* if we're restricting writes to the base directory,
901 * check whether the file falls within the dir
902 * returns 1 if OK, otherwise 0
904 static int check_file_access (const char *file, listen_socket_t *sock) /* {{{ */
906 assert(file != NULL);
908 if (!config_write_base_only
909 || sock == NULL /* journal replay */
910 || config_base_dir == NULL)
913 if (strstr(file, "../") != NULL) goto err;
915 /* relative paths without "../" are ok */
916 if (*file != '/') return 1;
918 /* file must be of the format base + "/" + <1+ char filename> */
919 if (strlen(file) < _config_base_dir_len + 2) goto err;
920 if (strncmp(file, config_base_dir, _config_base_dir_len) != 0) goto err;
921 if (*(file + _config_base_dir_len) != '/') goto err;
926 if (sock != NULL && sock->fd >= 0)
927 send_response(sock, RESP_ERR, "%s\n", rrd_strerror(EACCES));
930 } /* }}} static int check_file_access */
932 static int flush_file (const char *filename) /* {{{ */
936 pthread_mutex_lock (&cache_lock);
938 ci = (cache_item_t *) g_tree_lookup (cache_tree, filename);
941 pthread_mutex_unlock (&cache_lock);
945 if (ci->values_num > 0)
947 /* Enqueue at head */
948 enqueue_cache_item (ci, HEAD);
949 pthread_cond_wait(&ci->flushed, &cache_lock);
952 pthread_mutex_unlock(&cache_lock);
955 } /* }}} int flush_file */
957 static int handle_request_help (listen_socket_t *sock, /* {{{ */
958 char *buffer, size_t buffer_size)
971 "UPDATE <filename> <values> [<values> ...]\n"
975 char *help_flush[2] =
979 "Usage: FLUSH <filename>\n"
981 "Adds the given filename to the head of the update queue and returns\n"
982 "after is has been dequeued.\n"
985 char *help_flushall[2] =
987 "Help for FLUSHALL\n"
991 "Triggers writing of all pending updates. Returns immediately.\n"
994 char *help_update[2] =
998 "Usage: UPDATE <filename> <values> [<values> ...]\n"
1000 "Adds the given file to the internal cache if it is not yet known and\n"
1001 "appends the given value(s) to the entry. See the rrdcached(1) manpage\n"
1004 "Each <values> has the following form:\n"
1005 " <values> = <time>:<value>[:<value>[...]]\n"
1006 "See the rrdupdate(1) manpage for details.\n"
1009 char *help_stats[2] =
1015 "Returns some performance counters, see the rrdcached(1) manpage for\n"
1016 "a description of the values.\n"
1019 status = buffer_get_field (&buffer, &buffer_size, &command);
1021 help_text = help_help;
1024 if (strcasecmp (command, "update") == 0)
1025 help_text = help_update;
1026 else if (strcasecmp (command, "flush") == 0)
1027 help_text = help_flush;
1028 else if (strcasecmp (command, "flushall") == 0)
1029 help_text = help_flushall;
1030 else if (strcasecmp (command, "stats") == 0)
1031 help_text = help_stats;
1033 help_text = help_help;
1036 add_response_info(sock, help_text[1]);
1037 return send_response(sock, RESP_OK, help_text[0]);
1038 } /* }}} int handle_request_help */
1040 static int handle_request_stats (listen_socket_t *sock) /* {{{ */
1042 uint64_t copy_queue_length;
1043 uint64_t copy_updates_received;
1044 uint64_t copy_flush_received;
1045 uint64_t copy_updates_written;
1046 uint64_t copy_data_sets_written;
1047 uint64_t copy_journal_bytes;
1048 uint64_t copy_journal_rotate;
1050 uint64_t tree_nodes_number;
1051 uint64_t tree_depth;
1053 pthread_mutex_lock (&stats_lock);
1054 copy_queue_length = stats_queue_length;
1055 copy_updates_received = stats_updates_received;
1056 copy_flush_received = stats_flush_received;
1057 copy_updates_written = stats_updates_written;
1058 copy_data_sets_written = stats_data_sets_written;
1059 copy_journal_bytes = stats_journal_bytes;
1060 copy_journal_rotate = stats_journal_rotate;
1061 pthread_mutex_unlock (&stats_lock);
1063 pthread_mutex_lock (&cache_lock);
1064 tree_nodes_number = (uint64_t) g_tree_nnodes (cache_tree);
1065 tree_depth = (uint64_t) g_tree_height (cache_tree);
1066 pthread_mutex_unlock (&cache_lock);
1068 add_response_info(sock,
1069 "QueueLength: %"PRIu64"\n", copy_queue_length);
1070 add_response_info(sock,
1071 "UpdatesReceived: %"PRIu64"\n", copy_updates_received);
1072 add_response_info(sock,
1073 "FlushesReceived: %"PRIu64"\n", copy_flush_received);
1074 add_response_info(sock,
1075 "UpdatesWritten: %"PRIu64"\n", copy_updates_written);
1076 add_response_info(sock,
1077 "DataSetsWritten: %"PRIu64"\n", copy_data_sets_written);
1078 add_response_info(sock, "TreeNodesNumber: %"PRIu64"\n", tree_nodes_number);
1079 add_response_info(sock, "TreeDepth: %"PRIu64"\n", tree_depth);
1080 add_response_info(sock, "JournalBytes: %"PRIu64"\n", copy_journal_bytes);
1081 add_response_info(sock, "JournalRotate: %"PRIu64"\n", copy_journal_rotate);
1083 send_response(sock, RESP_OK, "Statistics follow\n");
1086 } /* }}} int handle_request_stats */
1088 static int handle_request_flush (listen_socket_t *sock, /* {{{ */
1089 char *buffer, size_t buffer_size)
1094 status = buffer_get_field (&buffer, &buffer_size, &file);
1097 return send_response(sock, RESP_ERR, "Usage: flush <filename>\n");
1101 pthread_mutex_lock(&stats_lock);
1102 stats_flush_received++;
1103 pthread_mutex_unlock(&stats_lock);
1105 if (!check_file_access(file, sock)) return 0;
1107 status = flush_file (file);
1109 return send_response(sock, RESP_OK, "Successfully flushed %s.\n", file);
1110 else if (status == ENOENT)
1112 /* no file in our tree; see whether it exists at all */
1113 struct stat statbuf;
1115 memset(&statbuf, 0, sizeof(statbuf));
1116 if (stat(file, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
1117 return send_response(sock, RESP_OK, "Nothing to flush: %s.\n", file);
1119 return send_response(sock, RESP_ERR, "No such file: %s.\n", file);
1121 else if (status < 0)
1122 return send_response(sock, RESP_ERR, "Internal error.\n");
1124 return send_response(sock, RESP_ERR, "Failed with status %i.\n", status);
1129 } /* }}} int handle_request_slurp */
1131 static int handle_request_flushall(listen_socket_t *sock) /* {{{ */
1134 RRDD_LOG(LOG_DEBUG, "Received FLUSHALL");
1136 pthread_mutex_lock(&cache_lock);
1137 flush_old_values(-1);
1138 pthread_mutex_unlock(&cache_lock);
1140 return send_response(sock, RESP_OK, "Started flush.\n");
1141 } /* }}} static int handle_request_flushall */
1143 static int handle_request_update (listen_socket_t *sock, /* {{{ */
1144 char *buffer, size_t buffer_size)
1155 status = buffer_get_field (&buffer, &buffer_size, &file);
1157 return send_response(sock, RESP_ERR,
1158 "Usage: UPDATE <filename> <values> [<values> ...]\n");
1160 pthread_mutex_lock(&stats_lock);
1161 stats_updates_received++;
1162 pthread_mutex_unlock(&stats_lock);
1164 if (!check_file_access(file, sock)) return 0;
1166 pthread_mutex_lock (&cache_lock);
1167 ci = g_tree_lookup (cache_tree, file);
1169 if (ci == NULL) /* {{{ */
1171 struct stat statbuf;
1173 /* don't hold the lock while we setup; stat(2) might block */
1174 pthread_mutex_unlock(&cache_lock);
1176 memset (&statbuf, 0, sizeof (statbuf));
1177 status = stat (file, &statbuf);
1180 RRDD_LOG (LOG_NOTICE, "handle_request_update: stat (%s) failed.", file);
1183 if (status == ENOENT)
1184 return send_response(sock, RESP_ERR, "No such file: %s\n", file);
1186 return send_response(sock, RESP_ERR,
1187 "stat failed with error %i.\n", status);
1189 if (!S_ISREG (statbuf.st_mode))
1190 return send_response(sock, RESP_ERR, "Not a regular file: %s\n", file);
1192 if (access(file, R_OK|W_OK) != 0)
1193 return send_response(sock, RESP_ERR, "Cannot read/write %s: %s\n",
1194 file, rrd_strerror(errno));
1196 ci = (cache_item_t *) malloc (sizeof (cache_item_t));
1199 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
1201 return send_response(sock, RESP_ERR, "malloc failed.\n");
1203 memset (ci, 0, sizeof (cache_item_t));
1205 ci->file = strdup (file);
1206 if (ci->file == NULL)
1209 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
1211 return send_response(sock, RESP_ERR, "strdup failed.\n");
1214 wipe_ci_values(ci, now);
1215 ci->flags = CI_FLAGS_IN_TREE;
1217 pthread_mutex_lock(&cache_lock);
1218 g_tree_insert (cache_tree, (void *) ci->file, (void *) ci);
1220 assert (ci != NULL);
1222 while (buffer_size > 0)
1227 status = buffer_get_field (&buffer, &buffer_size, &value);
1230 RRDD_LOG (LOG_INFO, "handle_request_update: Error reading field.");
1234 temp = (char **) realloc (ci->values,
1235 sizeof (char *) * (ci->values_num + 1));
1238 RRDD_LOG (LOG_ERR, "handle_request_update: realloc failed.");
1243 ci->values[ci->values_num] = strdup (value);
1244 if (ci->values[ci->values_num] == NULL)
1246 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
1254 if (((now - ci->last_flush_time) >= config_write_interval)
1255 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
1256 && (ci->values_num > 0))
1258 enqueue_cache_item (ci, TAIL);
1261 pthread_mutex_unlock (&cache_lock);
1264 return send_response(sock, RESP_ERR, "No values updated.\n");
1266 return send_response(sock, RESP_OK, "Enqueued %i value(s).\n", values_num);
1271 } /* }}} int handle_request_update */
1273 /* we came across a "WROTE" entry during journal replay.
1274 * throw away any values that we have accumulated for this file
1276 static int handle_request_wrote (const char *buffer) /* {{{ */
1280 const char *file = buffer;
1282 pthread_mutex_lock(&cache_lock);
1284 ci = g_tree_lookup(cache_tree, file);
1287 pthread_mutex_unlock(&cache_lock);
1293 for (i=0; i < ci->values_num; i++)
1294 free(ci->values[i]);
1299 wipe_ci_values(ci, time(NULL));
1300 remove_from_queue(ci);
1302 pthread_mutex_unlock(&cache_lock);
1304 } /* }}} int handle_request_wrote */
1306 /* returns 1 if we have the required privilege level */
1307 static int has_privilege (listen_socket_t *sock, /* {{{ */
1308 socket_privilege priv)
1310 if (sock == NULL) /* journal replay */
1313 if (sock->privilege >= priv)
1316 return send_response(sock, RESP_ERR, "%s\n", rrd_strerror(EACCES));
1317 } /* }}} static int has_privilege */
1319 /* if sock==NULL, we are in journal replay mode */
1320 static int handle_request (listen_socket_t *sock, /* {{{ */
1321 char *buffer, size_t buffer_size)
1327 assert (buffer[buffer_size - 1] == '\0');
1329 buffer_ptr = buffer;
1331 status = buffer_get_field (&buffer_ptr, &buffer_size, &command);
1334 RRDD_LOG (LOG_INFO, "handle_request: Unable parse command.");
1338 if (strcasecmp (command, "update") == 0)
1340 status = has_privilege(sock, PRIV_HIGH);
1344 /* don't re-write updates in replay mode */
1346 journal_write(command, buffer_ptr);
1348 return (handle_request_update (sock, buffer_ptr, buffer_size));
1350 else if (strcasecmp (command, "wrote") == 0 && sock == NULL)
1352 /* this is only valid in replay mode */
1353 return (handle_request_wrote (buffer_ptr));
1355 else if (strcasecmp (command, "flush") == 0)
1356 return (handle_request_flush (sock, buffer_ptr, buffer_size));
1357 else if (strcasecmp (command, "flushall") == 0)
1359 status = has_privilege(sock, PRIV_HIGH);
1363 return (handle_request_flushall(sock));
1365 else if (strcasecmp (command, "stats") == 0)
1366 return (handle_request_stats (sock));
1367 else if (strcasecmp (command, "help") == 0)
1368 return (handle_request_help (sock, buffer_ptr, buffer_size));
1370 return send_response(sock, RESP_ERR, "Unknown command: %s\n", command);
1374 } /* }}} int handle_request */
1376 /* MUST NOT hold journal_lock before calling this */
1377 static void journal_rotate(void) /* {{{ */
1379 FILE *old_fh = NULL;
1381 if (journal_cur == NULL || journal_old == NULL)
1384 pthread_mutex_lock(&journal_lock);
1386 /* we rotate this way (rename before close) so that the we can release
1387 * the journal lock as fast as possible. Journal writes to the new
1388 * journal can proceed immediately after the new file is opened. The
1389 * fclose can then block without affecting new updates.
1391 if (journal_fh != NULL)
1393 old_fh = journal_fh;
1394 rename(journal_cur, journal_old);
1395 ++stats_journal_rotate;
1398 journal_fh = fopen(journal_cur, "a");
1399 pthread_mutex_unlock(&journal_lock);
1404 if (journal_fh == NULL)
1407 "JOURNALING DISABLED: Cannot open journal file '%s' : (%s)",
1408 journal_cur, rrd_strerror(errno));
1411 "JOURNALING DISABLED: All values will be flushed at shutdown");
1412 config_flush_at_shutdown = 1;
1415 } /* }}} static void journal_rotate */
1417 static void journal_done(void) /* {{{ */
1419 if (journal_cur == NULL)
1422 pthread_mutex_lock(&journal_lock);
1423 if (journal_fh != NULL)
1429 if (config_flush_at_shutdown)
1431 RRDD_LOG(LOG_INFO, "removing journals");
1432 unlink(journal_old);
1433 unlink(journal_cur);
1437 RRDD_LOG(LOG_INFO, "expedited shutdown; "
1438 "journals will be used at next startup");
1441 pthread_mutex_unlock(&journal_lock);
1443 } /* }}} static void journal_done */
1445 static int journal_write(char *cmd, char *args) /* {{{ */
1449 if (journal_fh == NULL)
1452 pthread_mutex_lock(&journal_lock);
1453 chars = fprintf(journal_fh, "%s %s\n", cmd, args);
1454 pthread_mutex_unlock(&journal_lock);
1458 pthread_mutex_lock(&stats_lock);
1459 stats_journal_bytes += chars;
1460 pthread_mutex_unlock(&stats_lock);
1464 } /* }}} static int journal_write */
1466 static int journal_replay (const char *file) /* {{{ */
1472 char entry[CMD_MAX];
1474 if (file == NULL) return 0;
1476 fh = fopen(file, "r");
1479 if (errno != ENOENT)
1480 RRDD_LOG(LOG_ERR, "journal_replay: cannot open journal file: '%s' (%s)",
1481 file, rrd_strerror(errno));
1485 RRDD_LOG(LOG_NOTICE, "replaying from journal: %s", file);
1492 if (fgets(entry, sizeof(entry), fh) == NULL)
1494 entry_len = strlen(entry);
1496 /* check \n termination in case journal writing crashed mid-line */
1499 else if (entry[entry_len - 1] != '\n')
1501 RRDD_LOG(LOG_NOTICE, "Malformed journal entry at line %"PRIu64, line);
1506 entry[entry_len - 1] = '\0';
1508 if (handle_request(NULL, entry, entry_len) == 0)
1518 RRDD_LOG(LOG_INFO, "Replayed %d entries (%d failures)",
1519 entry_cnt, fail_cnt);
1525 } /* }}} static int journal_replay */
1527 static void close_connection(listen_socket_t *sock)
1529 close(sock->fd) ; sock->fd = -1;
1530 free(sock->rbuf); sock->rbuf = NULL;
1531 free(sock->wbuf); sock->wbuf = NULL;
1536 static void *connection_thread_main (void *args) /* {{{ */
1539 listen_socket_t *sock;
1543 sock = (listen_socket_t *) args;
1546 /* init read buffers */
1547 sock->next_read = sock->next_cmd = 0;
1548 sock->rbuf = malloc(RBUF_SIZE);
1549 if (sock->rbuf == NULL)
1551 RRDD_LOG(LOG_ERR, "connection_thread_main: cannot malloc read buffer");
1552 close_connection(sock);
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)
1581 struct pollfd pollfd;
1585 pollfd.events = POLLIN | POLLPRI;
1588 status = poll (&pollfd, 1, /* timeout = */ 500);
1591 else if (status == 0) /* timeout */
1593 else if (status < 0) /* error */
1596 if (status == EINTR)
1598 RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
1602 if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
1604 close_connection(sock);
1607 else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
1609 RRDD_LOG (LOG_WARNING, "connection_thread_main: "
1610 "poll(2) returned something unexpected: %#04hx",
1612 close_connection(sock);
1616 rbytes = read(fd, sock->rbuf + sock->next_read,
1617 RBUF_SIZE - sock->next_read);
1620 RRDD_LOG(LOG_ERR, "connection_thread_main: read() failed.");
1623 else if (rbytes == 0)
1626 sock->next_read += rbytes;
1628 while ((cmd = next_cmd(sock, &cmd_len)) != NULL)
1630 status = handle_request (sock, cmd, cmd_len+1);
1637 close_connection(sock);
1639 self = pthread_self ();
1640 /* Remove this thread from the connection threads list */
1641 pthread_mutex_lock (&connection_threads_lock);
1642 /* Find out own index in the array */
1643 for (i = 0; i < connection_threads_num; i++)
1644 if (pthread_equal (connection_threads[i], self) != 0)
1646 assert (i < connection_threads_num);
1648 /* Move the trailing threads forward. */
1649 if (i < (connection_threads_num - 1))
1651 memmove (connection_threads + i,
1652 connection_threads + i + 1,
1653 sizeof (pthread_t) * (connection_threads_num - i - 1));
1656 connection_threads_num--;
1657 pthread_mutex_unlock (&connection_threads_lock);
1660 } /* }}} void *connection_thread_main */
1662 static int open_listen_socket_unix (const listen_socket_t *sock) /* {{{ */
1665 struct sockaddr_un sa;
1666 listen_socket_t *temp;
1671 if (strncmp(path, "unix:", strlen("unix:")) == 0)
1672 path += strlen("unix:");
1674 temp = (listen_socket_t *) realloc (listen_fds,
1675 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1678 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: realloc failed.");
1682 memcpy (listen_fds + listen_fds_num, sock, sizeof (listen_fds[0]));
1684 fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
1687 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: socket(2) failed.");
1691 memset (&sa, 0, sizeof (sa));
1692 sa.sun_family = AF_UNIX;
1693 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
1695 status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
1698 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: bind(2) failed.");
1704 status = listen (fd, /* backlog = */ 10);
1707 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: listen(2) failed.");
1713 listen_fds[listen_fds_num].fd = fd;
1714 listen_fds[listen_fds_num].family = PF_UNIX;
1715 strncpy(listen_fds[listen_fds_num].addr, path,
1716 sizeof (listen_fds[listen_fds_num].addr) - 1);
1720 } /* }}} int open_listen_socket_unix */
1722 static int open_listen_socket_network(const listen_socket_t *sock) /* {{{ */
1724 struct addrinfo ai_hints;
1725 struct addrinfo *ai_res;
1726 struct addrinfo *ai_ptr;
1727 char addr_copy[NI_MAXHOST];
1732 strncpy (addr_copy, sock->addr, sizeof (addr_copy));
1733 addr_copy[sizeof (addr_copy) - 1] = 0;
1736 memset (&ai_hints, 0, sizeof (ai_hints));
1737 ai_hints.ai_flags = 0;
1738 #ifdef AI_ADDRCONFIG
1739 ai_hints.ai_flags |= AI_ADDRCONFIG;
1741 ai_hints.ai_family = AF_UNSPEC;
1742 ai_hints.ai_socktype = SOCK_STREAM;
1745 if (*addr == '[') /* IPv6+port format */
1747 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
1750 port = strchr (addr, ']');
1753 RRDD_LOG (LOG_ERR, "open_listen_socket_network: Malformed address: %s",
1762 else if (*port == 0)
1766 RRDD_LOG (LOG_ERR, "open_listen_socket_network: Garbage after address: %s",
1770 } /* if (*addr = ']') */
1771 else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
1773 port = rindex(addr, ':');
1781 status = getaddrinfo (addr,
1782 port == NULL ? RRDCACHED_DEFAULT_PORT : port,
1783 &ai_hints, &ai_res);
1786 RRDD_LOG (LOG_ERR, "open_listen_socket_network: getaddrinfo(%s) failed: "
1787 "%s", addr, gai_strerror (status));
1791 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1794 listen_socket_t *temp;
1797 temp = (listen_socket_t *) realloc (listen_fds,
1798 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1801 RRDD_LOG (LOG_ERR, "open_listen_socket_network: realloc failed.");
1805 memcpy (listen_fds + listen_fds_num, sock, sizeof (listen_fds[0]));
1807 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1810 RRDD_LOG (LOG_ERR, "open_listen_socket_network: socket(2) failed.");
1814 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1816 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1819 RRDD_LOG (LOG_ERR, "open_listen_socket_network: bind(2) failed.");
1824 status = listen (fd, /* backlog = */ 10);
1827 RRDD_LOG (LOG_ERR, "open_listen_socket_network: listen(2) failed.");
1832 listen_fds[listen_fds_num].fd = fd;
1833 listen_fds[listen_fds_num].family = ai_ptr->ai_family;
1835 } /* for (ai_ptr) */
1838 } /* }}} static int open_listen_socket_network */
1840 static int open_listen_socket (const listen_socket_t *sock) /* {{{ */
1842 assert(sock != NULL);
1843 assert(sock->addr != NULL);
1845 if (strncmp ("unix:", sock->addr, strlen ("unix:")) == 0
1846 || sock->addr[0] == '/')
1847 return (open_listen_socket_unix(sock));
1849 return (open_listen_socket_network(sock));
1850 } /* }}} int open_listen_socket */
1852 static int close_listen_sockets (void) /* {{{ */
1856 for (i = 0; i < listen_fds_num; i++)
1858 close (listen_fds[i].fd);
1860 if (listen_fds[i].family == PF_UNIX)
1861 unlink(listen_fds[i].addr);
1869 } /* }}} int close_listen_sockets */
1871 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
1873 struct pollfd *pollfds;
1878 for (i = 0; i < config_listen_address_list_len; i++)
1879 open_listen_socket (config_listen_address_list[i]);
1881 if (config_listen_address_list_len < 1)
1883 listen_socket_t sock;
1884 memset(&sock, 0, sizeof(sock));
1885 strncpy(sock.addr, RRDCACHED_DEFAULT_ADDRESS, sizeof(sock.addr));
1886 open_listen_socket (&sock);
1889 if (listen_fds_num < 1)
1891 RRDD_LOG (LOG_ERR, "listen_thread_main: No listen sockets "
1892 "could be opened. Sorry.");
1896 pollfds_num = listen_fds_num;
1897 pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
1898 if (pollfds == NULL)
1900 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1903 memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
1905 RRDD_LOG(LOG_INFO, "listening for connections");
1907 while (do_shutdown == 0)
1909 assert (pollfds_num == ((int) listen_fds_num));
1910 for (i = 0; i < pollfds_num; i++)
1912 pollfds[i].fd = listen_fds[i].fd;
1913 pollfds[i].events = POLLIN | POLLPRI;
1914 pollfds[i].revents = 0;
1917 status = poll (pollfds, pollfds_num, /* timeout = */ 1000);
1920 else if (status == 0) /* timeout */
1922 else if (status < 0) /* error */
1925 if (status != EINTR)
1927 RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
1932 for (i = 0; i < pollfds_num; i++)
1934 listen_socket_t *client_sock;
1935 struct sockaddr_storage client_sa;
1936 socklen_t client_sa_size;
1938 pthread_attr_t attr;
1940 if (pollfds[i].revents == 0)
1943 if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
1945 RRDD_LOG (LOG_ERR, "listen_thread_main: "
1946 "poll(2) returned something unexpected for listen FD #%i.",
1951 client_sock = (listen_socket_t *) malloc (sizeof (listen_socket_t));
1952 if (client_sock == NULL)
1954 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1957 memcpy(client_sock, &listen_fds[i], sizeof(listen_fds[0]));
1959 client_sa_size = sizeof (client_sa);
1960 client_sock->fd = accept (pollfds[i].fd,
1961 (struct sockaddr *) &client_sa, &client_sa_size);
1962 if (client_sock->fd < 0)
1964 RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
1969 pthread_attr_init (&attr);
1970 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
1972 status = pthread_create (&tid, &attr, connection_thread_main,
1976 RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
1977 close_connection(client_sock);
1980 } /* for (pollfds_num) */
1981 } /* while (do_shutdown == 0) */
1983 RRDD_LOG(LOG_INFO, "starting shutdown");
1985 close_listen_sockets ();
1987 pthread_mutex_lock (&connection_threads_lock);
1988 while (connection_threads_num > 0)
1992 wait_for = connection_threads[0];
1994 pthread_mutex_unlock (&connection_threads_lock);
1995 pthread_join (wait_for, /* retval = */ NULL);
1996 pthread_mutex_lock (&connection_threads_lock);
1998 pthread_mutex_unlock (&connection_threads_lock);
2001 } /* }}} void *listen_thread_main */
2003 static int daemonize (void) /* {{{ */
2009 fd = open_pidfile();
2010 if (fd < 0) return fd;
2012 if (!stay_foreground)
2019 fprintf (stderr, "daemonize: fork(2) failed.\n");
2027 /* Become session leader */
2030 /* Open the first three file descriptors to /dev/null */
2035 open ("/dev/null", O_RDWR);
2038 } /* if (!stay_foreground) */
2040 /* Change into the /tmp directory. */
2041 base_dir = (config_base_dir != NULL)
2044 status = chdir (base_dir);
2047 fprintf (stderr, "daemonize: chdir (%s) failed.\n", base_dir);
2051 install_signal_handlers();
2053 openlog ("rrdcached", LOG_PID, LOG_DAEMON);
2054 RRDD_LOG(LOG_INFO, "starting up");
2056 cache_tree = g_tree_new ((GCompareFunc) strcmp);
2057 if (cache_tree == NULL)
2059 RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
2063 status = write_pidfile (fd);
2065 } /* }}} int daemonize */
2067 static int cleanup (void) /* {{{ */
2071 pthread_cond_signal (&cache_cond);
2072 pthread_join (queue_thread, /* return = */ NULL);
2076 RRDD_LOG(LOG_INFO, "goodbye");
2080 } /* }}} int cleanup */
2082 static int read_options (int argc, char **argv) /* {{{ */
2087 while ((option = getopt(argc, argv, "gl:L:f:w:b:Bz:p:j:h?F")) != -1)
2098 listen_socket_t **temp;
2099 listen_socket_t *new;
2101 new = malloc(sizeof(listen_socket_t));
2104 fprintf(stderr, "read_options: malloc failed.\n");
2107 memset(new, 0, sizeof(listen_socket_t));
2109 temp = (listen_socket_t **) realloc (config_listen_address_list,
2110 sizeof (listen_socket_t *) * (config_listen_address_list_len + 1));
2113 fprintf (stderr, "read_options: realloc failed.\n");
2116 config_listen_address_list = temp;
2118 strncpy(new->addr, optarg, sizeof(new->addr)-1);
2119 new->privilege = (option == 'l') ? PRIV_HIGH : PRIV_LOW;
2121 temp[config_listen_address_list_len] = new;
2122 config_listen_address_list_len++;
2130 temp = atoi (optarg);
2132 config_flush_interval = temp;
2135 fprintf (stderr, "Invalid flush interval: %s\n", optarg);
2145 temp = atoi (optarg);
2147 config_write_interval = temp;
2150 fprintf (stderr, "Invalid write interval: %s\n", optarg);
2160 temp = atoi(optarg);
2162 config_write_jitter = temp;
2165 fprintf (stderr, "Invalid write jitter: -z %s\n", optarg);
2173 config_write_base_only = 1;
2180 if (config_base_dir != NULL)
2181 free (config_base_dir);
2182 config_base_dir = strdup (optarg);
2183 if (config_base_dir == NULL)
2185 fprintf (stderr, "read_options: strdup failed.\n");
2189 len = strlen (config_base_dir);
2190 while ((len > 0) && (config_base_dir[len - 1] == '/'))
2192 config_base_dir[len - 1] = 0;
2198 fprintf (stderr, "Invalid base directory: %s\n", optarg);
2202 _config_base_dir_len = len;
2208 if (config_pid_file != NULL)
2209 free (config_pid_file);
2210 config_pid_file = strdup (optarg);
2211 if (config_pid_file == NULL)
2213 fprintf (stderr, "read_options: strdup failed.\n");
2220 config_flush_at_shutdown = 1;
2225 struct stat statbuf;
2226 const char *dir = optarg;
2228 status = stat(dir, &statbuf);
2231 fprintf(stderr, "Cannot stat '%s' : %s\n", dir, rrd_strerror(errno));
2235 if (!S_ISDIR(statbuf.st_mode)
2236 || access(dir, R_OK|W_OK|X_OK) != 0)
2238 fprintf(stderr, "Must specify a writable directory with -j! (%s)\n",
2239 errno ? rrd_strerror(errno) : "");
2243 journal_cur = malloc(PATH_MAX + 1);
2244 journal_old = malloc(PATH_MAX + 1);
2245 if (journal_cur == NULL || journal_old == NULL)
2247 fprintf(stderr, "malloc failure for journal files\n");
2252 snprintf(journal_cur, PATH_MAX, "%s/rrd.journal", dir);
2253 snprintf(journal_old, PATH_MAX, "%s/rrd.journal.old", dir);
2260 printf ("RRDCacheD %s Copyright (C) 2008 Florian octo Forster\n"
2262 "Usage: rrdcached [options]\n"
2264 "Valid options are:\n"
2265 " -l <address> Socket address to listen to.\n"
2266 " -L <address> Socket address to listen to ('FLUSH' only).\n"
2267 " -w <seconds> Interval in which to write data.\n"
2268 " -z <delay> Delay writes up to <delay> seconds to spread load\n"
2269 " -f <seconds> Interval in which to flush dead data.\n"
2270 " -p <file> Location of the PID-file.\n"
2271 " -b <dir> Base directory to change to.\n"
2272 " -B Restrict file access to paths within -b <dir>\n"
2273 " -g Do not fork and run in the foreground.\n"
2274 " -j <dir> Directory in which to create the journal files.\n"
2275 " -F Always flush all updates at shutdown\n"
2277 "For more information and a detailed description of all options "
2279 "to the rrdcached(1) manual page.\n",
2283 } /* switch (option) */
2284 } /* while (getopt) */
2286 /* advise the user when values are not sane */
2287 if (config_flush_interval < 2 * config_write_interval)
2288 fprintf(stderr, "WARNING: flush interval (-f) should be at least"
2289 " 2x write interval (-w) !\n");
2290 if (config_write_jitter > config_write_interval)
2291 fprintf(stderr, "WARNING: write delay (-z) should NOT be larger than"
2292 " write interval (-w) !\n");
2294 if (config_write_base_only && config_base_dir == NULL)
2295 fprintf(stderr, "WARNING: -B does not make sense without -b!\n"
2296 " Consult the rrdcached documentation\n");
2298 if (journal_cur == NULL)
2299 config_flush_at_shutdown = 1;
2302 } /* }}} int read_options */
2304 int main (int argc, char **argv)
2308 status = read_options (argc, argv);
2316 status = daemonize ();
2319 struct sigaction sigchld;
2321 memset (&sigchld, 0, sizeof (sigchld));
2322 sigchld.sa_handler = SIG_IGN;
2323 sigaction (SIGCHLD, &sigchld, NULL);
2327 else if (status != 0)
2329 fprintf (stderr, "daemonize failed, exiting.\n");
2333 if (journal_cur != NULL)
2335 int had_journal = 0;
2337 pthread_mutex_lock(&journal_lock);
2339 RRDD_LOG(LOG_INFO, "checking for journal files");
2341 had_journal += journal_replay(journal_old);
2342 had_journal += journal_replay(journal_cur);
2345 flush_old_values(-1);
2347 pthread_mutex_unlock(&journal_lock);
2350 RRDD_LOG(LOG_INFO, "journal processing complete");
2353 /* start the queue thread */
2354 memset (&queue_thread, 0, sizeof (queue_thread));
2355 status = pthread_create (&queue_thread,
2361 RRDD_LOG (LOG_ERR, "FATAL: cannot create queue thread");
2366 listen_thread_main (NULL);
2373 * vim: set sw=2 sts=2 ts=8 et fdm=marker :