2 * RRDTool - src/rrd_daemon.c
3 * Copyright (C) 2008,2009 Florian octo Forster
4 * Copyright (C) 2008,2009 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..
66 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__) && !defined(HAVE_CONFIG_H)
67 #include "../win32/config.h"
70 #include "../rrd_config.h"
75 #include "rrd_client.h"
86 #include <sys/socket.h>
94 #include <sys/types.h>
106 #include <sys/time.h>
111 #include <glib-2.0/glib.h>
114 #define RRDD_LOG(severity, ...) syslog ((severity), __VA_ARGS__)
117 # define __attribute__(x) /**/
123 typedef enum { RESP_ERR = -1, RESP_OK = 0 } response_code;
125 struct listen_socket_s
128 char addr[PATH_MAX + 1];
131 /* state for BATCH processing */
143 uint32_t permissions;
146 mode_t socket_permissions;
148 typedef struct listen_socket_s listen_socket_t;
151 typedef struct command_s command_t;
152 /* note: guard against "unused" warnings in the handlers */
153 #define DISPATCH_PROTO listen_socket_t *sock __attribute__((unused)),\
154 time_t now __attribute__((unused)),\
155 char *buffer __attribute__((unused)),\
156 size_t buffer_size __attribute__((unused))
158 #define HANDLER_PROTO command_t *cmd __attribute__((unused)),\
163 int (*handler)(HANDLER_PROTO);
165 char context; /* where we expect to see it */
166 #define CMD_CONTEXT_CLIENT (1<<0)
167 #define CMD_CONTEXT_BATCH (1<<1)
168 #define CMD_CONTEXT_JOURNAL (1<<2)
169 #define CMD_CONTEXT_ANY (0x7f)
176 typedef struct cache_item_s cache_item_t;
182 time_t last_flush_time;
183 time_t last_update_stamp;
184 #define CI_FLAGS_IN_TREE (1<<0)
185 #define CI_FLAGS_IN_QUEUE (1<<1)
187 pthread_cond_t flushed;
192 struct callback_flush_data_s
199 typedef struct callback_flush_data_s callback_flush_data_t;
206 typedef enum queue_side_e queue_side_t;
208 /* describe a set of journal files */
214 /* max length of socket command or response */
216 #define RBUF_SIZE (CMD_MAX*2)
221 static int stay_foreground = 0;
222 static uid_t daemon_uid;
224 static listen_socket_t *listen_fds = NULL;
225 static size_t listen_fds_num = 0;
228 RUNNING, /* normal operation */
229 FLUSHING, /* flushing remaining values */
230 SHUTDOWN /* shutting down */
233 static pthread_t *queue_threads;
234 static pthread_cond_t queue_cond = PTHREAD_COND_INITIALIZER;
235 static int config_queue_threads = 4;
237 static pthread_t flush_thread;
238 static pthread_cond_t flush_cond = PTHREAD_COND_INITIALIZER;
240 static pthread_mutex_t connection_threads_lock = PTHREAD_MUTEX_INITIALIZER;
241 static pthread_cond_t connection_threads_done = PTHREAD_COND_INITIALIZER;
242 static int connection_threads_num = 0;
245 static GTree *cache_tree = NULL;
246 static cache_item_t *cache_queue_head = NULL;
247 static cache_item_t *cache_queue_tail = NULL;
248 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
250 static int config_write_interval = 300;
251 static int config_write_jitter = 0;
252 static int config_flush_interval = 3600;
253 static int config_flush_at_shutdown = 0;
254 static char *config_pid_file = NULL;
255 static char *config_base_dir = NULL;
256 static size_t _config_base_dir_len = 0;
257 static int config_write_base_only = 0;
259 static listen_socket_t **config_listen_address_list = NULL;
260 static size_t config_listen_address_list_len = 0;
262 static uint64_t stats_queue_length = 0;
263 static uint64_t stats_updates_received = 0;
264 static uint64_t stats_flush_received = 0;
265 static uint64_t stats_updates_written = 0;
266 static uint64_t stats_data_sets_written = 0;
267 static uint64_t stats_journal_bytes = 0;
268 static uint64_t stats_journal_rotate = 0;
269 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
271 /* Journaled updates */
272 #define JOURNAL_REPLAY(s) ((s) == NULL)
273 #define JOURNAL_BASE "rrd.journal"
274 static journal_set *journal_cur = NULL;
275 static journal_set *journal_old = NULL;
276 static char *journal_dir = NULL;
277 static FILE *journal_fh = NULL; /* current journal file handle */
278 static long journal_size = 0; /* current journal size */
279 #define JOURNAL_MAX (1 * 1024 * 1024 * 1024)
280 static pthread_mutex_t journal_lock = PTHREAD_MUTEX_INITIALIZER;
281 static int journal_write(char *cmd, char *args);
282 static void journal_done(void);
283 static void journal_rotate(void);
285 /* prototypes for forward refernces */
286 static int handle_request_help (HANDLER_PROTO);
291 static void sig_common (const char *sig) /* {{{ */
293 RRDD_LOG(LOG_NOTICE, "caught SIG%s", sig);
295 pthread_cond_broadcast(&flush_cond);
296 pthread_cond_broadcast(&queue_cond);
297 } /* }}} void sig_common */
299 static void sig_int_handler (int s __attribute__((unused))) /* {{{ */
302 } /* }}} void sig_int_handler */
304 static void sig_term_handler (int s __attribute__((unused))) /* {{{ */
307 } /* }}} void sig_term_handler */
309 static void sig_usr1_handler (int s __attribute__((unused))) /* {{{ */
311 config_flush_at_shutdown = 1;
313 } /* }}} void sig_usr1_handler */
315 static void sig_usr2_handler (int s __attribute__((unused))) /* {{{ */
317 config_flush_at_shutdown = 0;
319 } /* }}} void sig_usr2_handler */
321 static void install_signal_handlers(void) /* {{{ */
323 /* These structures are static, because `sigaction' behaves weird if the are
325 static struct sigaction sa_int;
326 static struct sigaction sa_term;
327 static struct sigaction sa_pipe;
328 static struct sigaction sa_usr1;
329 static struct sigaction sa_usr2;
331 /* Install signal handlers */
332 memset (&sa_int, 0, sizeof (sa_int));
333 sa_int.sa_handler = sig_int_handler;
334 sigaction (SIGINT, &sa_int, NULL);
336 memset (&sa_term, 0, sizeof (sa_term));
337 sa_term.sa_handler = sig_term_handler;
338 sigaction (SIGTERM, &sa_term, NULL);
340 memset (&sa_pipe, 0, sizeof (sa_pipe));
341 sa_pipe.sa_handler = SIG_IGN;
342 sigaction (SIGPIPE, &sa_pipe, NULL);
344 memset (&sa_pipe, 0, sizeof (sa_usr1));
345 sa_usr1.sa_handler = sig_usr1_handler;
346 sigaction (SIGUSR1, &sa_usr1, NULL);
348 memset (&sa_usr2, 0, sizeof (sa_usr2));
349 sa_usr2.sa_handler = sig_usr2_handler;
350 sigaction (SIGUSR2, &sa_usr2, NULL);
352 } /* }}} void install_signal_handlers */
354 static int open_pidfile(char *action, int oflag) /* {{{ */
358 char *file_copy, *dir;
360 file = (config_pid_file != NULL)
362 : LOCALSTATEDIR "/run/rrdcached.pid";
364 /* dirname may modify its argument */
365 file_copy = strdup(file);
366 if (file_copy == NULL)
368 fprintf(stderr, "rrdcached: strdup(): %s\n",
369 rrd_strerror(errno));
373 dir = dirname(file_copy);
374 if (rrd_mkdir_p(dir, 0777) != 0)
376 fprintf(stderr, "Failed to create pidfile directory '%s': %s\n",
377 dir, rrd_strerror(errno));
383 fd = open(file, oflag, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH);
385 fprintf(stderr, "rrdcached: can't %s pid file '%s' (%s)\n",
386 action, file, rrd_strerror(errno));
389 } /* }}} static int open_pidfile */
391 /* check existing pid file to see whether a daemon is running */
392 static int check_pidfile(void)
398 pid_fd = open_pidfile("open", O_RDWR);
402 if (read(pid_fd, pid_str, sizeof(pid_str)) <= 0)
409 /* another running process that we can signal COULD be
410 * a competing rrdcached */
411 if (pid != getpid() && kill(pid, 0) == 0)
414 "FATAL: Another rrdcached daemon is running?? (pid %d)\n", pid);
419 lseek(pid_fd, 0, SEEK_SET);
420 if (ftruncate(pid_fd, 0) == -1)
423 "FATAL: Faild to truncate stale PID file. (pid %d)\n", pid);
429 "rrdcached: removed stale PID file (no rrdcached on pid %d)\n"
430 "rrdcached: starting normally.\n", pid);
433 } /* }}} static int check_pidfile */
435 static int write_pidfile (int fd) /* {{{ */
442 fh = fdopen (fd, "w");
445 RRDD_LOG (LOG_ERR, "write_pidfile: fdopen() failed.");
450 fprintf (fh, "%i\n", (int) pid);
454 } /* }}} int write_pidfile */
456 static int remove_pidfile (void) /* {{{ */
461 file = (config_pid_file != NULL)
463 : LOCALSTATEDIR "/run/rrdcached.pid";
465 status = unlink (file);
469 } /* }}} int remove_pidfile */
471 static char *next_cmd (listen_socket_t *sock, ssize_t *len) /* {{{ */
475 eol = memchr(sock->rbuf + sock->next_cmd, '\n',
476 sock->next_read - sock->next_cmd);
480 /* no commands left, move remainder back to front of rbuf */
481 memmove(sock->rbuf, sock->rbuf + sock->next_cmd,
482 sock->next_read - sock->next_cmd);
483 sock->next_read -= sock->next_cmd;
490 char *cmd = sock->rbuf + sock->next_cmd;
493 sock->next_cmd = eol - sock->rbuf + 1;
495 if (eol > sock->rbuf && *(eol-1) == '\r')
496 *(--eol) = '\0'; /* handle "\r\n" EOL */
505 } /* }}} char *next_cmd */
507 /* add the characters directly to the write buffer */
508 static int add_to_wbuf(listen_socket_t *sock, char *str, size_t len) /* {{{ */
512 assert(sock != NULL);
514 new_buf = rrd_realloc(sock->wbuf, sock->wbuf_len + len + 1);
517 RRDD_LOG(LOG_ERR, "add_to_wbuf: realloc failed");
521 strncpy(new_buf + sock->wbuf_len, str, len + 1);
523 sock->wbuf = new_buf;
524 sock->wbuf_len += len;
527 } /* }}} static int add_to_wbuf */
529 /* add the text to the "extra" info that's sent after the status line */
530 static int add_response_info(listen_socket_t *sock, char *fmt, ...) /* {{{ */
533 char buffer[CMD_MAX];
536 if (JOURNAL_REPLAY(sock)) return 0;
537 if (sock->batch_start) return 0; /* no extra info returned when in BATCH */
540 #ifdef HAVE_VSNPRINTF
541 len = vsnprintf(buffer, sizeof(buffer), fmt, argp);
543 len = vsprintf(buffer, fmt, argp);
548 RRDD_LOG(LOG_ERR, "add_response_info: vnsprintf failed");
552 return add_to_wbuf(sock, buffer, len);
553 } /* }}} static int add_response_info */
555 static int count_lines(char *str) /* {{{ */
561 while ((str = strchr(str, '\n')) != NULL)
569 } /* }}} static int count_lines */
571 /* send the response back to the user.
572 * returns 0 on success, -1 on error
573 * write buffer is always zeroed after this call */
574 static int send_response (listen_socket_t *sock, response_code rc,
575 char *fmt, ...) /* {{{ */
578 char buffer[CMD_MAX];
583 if (JOURNAL_REPLAY(sock)) return rc;
585 if (sock->batch_start)
588 return rc; /* no response on success during BATCH */
589 lines = sock->batch_cmd;
591 else if (rc == RESP_OK)
592 lines = count_lines(sock->wbuf);
596 rclen = sprintf(buffer, "%d ", lines);
598 #ifdef HAVE_VSNPRINTF
599 len = vsnprintf(buffer+rclen, sizeof(buffer)-rclen, fmt, argp);
601 len = vsprintf(buffer+rclen, fmt, argp);
609 /* append the result to the wbuf, don't write to the user */
610 if (sock->batch_start)
611 return add_to_wbuf(sock, buffer, len);
613 /* first write must be complete */
614 if (len != write(sock->fd, buffer, len))
616 RRDD_LOG(LOG_INFO, "send_response: could not write status message");
620 if (sock->wbuf != NULL && rc == RESP_OK)
623 while (wrote < sock->wbuf_len)
625 ssize_t wb = write(sock->fd, sock->wbuf + wrote, sock->wbuf_len - wrote);
628 RRDD_LOG(LOG_INFO, "send_response: could not write results");
635 free(sock->wbuf); sock->wbuf = NULL;
641 static void wipe_ci_values(cache_item_t *ci, time_t when)
646 ci->last_flush_time = when;
647 if (config_write_jitter > 0)
648 ci->last_flush_time += (rrd_random() % config_write_jitter);
652 * remove a "cache_item_t" item from the queue.
653 * must hold 'cache_lock' when calling this
655 static void remove_from_queue(cache_item_t *ci) /* {{{ */
657 if (ci == NULL) return;
658 if ((ci->flags & CI_FLAGS_IN_QUEUE) == 0) return; /* not queued */
660 if (ci->prev == NULL)
661 cache_queue_head = ci->next; /* reset head */
663 ci->prev->next = ci->next;
665 if (ci->next == NULL)
666 cache_queue_tail = ci->prev; /* reset the tail */
668 ci->next->prev = ci->prev;
670 ci->next = ci->prev = NULL;
671 ci->flags &= ~CI_FLAGS_IN_QUEUE;
673 pthread_mutex_lock (&stats_lock);
674 assert (stats_queue_length > 0);
675 stats_queue_length--;
676 pthread_mutex_unlock (&stats_lock);
678 } /* }}} static void remove_from_queue */
680 /* free the resources associated with the cache_item_t
681 * must hold cache_lock when calling this function
683 static void *free_cache_item(cache_item_t *ci) /* {{{ */
685 if (ci == NULL) return NULL;
687 remove_from_queue(ci);
689 for (size_t i=0; i < ci->values_num; i++)
695 /* in case anyone is waiting */
696 pthread_cond_broadcast(&ci->flushed);
697 pthread_cond_destroy(&ci->flushed);
702 } /* }}} static void *free_cache_item */
705 * enqueue_cache_item:
706 * `cache_lock' must be acquired before calling this function!
708 static int enqueue_cache_item (cache_item_t *ci, /* {{{ */
714 if (ci->values_num == 0)
719 if (cache_queue_head == ci)
722 /* remove if further down in queue */
723 remove_from_queue(ci);
726 ci->next = cache_queue_head;
727 if (ci->next != NULL)
729 cache_queue_head = ci;
731 if (cache_queue_tail == NULL)
732 cache_queue_tail = cache_queue_head;
734 else /* (side == TAIL) */
736 /* We don't move values back in the list.. */
737 if (ci->flags & CI_FLAGS_IN_QUEUE)
740 assert (ci->next == NULL);
741 assert (ci->prev == NULL);
743 ci->prev = cache_queue_tail;
745 if (cache_queue_tail == NULL)
746 cache_queue_head = ci;
748 cache_queue_tail->next = ci;
750 cache_queue_tail = ci;
753 ci->flags |= CI_FLAGS_IN_QUEUE;
755 pthread_cond_signal(&queue_cond);
756 pthread_mutex_lock (&stats_lock);
757 stats_queue_length++;
758 pthread_mutex_unlock (&stats_lock);
761 } /* }}} int enqueue_cache_item */
764 * tree_callback_flush:
765 * Called via `g_tree_foreach' in `flush_thread_main'. `cache_lock' is held
766 * while this is in progress.
768 static gboolean tree_callback_flush (gpointer key, gpointer value, /* {{{ */
772 callback_flush_data_t *cfd;
774 ci = (cache_item_t *) value;
775 cfd = (callback_flush_data_t *) data;
777 if (ci->flags & CI_FLAGS_IN_QUEUE)
780 if (ci->values_num > 0
781 && (ci->last_flush_time <= cfd->abs_timeout || state != RUNNING))
783 enqueue_cache_item (ci, TAIL);
785 else if (((cfd->now - ci->last_flush_time) >= config_flush_interval)
786 && (ci->values_num <= 0))
788 assert ((char *) key == ci->file);
789 if (!rrd_add_ptr((void ***)&cfd->keys, &cfd->keys_num, (void *)key))
791 RRDD_LOG (LOG_ERR, "tree_callback_flush: rrd_add_ptrs failed.");
797 } /* }}} gboolean tree_callback_flush */
799 static int flush_old_values (int max_age)
801 callback_flush_data_t cfd;
804 memset (&cfd, 0, sizeof (cfd));
805 /* Pass the current time as user data so that we don't need to call
806 * `time' for each node. */
807 cfd.now = time (NULL);
812 cfd.abs_timeout = cfd.now - max_age;
814 cfd.abs_timeout = cfd.now + 2*config_write_jitter + 1;
816 /* `tree_callback_flush' will return the keys of all values that haven't
817 * been touched in the last `config_flush_interval' seconds in `cfd'.
818 * The char*'s in this array point to the same memory as ci->file, so we
819 * don't need to free them separately. */
820 g_tree_foreach (cache_tree, tree_callback_flush, (gpointer) &cfd);
822 for (k = 0; k < cfd.keys_num; k++)
824 gboolean status = g_tree_remove(cache_tree, cfd.keys[k]);
825 /* should never fail, since we have held the cache_lock
827 assert(status == TRUE);
830 if (cfd.keys != NULL)
837 } /* int flush_old_values */
839 static void *flush_thread_main (void *args __attribute__((unused))) /* {{{ */
842 struct timespec next_flush;
845 gettimeofday (&now, NULL);
846 next_flush.tv_sec = now.tv_sec + config_flush_interval;
847 next_flush.tv_nsec = 1000 * now.tv_usec;
849 pthread_mutex_lock(&cache_lock);
851 while (state == RUNNING)
853 gettimeofday (&now, NULL);
854 if ((now.tv_sec > next_flush.tv_sec)
855 || ((now.tv_sec == next_flush.tv_sec)
856 && ((1000 * now.tv_usec) > next_flush.tv_nsec)))
858 RRDD_LOG(LOG_DEBUG, "flushing old values");
860 /* Determine the time of the next cache flush. */
861 next_flush.tv_sec = now.tv_sec + config_flush_interval;
863 /* Flush all values that haven't been written in the last
864 * `config_write_interval' seconds. */
865 flush_old_values (config_write_interval);
867 /* unlock the cache while we rotate so we don't block incoming
868 * updates if the fsync() blocks on disk I/O */
869 pthread_mutex_unlock(&cache_lock);
871 pthread_mutex_lock(&cache_lock);
874 status = pthread_cond_timedwait(&flush_cond, &cache_lock, &next_flush);
875 if (status != 0 && status != ETIMEDOUT)
877 RRDD_LOG (LOG_ERR, "flush_thread_main: "
878 "pthread_cond_timedwait returned %i.", status);
882 if (config_flush_at_shutdown)
883 flush_old_values (-1); /* flush everything */
887 pthread_mutex_unlock(&cache_lock);
890 } /* void *flush_thread_main */
892 static void *queue_thread_main (void *args __attribute__((unused))) /* {{{ */
894 pthread_mutex_lock (&cache_lock);
896 while (state != SHUTDOWN
897 || (cache_queue_head != NULL && config_flush_at_shutdown))
905 /* Now, check if there's something to store away. If not, wait until
906 * something comes in. */
907 if (cache_queue_head == NULL)
909 status = pthread_cond_wait (&queue_cond, &cache_lock);
910 if ((status != 0) && (status != ETIMEDOUT))
912 RRDD_LOG (LOG_ERR, "queue_thread_main: "
913 "pthread_cond_wait returned %i.", status);
917 /* Check if a value has arrived. This may be NULL if we timed out or there
918 * was an interrupt such as a signal. */
919 if (cache_queue_head == NULL)
922 ci = cache_queue_head;
924 /* copy the relevant parts */
925 file = strdup (ci->file);
928 RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
932 assert(ci->values != NULL);
933 assert(ci->values_num > 0);
936 values_num = ci->values_num;
938 wipe_ci_values(ci, time(NULL));
939 remove_from_queue(ci);
941 pthread_mutex_unlock (&cache_lock);
944 status = rrd_update_r (file, NULL, (int) values_num, (void *) values);
947 RRDD_LOG (LOG_NOTICE, "queue_thread_main: "
948 "rrd_update_r (%s) failed with status %i. (%s)",
949 file, status, rrd_get_error());
952 journal_write("wrote", file);
954 /* Search again in the tree. It's possible someone issued a "FORGET"
955 * while we were writing the update values. */
956 pthread_mutex_lock(&cache_lock);
957 ci = (cache_item_t *) g_tree_lookup(cache_tree, file);
959 pthread_cond_broadcast(&ci->flushed);
960 pthread_mutex_unlock(&cache_lock);
964 pthread_mutex_lock (&stats_lock);
965 stats_updates_written++;
966 stats_data_sets_written += values_num;
967 pthread_mutex_unlock (&stats_lock);
970 rrd_free_ptrs((void ***) &values, &values_num);
973 pthread_mutex_lock (&cache_lock);
975 pthread_mutex_unlock (&cache_lock);
978 } /* }}} void *queue_thread_main */
980 static int buffer_get_field (char **buffer_ret, /* {{{ */
981 size_t *buffer_size_ret, char **field_ret)
990 buffer = *buffer_ret;
992 buffer_size = *buffer_size_ret;
996 if (buffer_size <= 0)
999 /* This is ensured by `handle_request'. */
1000 assert (buffer[buffer_size - 1] == '\0');
1003 while (buffer_pos < buffer_size)
1005 /* Check for end-of-field or end-of-buffer */
1006 if (buffer[buffer_pos] == ' ' || buffer[buffer_pos] == '\0')
1008 field[field_size] = 0;
1014 /* Handle escaped characters. */
1015 else if (buffer[buffer_pos] == '\\')
1017 if (buffer_pos >= (buffer_size - 1))
1020 field[field_size] = buffer[buffer_pos];
1024 /* Normal operation */
1027 field[field_size] = buffer[buffer_pos];
1031 } /* while (buffer_pos < buffer_size) */
1036 *buffer_ret = buffer + buffer_pos;
1037 *buffer_size_ret = buffer_size - buffer_pos;
1041 } /* }}} int buffer_get_field */
1043 /* if we're restricting writes to the base directory,
1044 * check whether the file falls within the dir
1045 * returns 1 if OK, otherwise 0
1047 static int check_file_access (const char *file, listen_socket_t *sock) /* {{{ */
1049 assert(file != NULL);
1051 if (!config_write_base_only
1052 || JOURNAL_REPLAY(sock)
1053 || config_base_dir == NULL)
1056 if (strstr(file, "../") != NULL) goto err;
1058 /* relative paths without "../" are ok */
1059 if (*file != '/') return 1;
1061 /* file must be of the format base + "/" + <1+ char filename> */
1062 if (strlen(file) < _config_base_dir_len + 2) goto err;
1063 if (strncmp(file, config_base_dir, _config_base_dir_len) != 0) goto err;
1064 if (*(file + _config_base_dir_len) != '/') goto err;
1069 if (sock != NULL && sock->fd >= 0)
1070 send_response(sock, RESP_ERR, "%s\n", rrd_strerror(EACCES));
1073 } /* }}} static int check_file_access */
1075 /* when using a base dir, convert relative paths to absolute paths.
1076 * if necessary, modifies the "filename" pointer to point
1077 * to the new path created in "tmp". "tmp" is provided
1078 * by the caller and sizeof(tmp) must be >= PATH_MAX.
1080 * this allows us to optimize for the expected case (absolute path)
1083 static void get_abs_path(char **filename, char *tmp)
1085 assert(tmp != NULL);
1086 assert(filename != NULL && *filename != NULL);
1088 if (config_base_dir == NULL || **filename == '/')
1091 snprintf(tmp, PATH_MAX, "%s/%s", config_base_dir, *filename);
1093 } /* }}} static int get_abs_path */
1095 static int flush_file (const char *filename) /* {{{ */
1099 pthread_mutex_lock (&cache_lock);
1101 ci = (cache_item_t *) g_tree_lookup (cache_tree, filename);
1104 pthread_mutex_unlock (&cache_lock);
1108 if (ci->values_num > 0)
1110 /* Enqueue at head */
1111 enqueue_cache_item (ci, HEAD);
1112 pthread_cond_wait(&ci->flushed, &cache_lock);
1115 /* DO NOT DO ANYTHING WITH ci HERE!! The entry
1116 * may have been purged during our cond_wait() */
1118 pthread_mutex_unlock(&cache_lock);
1121 } /* }}} int flush_file */
1123 static int syntax_error(listen_socket_t *sock, command_t *cmd) /* {{{ */
1125 char *err = "Syntax error.\n";
1127 if (cmd && cmd->syntax)
1130 return send_response(sock, RESP_ERR, "Usage: %s", err);
1131 } /* }}} static int syntax_error() */
1133 static int handle_request_stats (HANDLER_PROTO) /* {{{ */
1135 uint64_t copy_queue_length;
1136 uint64_t copy_updates_received;
1137 uint64_t copy_flush_received;
1138 uint64_t copy_updates_written;
1139 uint64_t copy_data_sets_written;
1140 uint64_t copy_journal_bytes;
1141 uint64_t copy_journal_rotate;
1143 uint64_t tree_nodes_number;
1144 uint64_t tree_depth;
1146 pthread_mutex_lock (&stats_lock);
1147 copy_queue_length = stats_queue_length;
1148 copy_updates_received = stats_updates_received;
1149 copy_flush_received = stats_flush_received;
1150 copy_updates_written = stats_updates_written;
1151 copy_data_sets_written = stats_data_sets_written;
1152 copy_journal_bytes = stats_journal_bytes;
1153 copy_journal_rotate = stats_journal_rotate;
1154 pthread_mutex_unlock (&stats_lock);
1156 pthread_mutex_lock (&cache_lock);
1157 tree_nodes_number = (uint64_t) g_tree_nnodes (cache_tree);
1158 tree_depth = (uint64_t) g_tree_height (cache_tree);
1159 pthread_mutex_unlock (&cache_lock);
1161 add_response_info(sock,
1162 "QueueLength: %"PRIu64"\n", copy_queue_length);
1163 add_response_info(sock,
1164 "UpdatesReceived: %"PRIu64"\n", copy_updates_received);
1165 add_response_info(sock,
1166 "FlushesReceived: %"PRIu64"\n", copy_flush_received);
1167 add_response_info(sock,
1168 "UpdatesWritten: %"PRIu64"\n", copy_updates_written);
1169 add_response_info(sock,
1170 "DataSetsWritten: %"PRIu64"\n", copy_data_sets_written);
1171 add_response_info(sock, "TreeNodesNumber: %"PRIu64"\n", tree_nodes_number);
1172 add_response_info(sock, "TreeDepth: %"PRIu64"\n", tree_depth);
1173 add_response_info(sock, "JournalBytes: %"PRIu64"\n", copy_journal_bytes);
1174 add_response_info(sock, "JournalRotate: %"PRIu64"\n", copy_journal_rotate);
1176 send_response(sock, RESP_OK, "Statistics follow\n");
1179 } /* }}} int handle_request_stats */
1181 static int handle_request_flush (HANDLER_PROTO) /* {{{ */
1183 char *file, file_tmp[PATH_MAX];
1186 status = buffer_get_field (&buffer, &buffer_size, &file);
1189 return syntax_error(sock,cmd);
1193 pthread_mutex_lock(&stats_lock);
1194 stats_flush_received++;
1195 pthread_mutex_unlock(&stats_lock);
1197 get_abs_path(&file, file_tmp);
1198 if (!check_file_access(file, sock)) return 0;
1200 status = flush_file (file);
1202 return send_response(sock, RESP_OK, "Successfully flushed %s.\n", file);
1203 else if (status == ENOENT)
1205 /* no file in our tree; see whether it exists at all */
1206 struct stat statbuf;
1208 memset(&statbuf, 0, sizeof(statbuf));
1209 if (stat(file, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
1210 return send_response(sock, RESP_OK, "Nothing to flush: %s.\n", file);
1212 return send_response(sock, RESP_ERR, "No such file: %s.\n", file);
1214 else if (status < 0)
1215 return send_response(sock, RESP_ERR, "Internal error.\n");
1217 return send_response(sock, RESP_ERR, "Failed with status %i.\n", status);
1222 } /* }}} int handle_request_flush */
1224 static int handle_request_flushall(HANDLER_PROTO) /* {{{ */
1226 RRDD_LOG(LOG_DEBUG, "Received FLUSHALL");
1228 pthread_mutex_lock(&cache_lock);
1229 flush_old_values(-1);
1230 pthread_mutex_unlock(&cache_lock);
1232 return send_response(sock, RESP_OK, "Started flush.\n");
1233 } /* }}} static int handle_request_flushall */
1235 static int handle_request_pending(HANDLER_PROTO) /* {{{ */
1238 char *file, file_tmp[PATH_MAX];
1241 status = buffer_get_field(&buffer, &buffer_size, &file);
1243 return syntax_error(sock,cmd);
1245 get_abs_path(&file, file_tmp);
1247 pthread_mutex_lock(&cache_lock);
1248 ci = g_tree_lookup(cache_tree, file);
1251 pthread_mutex_unlock(&cache_lock);
1252 return send_response(sock, RESP_ERR, "%s\n", rrd_strerror(ENOENT));
1255 for (size_t i=0; i < ci->values_num; i++)
1256 add_response_info(sock, "%s\n", ci->values[i]);
1258 pthread_mutex_unlock(&cache_lock);
1259 return send_response(sock, RESP_OK, "updates pending\n");
1260 } /* }}} static int handle_request_pending */
1262 static int handle_request_forget(HANDLER_PROTO) /* {{{ */
1266 char *file, file_tmp[PATH_MAX];
1268 status = buffer_get_field(&buffer, &buffer_size, &file);
1270 return syntax_error(sock,cmd);
1272 get_abs_path(&file, file_tmp);
1273 if (!check_file_access(file, sock)) return 0;
1275 pthread_mutex_lock(&cache_lock);
1276 found = g_tree_remove(cache_tree, file);
1277 pthread_mutex_unlock(&cache_lock);
1281 if (!JOURNAL_REPLAY(sock))
1282 journal_write("forget", file);
1284 return send_response(sock, RESP_OK, "Gone!\n");
1287 return send_response(sock, RESP_ERR, "%s\n", rrd_strerror(ENOENT));
1291 } /* }}} static int handle_request_forget */
1293 static int handle_request_queue (HANDLER_PROTO) /* {{{ */
1297 pthread_mutex_lock(&cache_lock);
1299 ci = cache_queue_head;
1302 add_response_info(sock, "%d %s\n", ci->values_num, ci->file);
1306 pthread_mutex_unlock(&cache_lock);
1308 return send_response(sock, RESP_OK, "in queue.\n");
1309 } /* }}} int handle_request_queue */
1311 static int handle_request_update (HANDLER_PROTO) /* {{{ */
1313 char *file, file_tmp[PATH_MAX];
1316 char orig_buf[CMD_MAX];
1320 /* save it for the journal later */
1321 if (!JOURNAL_REPLAY(sock))
1322 strncpy(orig_buf, buffer, buffer_size);
1324 status = buffer_get_field (&buffer, &buffer_size, &file);
1326 return syntax_error(sock,cmd);
1328 pthread_mutex_lock(&stats_lock);
1329 stats_updates_received++;
1330 pthread_mutex_unlock(&stats_lock);
1332 get_abs_path(&file, file_tmp);
1333 if (!check_file_access(file, sock)) return 0;
1335 pthread_mutex_lock (&cache_lock);
1336 ci = g_tree_lookup (cache_tree, file);
1338 if (ci == NULL) /* {{{ */
1340 struct stat statbuf;
1343 /* don't hold the lock while we setup; stat(2) might block */
1344 pthread_mutex_unlock(&cache_lock);
1346 memset (&statbuf, 0, sizeof (statbuf));
1347 status = stat (file, &statbuf);
1350 RRDD_LOG (LOG_NOTICE, "handle_request_update: stat (%s) failed.", file);
1353 if (status == ENOENT)
1354 return send_response(sock, RESP_ERR, "No such file: %s\n", file);
1356 return send_response(sock, RESP_ERR,
1357 "stat failed with error %i.\n", status);
1359 if (!S_ISREG (statbuf.st_mode))
1360 return send_response(sock, RESP_ERR, "Not a regular file: %s\n", file);
1362 if (access(file, R_OK|W_OK) != 0)
1363 return send_response(sock, RESP_ERR, "Cannot read/write %s: %s\n",
1364 file, rrd_strerror(errno));
1366 ci = (cache_item_t *) malloc (sizeof (cache_item_t));
1369 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
1371 return send_response(sock, RESP_ERR, "malloc failed.\n");
1373 memset (ci, 0, sizeof (cache_item_t));
1375 ci->file = strdup (file);
1376 if (ci->file == NULL)
1379 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
1381 return send_response(sock, RESP_ERR, "strdup failed.\n");
1384 wipe_ci_values(ci, now);
1385 ci->flags = CI_FLAGS_IN_TREE;
1386 pthread_cond_init(&ci->flushed, NULL);
1388 pthread_mutex_lock(&cache_lock);
1390 /* another UPDATE might have added this entry in the meantime */
1391 tmp = g_tree_lookup (cache_tree, file);
1393 g_tree_replace (cache_tree, (void *) ci->file, (void *) ci);
1396 free_cache_item (ci);
1400 /* state may have changed while we were unlocked */
1401 if (state == SHUTDOWN)
1404 assert (ci != NULL);
1406 /* don't re-write updates in replay mode */
1407 if (!JOURNAL_REPLAY(sock))
1408 journal_write("update", orig_buf);
1410 while (buffer_size > 0)
1416 status = buffer_get_field (&buffer, &buffer_size, &value);
1419 RRDD_LOG (LOG_INFO, "handle_request_update: Error reading field.");
1423 /* make sure update time is always moving forward */
1424 stamp = strtol(value, &eostamp, 10);
1425 if (eostamp == value || eostamp == NULL || *eostamp != ':')
1427 pthread_mutex_unlock(&cache_lock);
1428 return send_response(sock, RESP_ERR,
1429 "Cannot find timestamp in '%s'!\n", value);
1431 else if (stamp <= ci->last_update_stamp)
1433 pthread_mutex_unlock(&cache_lock);
1434 return send_response(sock, RESP_ERR,
1435 "illegal attempt to update using time %ld when last"
1436 " update time is %ld (minimum one second step)\n",
1437 stamp, ci->last_update_stamp);
1440 ci->last_update_stamp = stamp;
1442 if (!rrd_add_strdup(&ci->values, &ci->values_num, value))
1444 RRDD_LOG (LOG_ERR, "handle_request_update: rrd_add_strdup failed.");
1451 if (((now - ci->last_flush_time) >= config_write_interval)
1452 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
1453 && (ci->values_num > 0))
1455 enqueue_cache_item (ci, TAIL);
1458 pthread_mutex_unlock (&cache_lock);
1461 return send_response(sock, RESP_ERR, "No values updated.\n");
1463 return send_response(sock, RESP_OK,
1464 "errors, enqueued %i value(s).\n", values_num);
1469 } /* }}} int handle_request_update */
1471 /* we came across a "WROTE" entry during journal replay.
1472 * throw away any values that we have accumulated for this file
1474 static int handle_request_wrote (HANDLER_PROTO) /* {{{ */
1477 const char *file = buffer;
1479 pthread_mutex_lock(&cache_lock);
1481 ci = g_tree_lookup(cache_tree, file);
1484 pthread_mutex_unlock(&cache_lock);
1489 rrd_free_ptrs((void ***) &ci->values, &ci->values_num);
1491 wipe_ci_values(ci, now);
1492 remove_from_queue(ci);
1494 pthread_mutex_unlock(&cache_lock);
1496 } /* }}} int handle_request_wrote */
1498 /* start "BATCH" processing */
1499 static int batch_start (HANDLER_PROTO) /* {{{ */
1502 if (sock->batch_start)
1503 return send_response(sock, RESP_ERR, "Already in BATCH\n");
1505 status = send_response(sock, RESP_OK,
1506 "Go ahead. End with dot '.' on its own line.\n");
1507 sock->batch_start = time(NULL);
1508 sock->batch_cmd = 0;
1511 } /* }}} static int batch_start */
1513 /* finish "BATCH" processing and return results to the client */
1514 static int batch_done (HANDLER_PROTO) /* {{{ */
1516 assert(sock->batch_start);
1517 sock->batch_start = 0;
1518 sock->batch_cmd = 0;
1519 return send_response(sock, RESP_OK, "errors\n");
1520 } /* }}} static int batch_done */
1522 static int handle_request_quit (HANDLER_PROTO) /* {{{ */
1525 } /* }}} static int handle_request_quit */
1527 static command_t list_of_commands[] = { /* {{{ */
1530 handle_request_update,
1532 "UPDATE <filename> <values> [<values> ...]\n"
1534 "Adds the given file to the internal cache if it is not yet known and\n"
1535 "appends the given value(s) to the entry. See the rrdcached(1) manpage\n"
1538 "Each <values> has the following form:\n"
1539 " <values> = <time>:<value>[:<value>[...]]\n"
1540 "See the rrdupdate(1) manpage for details.\n"
1544 handle_request_wrote,
1545 CMD_CONTEXT_JOURNAL,
1551 handle_request_flush,
1552 CMD_CONTEXT_CLIENT | CMD_CONTEXT_BATCH,
1553 "FLUSH <filename>\n"
1555 "Adds the given filename to the head of the update queue and returns\n"
1556 "after it has been dequeued.\n"
1560 handle_request_flushall,
1564 "Triggers writing of all pending updates. Returns immediately.\n"
1568 handle_request_pending,
1570 "PENDING <filename>\n"
1572 "Shows any 'pending' updates for a file, in order.\n"
1573 "The updates shown have not yet been written to the underlying RRD file.\n"
1577 handle_request_forget,
1579 "FORGET <filename>\n"
1581 "Removes the file completely from the cache.\n"
1582 "Any pending updates for the file will be lost.\n"
1586 handle_request_queue,
1590 "Shows all files in the output queue.\n"
1591 "The output is zero or more lines in the following format:\n"
1592 "(where <num_vals> is the number of values to be written)\n"
1594 "<num_vals> <filename>\n"
1598 handle_request_stats,
1602 "Returns some performance counters, see the rrdcached(1) manpage for\n"
1603 "a description of the values.\n"
1607 handle_request_help,
1609 "HELP [<command>]\n",
1610 NULL, /* special! */
1618 "The 'BATCH' command permits the client to initiate a bulk load\n"
1619 " of commands to rrdcached.\n"
1624 " server: 0 Go ahead. End with dot '.' on its own line.\n"
1625 " client: command #1\n"
1626 " client: command #2\n"
1627 " client: ... and so on\n"
1629 " server: 2 errors\n"
1630 " server: 7 message for command #7\n"
1631 " server: 9 message for command #9\n"
1633 "For more information, consult the rrdcached(1) documentation.\n"
1636 ".", /* BATCH terminator */
1644 handle_request_quit,
1645 CMD_CONTEXT_CLIENT | CMD_CONTEXT_BATCH,
1648 "Disconnect from rrdcached.\n"
1650 }; /* }}} command_t list_of_commands[] */
1651 static size_t list_of_commands_len = sizeof (list_of_commands)
1652 / sizeof (list_of_commands[0]);
1654 static command_t *find_command(char *cmd)
1658 for (i = 0; i < list_of_commands_len; i++)
1659 if (strcasecmp(cmd, list_of_commands[i].cmd) == 0)
1660 return (&list_of_commands[i]);
1664 /* We currently use the index in the `list_of_commands' array as a bit position
1665 * in `listen_socket_t.permissions'. This member schould NEVER be accessed from
1666 * outside these functions so that switching to a more elegant storage method
1667 * is easily possible. */
1668 static ssize_t find_command_index (const char *cmd) /* {{{ */
1672 for (i = 0; i < list_of_commands_len; i++)
1673 if (strcasecmp(cmd, list_of_commands[i].cmd) == 0)
1674 return ((ssize_t) i);
1676 } /* }}} ssize_t find_command_index */
1678 static int socket_permission_check (listen_socket_t *sock, /* {{{ */
1683 if (JOURNAL_REPLAY(sock))
1689 if ((strcasecmp ("QUIT", cmd) == 0)
1690 || (strcasecmp ("HELP", cmd) == 0))
1692 else if (strcmp (".", cmd) == 0)
1695 i = find_command_index (cmd);
1700 if ((sock->permissions & (1 << i)) != 0)
1703 } /* }}} int socket_permission_check */
1705 static int socket_permission_add (listen_socket_t *sock, /* {{{ */
1710 i = find_command_index (cmd);
1715 sock->permissions |= (1 << i);
1717 } /* }}} int socket_permission_add */
1719 /* check whether commands are received in the expected context */
1720 static int command_check_context(listen_socket_t *sock, command_t *cmd)
1722 if (JOURNAL_REPLAY(sock))
1723 return (cmd->context & CMD_CONTEXT_JOURNAL);
1724 else if (sock->batch_start)
1725 return (cmd->context & CMD_CONTEXT_BATCH);
1727 return (cmd->context & CMD_CONTEXT_CLIENT);
1733 static int handle_request_help (HANDLER_PROTO) /* {{{ */
1738 command_t *help = NULL;
1740 status = buffer_get_field (&buffer, &buffer_size, &cmd_str);
1742 help = find_command(cmd_str);
1744 if (help && (help->syntax || help->help))
1748 snprintf(tmp, sizeof(tmp)-1, "Help for %s\n", help->cmd);
1752 add_response_info(sock, "Usage: %s\n", help->syntax);
1755 add_response_info(sock, "%s\n", help->help);
1761 resp_txt = "Command overview\n";
1763 for (i = 0; i < list_of_commands_len; i++)
1765 if (list_of_commands[i].syntax == NULL)
1767 add_response_info (sock, "%s", list_of_commands[i].syntax);
1771 return send_response(sock, RESP_OK, resp_txt);
1772 } /* }}} int handle_request_help */
1774 static int handle_request (DISPATCH_PROTO) /* {{{ */
1776 char *buffer_ptr = buffer;
1777 char *cmd_str = NULL;
1778 command_t *cmd = NULL;
1781 assert (buffer[buffer_size - 1] == '\0');
1783 status = buffer_get_field (&buffer_ptr, &buffer_size, &cmd_str);
1786 RRDD_LOG (LOG_INFO, "handle_request: Unable parse command.");
1790 if (sock != NULL && sock->batch_start)
1793 cmd = find_command(cmd_str);
1795 return send_response(sock, RESP_ERR, "Unknown command: %s\n", cmd_str);
1797 if (!socket_permission_check (sock, cmd->cmd))
1798 return send_response(sock, RESP_ERR, "Permission denied.\n");
1800 if (!command_check_context(sock, cmd))
1801 return send_response(sock, RESP_ERR, "Can't use '%s' here.\n", cmd_str);
1803 return cmd->handler(cmd, sock, now, buffer_ptr, buffer_size);
1804 } /* }}} int handle_request */
1806 static void journal_set_free (journal_set *js) /* {{{ */
1811 rrd_free_ptrs((void ***) &js->files, &js->files_num);
1814 } /* }}} journal_set_free */
1816 static void journal_set_remove (journal_set *js) /* {{{ */
1821 for (uint i=0; i < js->files_num; i++)
1823 RRDD_LOG(LOG_DEBUG, "removing old journal %s", js->files[i]);
1824 unlink(js->files[i]);
1826 } /* }}} journal_set_remove */
1828 /* close current journal file handle.
1829 * MUST hold journal_lock before calling */
1830 static void journal_close(void) /* {{{ */
1832 if (journal_fh != NULL)
1834 if (fclose(journal_fh) != 0)
1835 RRDD_LOG(LOG_ERR, "cannot close journal: %s", rrd_strerror(errno));
1840 } /* }}} journal_close */
1842 /* MUST hold journal_lock before calling */
1843 static void journal_new_file(void) /* {{{ */
1847 char new_file[PATH_MAX + 1];
1849 assert(journal_dir != NULL);
1850 assert(journal_cur != NULL);
1854 gettimeofday(&now, NULL);
1855 /* this format assures that the files sort in strcmp() order */
1856 snprintf(new_file, PATH_MAX, "%s/%s.%010d.%06d",
1857 journal_dir, JOURNAL_BASE, (int)now.tv_sec, (int)now.tv_usec);
1859 new_fd = open(new_file, O_WRONLY|O_CREAT|O_APPEND,
1860 S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
1864 journal_fh = fdopen(new_fd, "a");
1865 if (journal_fh == NULL)
1868 journal_size = ftell(journal_fh);
1869 RRDD_LOG(LOG_DEBUG, "started new journal %s", new_file);
1871 /* record the file in the journal set */
1872 rrd_add_strdup(&journal_cur->files, &journal_cur->files_num, new_file);
1878 "JOURNALING DISABLED: Error while trying to create %s : %s",
1879 new_file, rrd_strerror(errno));
1881 "JOURNALING DISABLED: All values will be flushed at shutdown");
1884 config_flush_at_shutdown = 1;
1886 } /* }}} journal_new_file */
1888 /* MUST NOT hold journal_lock before calling this */
1889 static void journal_rotate(void) /* {{{ */
1891 journal_set *old_js = NULL;
1893 if (journal_dir == NULL)
1896 RRDD_LOG(LOG_DEBUG, "rotating journals");
1898 pthread_mutex_lock(&stats_lock);
1899 ++stats_journal_rotate;
1900 pthread_mutex_unlock(&stats_lock);
1902 pthread_mutex_lock(&journal_lock);
1906 /* rotate the journal sets */
1907 old_js = journal_old;
1908 journal_old = journal_cur;
1909 journal_cur = calloc(1, sizeof(journal_set));
1911 if (journal_cur != NULL)
1914 RRDD_LOG(LOG_CRIT, "journal_rotate: malloc(journal_set) failed\n");
1916 pthread_mutex_unlock(&journal_lock);
1918 journal_set_remove(old_js);
1919 journal_set_free (old_js);
1921 } /* }}} static void journal_rotate */
1923 /* MUST hold journal_lock when calling */
1924 static void journal_done(void) /* {{{ */
1926 if (journal_cur == NULL)
1931 if (config_flush_at_shutdown)
1933 RRDD_LOG(LOG_INFO, "removing journals");
1934 journal_set_remove(journal_old);
1935 journal_set_remove(journal_cur);
1939 RRDD_LOG(LOG_INFO, "expedited shutdown; "
1940 "journals will be used at next startup");
1943 journal_set_free(journal_cur);
1944 journal_set_free(journal_old);
1947 } /* }}} static void journal_done */
1949 static int journal_write(char *cmd, char *args) /* {{{ */
1953 if (journal_fh == NULL)
1956 pthread_mutex_lock(&journal_lock);
1957 chars = fprintf(journal_fh, "%s %s\n", cmd, args);
1958 journal_size += chars;
1960 if (journal_size > JOURNAL_MAX)
1963 pthread_mutex_unlock(&journal_lock);
1967 pthread_mutex_lock(&stats_lock);
1968 stats_journal_bytes += chars;
1969 pthread_mutex_unlock(&stats_lock);
1973 } /* }}} static int journal_write */
1975 static int journal_replay (const char *file) /* {{{ */
1981 char entry[CMD_MAX];
1984 if (file == NULL) return 0;
1987 char *reason = "unknown error";
1989 struct stat statbuf;
1991 memset(&statbuf, 0, sizeof(statbuf));
1992 if (stat(file, &statbuf) != 0)
1994 reason = "stat error";
1997 else if (!S_ISREG(statbuf.st_mode))
1999 reason = "not a regular file";
2002 if (statbuf.st_uid != daemon_uid)
2004 reason = "not owned by daemon user";
2007 if (statbuf.st_mode & (S_IWGRP|S_IWOTH))
2009 reason = "must not be user/group writable";
2015 RRDD_LOG(LOG_ERR, "journal_replay: %s : %s (%s)",
2016 file, rrd_strerror(status), reason);
2021 fh = fopen(file, "r");
2024 if (errno != ENOENT)
2025 RRDD_LOG(LOG_ERR, "journal_replay: cannot open journal file: '%s' (%s)",
2026 file, rrd_strerror(errno));
2030 RRDD_LOG(LOG_NOTICE, "replaying from journal: %s", file);
2039 if (fgets(entry, sizeof(entry), fh) == NULL)
2041 entry_len = strlen(entry);
2043 /* check \n termination in case journal writing crashed mid-line */
2046 else if (entry[entry_len - 1] != '\n')
2048 RRDD_LOG(LOG_NOTICE, "Malformed journal entry at line %"PRIu64, line);
2053 entry[entry_len - 1] = '\0';
2055 if (handle_request(NULL, now, entry, entry_len) == 0)
2063 RRDD_LOG(LOG_INFO, "Replayed %d entries (%d failures)",
2064 entry_cnt, fail_cnt);
2066 return entry_cnt > 0 ? 1 : 0;
2067 } /* }}} static int journal_replay */
2069 static int journal_sort(const void *v1, const void *v2)
2071 char **jn1 = (char **) v1;
2072 char **jn2 = (char **) v2;
2074 return strcmp(*jn1,*jn2);
2077 static void journal_init(void) /* {{{ */
2079 int had_journal = 0;
2081 struct dirent *dent;
2082 char path[PATH_MAX+1];
2084 if (journal_dir == NULL) return;
2086 pthread_mutex_lock(&journal_lock);
2088 journal_cur = calloc(1, sizeof(journal_set));
2089 if (journal_cur == NULL)
2091 RRDD_LOG(LOG_CRIT, "journal_rotate: malloc(journal_set) failed\n");
2095 RRDD_LOG(LOG_INFO, "checking for journal files");
2097 /* Handle old journal files during transition. This gives them the
2098 * correct sort order. TODO: remove after first release
2101 char old_path[PATH_MAX+1];
2102 snprintf(old_path, PATH_MAX, "%s/%s", journal_dir, JOURNAL_BASE ".old" );
2103 snprintf(path, PATH_MAX, "%s/%s", journal_dir, JOURNAL_BASE ".0000");
2104 rename(old_path, path);
2106 snprintf(old_path, PATH_MAX, "%s/%s", journal_dir, JOURNAL_BASE );
2107 snprintf(path, PATH_MAX, "%s/%s", journal_dir, JOURNAL_BASE ".0001");
2108 rename(old_path, path);
2111 dir = opendir(journal_dir);
2112 while ((dent = readdir(dir)) != NULL)
2114 /* looks like a journal file? */
2115 if (strncmp(dent->d_name, JOURNAL_BASE, strlen(JOURNAL_BASE)))
2118 snprintf(path, PATH_MAX, "%s/%s", journal_dir, dent->d_name);
2120 if (!rrd_add_strdup(&journal_cur->files, &journal_cur->files_num, path))
2122 RRDD_LOG(LOG_CRIT, "journal_init: cannot add journal file %s!",
2129 qsort(journal_cur->files, journal_cur->files_num,
2130 sizeof(journal_cur->files[0]), journal_sort);
2132 for (uint i=0; i < journal_cur->files_num; i++)
2133 had_journal += journal_replay(journal_cur->files[i]);
2137 /* it must have been a crash. start a flush */
2138 if (had_journal && config_flush_at_shutdown)
2139 flush_old_values(-1);
2141 pthread_mutex_unlock(&journal_lock);
2143 RRDD_LOG(LOG_INFO, "journal processing complete");
2145 } /* }}} static void journal_init */
2147 static void free_listen_socket(listen_socket_t *sock) /* {{{ */
2149 assert(sock != NULL);
2151 free(sock->rbuf); sock->rbuf = NULL;
2152 free(sock->wbuf); sock->wbuf = NULL;
2154 } /* }}} void free_listen_socket */
2156 static void close_connection(listen_socket_t *sock) /* {{{ */
2164 free_listen_socket(sock);
2166 } /* }}} void close_connection */
2168 static void *connection_thread_main (void *args) /* {{{ */
2170 listen_socket_t *sock;
2173 sock = (listen_socket_t *) args;
2176 /* init read buffers */
2177 sock->next_read = sock->next_cmd = 0;
2178 sock->rbuf = malloc(RBUF_SIZE);
2179 if (sock->rbuf == NULL)
2181 RRDD_LOG(LOG_ERR, "connection_thread_main: cannot malloc read buffer");
2182 close_connection(sock);
2186 pthread_mutex_lock (&connection_threads_lock);
2187 connection_threads_num++;
2188 pthread_mutex_unlock (&connection_threads_lock);
2190 while (state == RUNNING)
2197 struct pollfd pollfd;
2201 pollfd.events = POLLIN | POLLPRI;
2204 status = poll (&pollfd, 1, /* timeout = */ 500);
2205 if (state != RUNNING)
2207 else if (status == 0) /* timeout */
2209 else if (status < 0) /* error */
2212 if (status != EINTR)
2213 RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
2217 if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
2219 else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
2221 RRDD_LOG (LOG_WARNING, "connection_thread_main: "
2222 "poll(2) returned something unexpected: %#04hx",
2227 rbytes = read(fd, sock->rbuf + sock->next_read,
2228 RBUF_SIZE - sock->next_read);
2231 RRDD_LOG(LOG_ERR, "connection_thread_main: read() failed.");
2234 else if (rbytes == 0)
2237 sock->next_read += rbytes;
2239 if (sock->batch_start)
2240 now = sock->batch_start;
2244 while ((cmd = next_cmd(sock, &cmd_len)) != NULL)
2246 status = handle_request (sock, now, cmd, cmd_len+1);
2253 close_connection(sock);
2255 /* Remove this thread from the connection threads list */
2256 pthread_mutex_lock (&connection_threads_lock);
2257 connection_threads_num--;
2258 if (connection_threads_num <= 0)
2259 pthread_cond_broadcast(&connection_threads_done);
2260 pthread_mutex_unlock (&connection_threads_lock);
2263 } /* }}} void *connection_thread_main */
2265 static int open_listen_socket_unix (const listen_socket_t *sock) /* {{{ */
2268 struct sockaddr_un sa;
2269 listen_socket_t *temp;
2272 char *path_copy, *dir;
2275 if (strncmp(path, "unix:", strlen("unix:")) == 0)
2276 path += strlen("unix:");
2278 /* dirname may modify its argument */
2279 path_copy = strdup(path);
2280 if (path_copy == NULL)
2282 fprintf(stderr, "rrdcached: strdup(): %s\n",
2283 rrd_strerror(errno));
2287 dir = dirname(path_copy);
2288 if (rrd_mkdir_p(dir, 0777) != 0)
2290 fprintf(stderr, "Failed to create socket directory '%s': %s\n",
2291 dir, rrd_strerror(errno));
2297 temp = (listen_socket_t *) rrd_realloc (listen_fds,
2298 sizeof (listen_fds[0]) * (listen_fds_num + 1));
2301 fprintf (stderr, "rrdcached: open_listen_socket_unix: realloc failed.\n");
2305 memcpy (listen_fds + listen_fds_num, sock, sizeof (listen_fds[0]));
2307 fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
2310 fprintf (stderr, "rrdcached: unix socket(2) failed: %s\n",
2311 rrd_strerror(errno));
2315 memset (&sa, 0, sizeof (sa));
2316 sa.sun_family = AF_UNIX;
2317 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
2319 /* if we've gotten this far, we own the pid file. any daemon started
2320 * with the same args must not be alive. therefore, ensure that we can
2321 * create the socket...
2325 status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
2328 fprintf (stderr, "rrdcached: bind(%s) failed: %s.\n",
2329 path, rrd_strerror(errno));
2334 /* tweak the sockets group ownership */
2335 if (sock->socket_group != (gid_t)-1)
2337 if ( (chown(path, getuid(), sock->socket_group) != 0) ||
2338 (chmod(path, (S_IRUSR|S_IWUSR|S_IXUSR | S_IRGRP|S_IWGRP)) != 0) )
2340 fprintf(stderr, "rrdcached: failed to set socket group permissions (%s)\n", strerror(errno));
2344 if (sock->socket_permissions != (mode_t)-1)
2346 if (chmod(path, sock->socket_permissions) != 0)
2347 fprintf(stderr, "rrdcached: failed to set socket file permissions (%o): %s\n",
2348 (unsigned int)sock->socket_permissions, strerror(errno));
2351 status = listen (fd, /* backlog = */ 10);
2354 fprintf (stderr, "rrdcached: listen(%s) failed: %s.\n",
2355 path, rrd_strerror(errno));
2361 listen_fds[listen_fds_num].fd = fd;
2362 listen_fds[listen_fds_num].family = PF_UNIX;
2363 strncpy(listen_fds[listen_fds_num].addr, path,
2364 sizeof (listen_fds[listen_fds_num].addr) - 1);
2368 } /* }}} int open_listen_socket_unix */
2370 static int open_listen_socket_network(const listen_socket_t *sock) /* {{{ */
2372 struct addrinfo ai_hints;
2373 struct addrinfo *ai_res;
2374 struct addrinfo *ai_ptr;
2375 char addr_copy[NI_MAXHOST];
2380 strncpy (addr_copy, sock->addr, sizeof(addr_copy)-1);
2381 addr_copy[sizeof (addr_copy) - 1] = 0;
2384 memset (&ai_hints, 0, sizeof (ai_hints));
2385 ai_hints.ai_flags = 0;
2386 #ifdef AI_ADDRCONFIG
2387 ai_hints.ai_flags |= AI_ADDRCONFIG;
2389 ai_hints.ai_family = AF_UNSPEC;
2390 ai_hints.ai_socktype = SOCK_STREAM;
2393 if (*addr == '[') /* IPv6+port format */
2395 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
2398 port = strchr (addr, ']');
2401 fprintf (stderr, "rrdcached: Malformed address: %s\n", sock->addr);
2409 else if (*port == 0)
2413 fprintf (stderr, "rrdcached: Garbage after address: %s\n", port);
2416 } /* if (*addr == '[') */
2419 port = rindex(addr, ':');
2427 status = getaddrinfo (addr,
2428 port == NULL ? RRDCACHED_DEFAULT_PORT : port,
2429 &ai_hints, &ai_res);
2432 fprintf (stderr, "rrdcached: getaddrinfo(%s) failed: %s\n",
2433 addr, gai_strerror (status));
2437 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2440 listen_socket_t *temp;
2443 temp = (listen_socket_t *) rrd_realloc (listen_fds,
2444 sizeof (listen_fds[0]) * (listen_fds_num + 1));
2448 "rrdcached: open_listen_socket_network: realloc failed.\n");
2452 memcpy (listen_fds + listen_fds_num, sock, sizeof (listen_fds[0]));
2454 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
2457 fprintf (stderr, "rrdcached: network socket(2) failed: %s.\n",
2458 rrd_strerror(errno));
2462 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
2464 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2467 fprintf (stderr, "rrdcached: bind(%s) failed: %s.\n",
2468 sock->addr, rrd_strerror(errno));
2473 status = listen (fd, /* backlog = */ 10);
2476 fprintf (stderr, "rrdcached: listen(%s) failed: %s\n.",
2477 sock->addr, rrd_strerror(errno));
2479 freeaddrinfo(ai_res);
2483 listen_fds[listen_fds_num].fd = fd;
2484 listen_fds[listen_fds_num].family = ai_ptr->ai_family;
2486 } /* for (ai_ptr) */
2488 freeaddrinfo(ai_res);
2490 } /* }}} static int open_listen_socket_network */
2492 static int open_listen_socket (const listen_socket_t *sock) /* {{{ */
2494 assert(sock != NULL);
2495 assert(sock->addr != NULL);
2497 if (strncmp ("unix:", sock->addr, strlen ("unix:")) == 0
2498 || sock->addr[0] == '/')
2499 return (open_listen_socket_unix(sock));
2501 return (open_listen_socket_network(sock));
2502 } /* }}} int open_listen_socket */
2504 static int close_listen_sockets (void) /* {{{ */
2508 for (i = 0; i < listen_fds_num; i++)
2510 close (listen_fds[i].fd);
2512 if (listen_fds[i].family == PF_UNIX)
2513 unlink(listen_fds[i].addr);
2521 } /* }}} int close_listen_sockets */
2523 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
2525 struct pollfd *pollfds;
2530 if (listen_fds_num < 1)
2532 RRDD_LOG(LOG_ERR, "listen_thread_main: no listen_fds !");
2536 pollfds_num = listen_fds_num;
2537 pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
2538 if (pollfds == NULL)
2540 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
2543 memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
2545 RRDD_LOG(LOG_INFO, "listening for connections");
2547 while (state == RUNNING)
2549 for (i = 0; i < pollfds_num; i++)
2551 pollfds[i].fd = listen_fds[i].fd;
2552 pollfds[i].events = POLLIN | POLLPRI;
2553 pollfds[i].revents = 0;
2556 status = poll (pollfds, pollfds_num, /* timeout = */ 1000);
2557 if (state != RUNNING)
2559 else if (status == 0) /* timeout */
2561 else if (status < 0) /* error */
2564 if (status != EINTR)
2566 RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
2571 for (i = 0; i < pollfds_num; i++)
2573 listen_socket_t *client_sock;
2574 struct sockaddr_storage client_sa;
2575 socklen_t client_sa_size;
2577 pthread_attr_t attr;
2579 if (pollfds[i].revents == 0)
2582 if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
2584 RRDD_LOG (LOG_ERR, "listen_thread_main: "
2585 "poll(2) returned something unexpected for listen FD #%i.",
2590 client_sock = (listen_socket_t *) malloc (sizeof (listen_socket_t));
2591 if (client_sock == NULL)
2593 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
2596 memcpy(client_sock, &listen_fds[i], sizeof(listen_fds[0]));
2598 client_sa_size = sizeof (client_sa);
2599 client_sock->fd = accept (pollfds[i].fd,
2600 (struct sockaddr *) &client_sa, &client_sa_size);
2601 if (client_sock->fd < 0)
2603 RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
2608 pthread_attr_init (&attr);
2609 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
2611 status = pthread_create (&tid, &attr, connection_thread_main,
2615 RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
2616 close_connection(client_sock);
2619 } /* for (pollfds_num) */
2620 } /* while (state == RUNNING) */
2622 RRDD_LOG(LOG_INFO, "starting shutdown");
2624 close_listen_sockets ();
2626 pthread_mutex_lock (&connection_threads_lock);
2627 while (connection_threads_num > 0)
2628 pthread_cond_wait(&connection_threads_done, &connection_threads_lock);
2629 pthread_mutex_unlock (&connection_threads_lock);
2634 } /* }}} void *listen_thread_main */
2636 static int daemonize (void) /* {{{ */
2641 daemon_uid = geteuid();
2643 pid_fd = open_pidfile("create", O_CREAT|O_EXCL|O_WRONLY);
2645 pid_fd = check_pidfile();
2649 /* open all the listen sockets */
2650 if (config_listen_address_list_len > 0)
2652 for (size_t i = 0; i < config_listen_address_list_len; i++)
2653 open_listen_socket (config_listen_address_list[i]);
2655 rrd_free_ptrs((void ***) &config_listen_address_list,
2656 &config_listen_address_list_len);
2660 listen_socket_t sock;
2661 memset(&sock, 0, sizeof(sock));
2662 strncpy(sock.addr, RRDCACHED_DEFAULT_ADDRESS, sizeof(sock.addr)-1);
2663 open_listen_socket (&sock);
2666 if (listen_fds_num < 1)
2668 fprintf (stderr, "rrdcached: FATAL: cannot open any listen sockets\n");
2672 if (!stay_foreground)
2679 fprintf (stderr, "daemonize: fork(2) failed.\n");
2685 /* Become session leader */
2688 /* Open the first three file descriptors to /dev/null */
2693 open ("/dev/null", O_RDWR);
2694 if (dup(0) == -1 || dup(0) == -1){
2695 RRDD_LOG (LOG_ERR, "faild to run dup.\n");
2697 } /* if (!stay_foreground) */
2699 /* Change into the /tmp directory. */
2700 base_dir = (config_base_dir != NULL)
2704 if (chdir (base_dir) != 0)
2706 fprintf (stderr, "daemonize: chdir (%s) failed.\n", base_dir);
2710 install_signal_handlers();
2712 openlog ("rrdcached", LOG_PID, LOG_DAEMON);
2713 RRDD_LOG(LOG_INFO, "starting up");
2715 cache_tree = g_tree_new_full ((GCompareDataFunc) strcmp, NULL, NULL,
2716 (GDestroyNotify) free_cache_item);
2717 if (cache_tree == NULL)
2719 RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
2723 return write_pidfile (pid_fd);
2728 } /* }}} int daemonize */
2730 static int cleanup (void) /* {{{ */
2732 pthread_cond_broadcast (&flush_cond);
2733 pthread_join (flush_thread, NULL);
2735 pthread_cond_broadcast (&queue_cond);
2736 for (int i = 0; i < config_queue_threads; i++)
2737 pthread_join (queue_threads[i], NULL);
2739 if (config_flush_at_shutdown)
2741 assert(cache_queue_head == NULL);
2742 RRDD_LOG(LOG_INFO, "clean shutdown; all RRDs flushed");
2745 free(queue_threads);
2746 free(config_base_dir);
2748 pthread_mutex_lock(&cache_lock);
2749 g_tree_destroy(cache_tree);
2751 pthread_mutex_lock(&journal_lock);
2754 RRDD_LOG(LOG_INFO, "goodbye");
2758 free(config_pid_file);
2761 } /* }}} int cleanup */
2763 static int read_options (int argc, char **argv) /* {{{ */
2768 char **permissions = NULL;
2769 size_t permissions_len = 0;
2771 gid_t socket_group = (gid_t)-1;
2772 mode_t socket_permissions = (mode_t)-1;
2774 while ((option = getopt(argc, argv, "gl:s:m:P:f:w:z:t:Bb:p:Fj:h?")) != -1)
2784 listen_socket_t *new;
2786 new = malloc(sizeof(listen_socket_t));
2789 fprintf(stderr, "read_options: malloc failed.\n");
2792 memset(new, 0, sizeof(listen_socket_t));
2794 strncpy(new->addr, optarg, sizeof(new->addr)-1);
2796 /* Add permissions to the socket {{{ */
2797 if (permissions_len != 0)
2800 for (i = 0; i < permissions_len; i++)
2802 status = socket_permission_add (new, permissions[i]);
2805 fprintf (stderr, "read_options: Adding permission \"%s\" to "
2806 "socket failed. Most likely, this permission doesn't "
2807 "exist. Check your command line.\n", permissions[i]);
2812 else /* if (permissions_len == 0) */
2814 /* Add permission for ALL commands to the socket. */
2816 for (i = 0; i < list_of_commands_len; i++)
2818 status = socket_permission_add (new, list_of_commands[i].cmd);
2821 fprintf (stderr, "read_options: Adding permission \"%s\" to "
2822 "socket failed. This should never happen, ever! Sorry.\n",
2828 /* }}} Done adding permissions. */
2830 new->socket_group = socket_group;
2831 new->socket_permissions = socket_permissions;
2833 if (!rrd_add_ptr((void ***)&config_listen_address_list,
2834 &config_listen_address_list_len, new))
2836 fprintf(stderr, "read_options: rrd_add_ptr failed.\n");
2842 /* set socket group permissions */
2848 group_gid = strtoul(optarg, NULL, 10);
2849 if (errno != EINVAL && group_gid>0)
2851 /* we were passed a number */
2852 grp = getgrgid(group_gid);
2856 grp = getgrnam(optarg);
2861 socket_group = grp->gr_gid;
2865 /* no idea what the user wanted... */
2866 fprintf (stderr, "read_options: couldn't map \"%s\" to a group, Sorry\n", optarg);
2872 /* set socket file permissions */
2876 char *endptr = NULL;
2878 tmp = strtol (optarg, &endptr, 8);
2879 if ((endptr == optarg) || (! endptr) || (*endptr != '\0')
2880 || (tmp > 07777) || (tmp < 0)) {
2881 fprintf (stderr, "read_options: Invalid file mode \"%s\".\n",
2886 socket_permissions = (mode_t)tmp;
2897 rrd_free_ptrs ((void *) &permissions, &permissions_len);
2899 optcopy = strdup (optarg);
2902 while ((ptr = strtok_r (dummy, ", ", &saveptr)) != NULL)
2905 rrd_add_strdup ((void *) &permissions, &permissions_len, ptr);
2916 temp = atoi (optarg);
2918 config_flush_interval = temp;
2921 fprintf (stderr, "Invalid flush interval: %s\n", optarg);
2931 temp = atoi (optarg);
2933 config_write_interval = temp;
2936 fprintf (stderr, "Invalid write interval: %s\n", optarg);
2946 temp = atoi(optarg);
2948 config_write_jitter = temp;
2951 fprintf (stderr, "Invalid write jitter: -z %s\n", optarg);
2961 threads = atoi(optarg);
2963 config_queue_threads = threads;
2966 fprintf (stderr, "Invalid thread count: -t %s\n", optarg);
2973 config_write_base_only = 1;
2979 char base_realpath[PATH_MAX];
2981 if (config_base_dir != NULL)
2982 free (config_base_dir);
2983 config_base_dir = strdup (optarg);
2984 if (config_base_dir == NULL)
2986 fprintf (stderr, "read_options: strdup failed.\n");
2990 if (rrd_mkdir_p (config_base_dir, 0777) != 0)
2992 fprintf (stderr, "Failed to create base directory '%s': %s\n",
2993 config_base_dir, rrd_strerror (errno));
2997 /* make sure that the base directory is not resolved via
2998 * symbolic links. this makes some performance-enhancing
2999 * assumptions possible (we don't have to resolve paths
3000 * that start with a "/")
3002 if (realpath(config_base_dir, base_realpath) == NULL)
3004 fprintf (stderr, "Failed to canonicalize the base directory '%s': "
3005 "%s\n", config_base_dir, rrd_strerror(errno));
3009 len = strlen (config_base_dir);
3010 while ((len > 0) && (config_base_dir[len - 1] == '/'))
3012 config_base_dir[len - 1] = 0;
3018 fprintf (stderr, "Invalid base directory: %s\n", optarg);
3022 _config_base_dir_len = len;
3024 len = strlen (base_realpath);
3025 while ((len > 0) && (base_realpath[len - 1] == '/'))
3027 base_realpath[len - 1] = '\0';
3031 if (strncmp(config_base_dir,
3032 base_realpath, sizeof(base_realpath)) != 0)
3035 "Base directory (-b) resolved via file system links!\n"
3036 "Please consult rrdcached '-b' documentation!\n"
3037 "Consider specifying the real directory (%s)\n",
3046 if (config_pid_file != NULL)
3047 free (config_pid_file);
3048 config_pid_file = strdup (optarg);
3049 if (config_pid_file == NULL)
3051 fprintf (stderr, "read_options: strdup failed.\n");
3058 config_flush_at_shutdown = 1;
3063 const char *dir = journal_dir = strdup(optarg);
3065 status = rrd_mkdir_p(dir, 0777);
3068 fprintf(stderr, "Failed to create journal directory '%s': %s\n",
3069 dir, rrd_strerror(errno));
3073 if (access(dir, R_OK|W_OK|X_OK) != 0)
3075 fprintf(stderr, "Must specify a writable directory with -j! (%s)\n",
3076 errno ? rrd_strerror(errno) : "");
3084 printf ("RRDCacheD %s\n"
3085 "Copyright (C) 2008,2009 Florian octo Forster and Kevin Brintnall\n"
3087 "Usage: rrdcached [options]\n"
3089 "Valid options are:\n"
3090 " -l <address> Socket address to listen to.\n"
3091 " -P <perms> Sets the permissions to assign to all following "
3093 " -w <seconds> Interval in which to write data.\n"
3094 " -z <delay> Delay writes up to <delay> seconds to spread load\n"
3095 " -t <threads> Number of write threads.\n"
3096 " -f <seconds> Interval in which to flush dead data.\n"
3097 " -p <file> Location of the PID-file.\n"
3098 " -b <dir> Base directory to change to.\n"
3099 " -B Restrict file access to paths within -b <dir>\n"
3100 " -g Do not fork and run in the foreground.\n"
3101 " -j <dir> Directory in which to create the journal files.\n"
3102 " -F Always flush all updates at shutdown\n"
3103 " -s <id|name> Make socket g+rw to named group\n"
3105 "For more information and a detailed description of all options "
3107 "to the rrdcached(1) manual page.\n",
3111 } /* switch (option) */
3112 } /* while (getopt) */
3114 /* advise the user when values are not sane */
3115 if (config_flush_interval < 2 * config_write_interval)
3116 fprintf(stderr, "WARNING: flush interval (-f) should be at least"
3117 " 2x write interval (-w) !\n");
3118 if (config_write_jitter > config_write_interval)
3119 fprintf(stderr, "WARNING: write delay (-z) should NOT be larger than"
3120 " write interval (-w) !\n");
3122 if (config_write_base_only && config_base_dir == NULL)
3123 fprintf(stderr, "WARNING: -B does not make sense without -b!\n"
3124 " Consult the rrdcached documentation\n");
3126 if (journal_dir == NULL)
3127 config_flush_at_shutdown = 1;
3129 rrd_free_ptrs ((void *) &permissions, &permissions_len);
3132 } /* }}} int read_options */
3134 int main (int argc, char **argv)
3138 status = read_options (argc, argv);
3146 status = daemonize ();
3149 fprintf (stderr, "rrdcached: daemonize failed, exiting.\n");
3155 /* start the queue threads */
3156 queue_threads = calloc(config_queue_threads, sizeof(*queue_threads));
3157 if (queue_threads == NULL)
3159 RRDD_LOG (LOG_ERR, "FATAL: cannot calloc queue threads");
3163 for (int i = 0; i < config_queue_threads; i++)
3165 memset (&queue_threads[i], 0, sizeof (*queue_threads));
3166 status = pthread_create (&queue_threads[i], NULL, queue_thread_main, NULL);
3169 RRDD_LOG (LOG_ERR, "FATAL: cannot create queue thread");
3175 /* start the flush thread */
3176 memset(&flush_thread, 0, sizeof(flush_thread));
3177 status = pthread_create (&flush_thread, NULL, flush_thread_main, NULL);
3180 RRDD_LOG (LOG_ERR, "FATAL: cannot create flush thread");
3185 listen_thread_main (NULL);
3192 * vim: set sw=2 sts=2 ts=8 et fdm=marker :