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>
110 #include <glib-2.0/glib.h>
113 #define RRDD_LOG(severity, ...) syslog ((severity), __VA_ARGS__)
116 # define __attribute__(x) /**/
122 typedef enum { RESP_ERR = -1, RESP_OK = 0 } response_code;
124 struct listen_socket_s
127 char addr[PATH_MAX + 1];
130 /* state for BATCH processing */
142 uint32_t permissions;
144 typedef struct listen_socket_s listen_socket_t;
147 typedef struct command_s command_t;
148 /* note: guard against "unused" warnings in the handlers */
149 #define DISPATCH_PROTO listen_socket_t *sock __attribute__((unused)),\
150 time_t now __attribute__((unused)),\
151 char *buffer __attribute__((unused)),\
152 size_t buffer_size __attribute__((unused))
154 #define HANDLER_PROTO command_t *cmd __attribute__((unused)),\
159 int (*handler)(HANDLER_PROTO);
161 char context; /* where we expect to see it */
162 #define CMD_CONTEXT_CLIENT (1<<0)
163 #define CMD_CONTEXT_BATCH (1<<1)
164 #define CMD_CONTEXT_JOURNAL (1<<2)
165 #define CMD_CONTEXT_ANY (0x7f)
172 typedef struct cache_item_s cache_item_t;
178 time_t last_flush_time;
179 time_t last_update_stamp;
180 #define CI_FLAGS_IN_TREE (1<<0)
181 #define CI_FLAGS_IN_QUEUE (1<<1)
183 pthread_cond_t flushed;
188 struct callback_flush_data_s
195 typedef struct callback_flush_data_s callback_flush_data_t;
202 typedef enum queue_side_e queue_side_t;
204 /* describe a set of journal files */
210 /* max length of socket command or response */
212 #define RBUF_SIZE (CMD_MAX*2)
217 static int stay_foreground = 0;
218 static uid_t daemon_uid;
220 static listen_socket_t *listen_fds = NULL;
221 static size_t listen_fds_num = 0;
224 RUNNING, /* normal operation */
225 FLUSHING, /* flushing remaining values */
226 SHUTDOWN /* shutting down */
229 static pthread_t *queue_threads;
230 static pthread_cond_t queue_cond = PTHREAD_COND_INITIALIZER;
231 static int config_queue_threads = 4;
233 static pthread_t flush_thread;
234 static pthread_cond_t flush_cond = PTHREAD_COND_INITIALIZER;
236 static pthread_mutex_t connection_threads_lock = PTHREAD_MUTEX_INITIALIZER;
237 static pthread_cond_t connection_threads_done = PTHREAD_COND_INITIALIZER;
238 static int connection_threads_num = 0;
241 static GTree *cache_tree = NULL;
242 static cache_item_t *cache_queue_head = NULL;
243 static cache_item_t *cache_queue_tail = NULL;
244 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
246 static int config_write_interval = 300;
247 static int config_write_jitter = 0;
248 static int config_flush_interval = 3600;
249 static int config_flush_at_shutdown = 0;
250 static char *config_pid_file = NULL;
251 static char *config_base_dir = NULL;
252 static size_t _config_base_dir_len = 0;
253 static int config_write_base_only = 0;
255 static listen_socket_t **config_listen_address_list = NULL;
256 static size_t config_listen_address_list_len = 0;
258 static uint64_t stats_queue_length = 0;
259 static uint64_t stats_updates_received = 0;
260 static uint64_t stats_flush_received = 0;
261 static uint64_t stats_updates_written = 0;
262 static uint64_t stats_data_sets_written = 0;
263 static uint64_t stats_journal_bytes = 0;
264 static uint64_t stats_journal_rotate = 0;
265 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
267 /* Journaled updates */
268 #define JOURNAL_BASE "rrd.journal"
269 static journal_set *journal_cur = NULL;
270 static journal_set *journal_old = NULL;
271 static char *journal_dir = NULL;
272 static FILE *journal_fh = NULL; /* current journal file handle */
273 static long journal_size = 0; /* current journal size */
274 #define JOURNAL_MAX (1 * 1024 * 1024 * 1024)
275 static pthread_mutex_t journal_lock = PTHREAD_MUTEX_INITIALIZER;
276 static int journal_write(char *cmd, char *args);
277 static void journal_done(void);
278 static void journal_rotate(void);
280 /* prototypes for forward refernces */
281 static int handle_request_help (HANDLER_PROTO);
286 static void sig_common (const char *sig) /* {{{ */
288 RRDD_LOG(LOG_NOTICE, "caught SIG%s", sig);
290 pthread_cond_broadcast(&flush_cond);
291 pthread_cond_broadcast(&queue_cond);
292 } /* }}} void sig_common */
294 static void sig_int_handler (int s __attribute__((unused))) /* {{{ */
297 } /* }}} void sig_int_handler */
299 static void sig_term_handler (int s __attribute__((unused))) /* {{{ */
302 } /* }}} void sig_term_handler */
304 static void sig_usr1_handler (int s __attribute__((unused))) /* {{{ */
306 config_flush_at_shutdown = 1;
308 } /* }}} void sig_usr1_handler */
310 static void sig_usr2_handler (int s __attribute__((unused))) /* {{{ */
312 config_flush_at_shutdown = 0;
314 } /* }}} void sig_usr2_handler */
316 static void install_signal_handlers(void) /* {{{ */
318 /* These structures are static, because `sigaction' behaves weird if the are
320 static struct sigaction sa_int;
321 static struct sigaction sa_term;
322 static struct sigaction sa_pipe;
323 static struct sigaction sa_usr1;
324 static struct sigaction sa_usr2;
326 /* Install signal handlers */
327 memset (&sa_int, 0, sizeof (sa_int));
328 sa_int.sa_handler = sig_int_handler;
329 sigaction (SIGINT, &sa_int, NULL);
331 memset (&sa_term, 0, sizeof (sa_term));
332 sa_term.sa_handler = sig_term_handler;
333 sigaction (SIGTERM, &sa_term, NULL);
335 memset (&sa_pipe, 0, sizeof (sa_pipe));
336 sa_pipe.sa_handler = SIG_IGN;
337 sigaction (SIGPIPE, &sa_pipe, NULL);
339 memset (&sa_pipe, 0, sizeof (sa_usr1));
340 sa_usr1.sa_handler = sig_usr1_handler;
341 sigaction (SIGUSR1, &sa_usr1, NULL);
343 memset (&sa_usr2, 0, sizeof (sa_usr2));
344 sa_usr2.sa_handler = sig_usr2_handler;
345 sigaction (SIGUSR2, &sa_usr2, NULL);
347 } /* }}} void install_signal_handlers */
349 static int open_pidfile(char *action, int oflag) /* {{{ */
353 char *file_copy, *dir;
355 file = (config_pid_file != NULL)
357 : LOCALSTATEDIR "/run/rrdcached.pid";
359 /* dirname may modify its argument */
360 file_copy = strdup(file);
361 if (file_copy == NULL)
363 fprintf(stderr, "rrdcached: strdup(): %s\n",
364 rrd_strerror(errno));
368 dir = dirname(file_copy);
369 if (rrd_mkdir_p(dir, 0777) != 0)
371 fprintf(stderr, "Failed to create pidfile directory '%s': %s\n",
372 dir, rrd_strerror(errno));
378 fd = open(file, oflag, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH);
380 fprintf(stderr, "rrdcached: can't %s pid file '%s' (%s)\n",
381 action, file, rrd_strerror(errno));
384 } /* }}} static int open_pidfile */
386 /* check existing pid file to see whether a daemon is running */
387 static int check_pidfile(void)
393 pid_fd = open_pidfile("open", O_RDWR);
397 if (read(pid_fd, pid_str, sizeof(pid_str)) <= 0)
404 /* another running process that we can signal COULD be
405 * a competing rrdcached */
406 if (pid != getpid() && kill(pid, 0) == 0)
409 "FATAL: Another rrdcached daemon is running?? (pid %d)\n", pid);
414 lseek(pid_fd, 0, SEEK_SET);
415 if (ftruncate(pid_fd, 0) == -1)
418 "FATAL: Faild to truncate stale PID file. (pid %d)\n", pid);
424 "rrdcached: removed stale PID file (no rrdcached on pid %d)\n"
425 "rrdcached: starting normally.\n", pid);
428 } /* }}} static int check_pidfile */
430 static int write_pidfile (int fd) /* {{{ */
437 fh = fdopen (fd, "w");
440 RRDD_LOG (LOG_ERR, "write_pidfile: fdopen() failed.");
445 fprintf (fh, "%i\n", (int) pid);
449 } /* }}} int write_pidfile */
451 static int remove_pidfile (void) /* {{{ */
456 file = (config_pid_file != NULL)
458 : LOCALSTATEDIR "/run/rrdcached.pid";
460 status = unlink (file);
464 } /* }}} int remove_pidfile */
466 static char *next_cmd (listen_socket_t *sock, ssize_t *len) /* {{{ */
470 eol = memchr(sock->rbuf + sock->next_cmd, '\n',
471 sock->next_read - sock->next_cmd);
475 /* no commands left, move remainder back to front of rbuf */
476 memmove(sock->rbuf, sock->rbuf + sock->next_cmd,
477 sock->next_read - sock->next_cmd);
478 sock->next_read -= sock->next_cmd;
485 char *cmd = sock->rbuf + sock->next_cmd;
488 sock->next_cmd = eol - sock->rbuf + 1;
490 if (eol > sock->rbuf && *(eol-1) == '\r')
491 *(--eol) = '\0'; /* handle "\r\n" EOL */
500 } /* }}} char *next_cmd */
502 /* add the characters directly to the write buffer */
503 static int add_to_wbuf(listen_socket_t *sock, char *str, size_t len) /* {{{ */
507 assert(sock != NULL);
509 new_buf = rrd_realloc(sock->wbuf, sock->wbuf_len + len + 1);
512 RRDD_LOG(LOG_ERR, "add_to_wbuf: realloc failed");
516 strncpy(new_buf + sock->wbuf_len, str, len + 1);
518 sock->wbuf = new_buf;
519 sock->wbuf_len += len;
522 } /* }}} static int add_to_wbuf */
524 /* add the text to the "extra" info that's sent after the status line */
525 static int add_response_info(listen_socket_t *sock, char *fmt, ...) /* {{{ */
528 char buffer[CMD_MAX];
531 if (sock == NULL) return 0; /* journal replay mode */
532 if (sock->batch_start) return 0; /* no extra info returned when in BATCH */
535 #ifdef HAVE_VSNPRINTF
536 len = vsnprintf(buffer, sizeof(buffer), fmt, argp);
538 len = vsprintf(buffer, fmt, argp);
543 RRDD_LOG(LOG_ERR, "add_response_info: vnsprintf failed");
547 return add_to_wbuf(sock, buffer, len);
548 } /* }}} static int add_response_info */
550 static int count_lines(char *str) /* {{{ */
556 while ((str = strchr(str, '\n')) != NULL)
564 } /* }}} static int count_lines */
566 /* send the response back to the user.
567 * returns 0 on success, -1 on error
568 * write buffer is always zeroed after this call */
569 static int send_response (listen_socket_t *sock, response_code rc,
570 char *fmt, ...) /* {{{ */
573 char buffer[CMD_MAX];
578 if (sock == NULL) return rc; /* journal replay mode */
580 if (sock->batch_start)
583 return rc; /* no response on success during BATCH */
584 lines = sock->batch_cmd;
586 else if (rc == RESP_OK)
587 lines = count_lines(sock->wbuf);
591 rclen = sprintf(buffer, "%d ", lines);
593 #ifdef HAVE_VSNPRINTF
594 len = vsnprintf(buffer+rclen, sizeof(buffer)-rclen, fmt, argp);
596 len = vsprintf(buffer+rclen, fmt, argp);
604 /* append the result to the wbuf, don't write to the user */
605 if (sock->batch_start)
606 return add_to_wbuf(sock, buffer, len);
608 /* first write must be complete */
609 if (len != write(sock->fd, buffer, len))
611 RRDD_LOG(LOG_INFO, "send_response: could not write status message");
615 if (sock->wbuf != NULL && rc == RESP_OK)
618 while (wrote < sock->wbuf_len)
620 ssize_t wb = write(sock->fd, sock->wbuf + wrote, sock->wbuf_len - wrote);
623 RRDD_LOG(LOG_INFO, "send_response: could not write results");
630 free(sock->wbuf); sock->wbuf = NULL;
636 static void wipe_ci_values(cache_item_t *ci, time_t when)
641 ci->last_flush_time = when;
642 if (config_write_jitter > 0)
643 ci->last_flush_time += (rrd_random() % config_write_jitter);
647 * remove a "cache_item_t" item from the queue.
648 * must hold 'cache_lock' when calling this
650 static void remove_from_queue(cache_item_t *ci) /* {{{ */
652 if (ci == NULL) return;
653 if ((ci->flags & CI_FLAGS_IN_QUEUE) == 0) return; /* not queued */
655 if (ci->prev == NULL)
656 cache_queue_head = ci->next; /* reset head */
658 ci->prev->next = ci->next;
660 if (ci->next == NULL)
661 cache_queue_tail = ci->prev; /* reset the tail */
663 ci->next->prev = ci->prev;
665 ci->next = ci->prev = NULL;
666 ci->flags &= ~CI_FLAGS_IN_QUEUE;
668 pthread_mutex_lock (&stats_lock);
669 assert (stats_queue_length > 0);
670 stats_queue_length--;
671 pthread_mutex_unlock (&stats_lock);
673 } /* }}} static void remove_from_queue */
675 /* free the resources associated with the cache_item_t
676 * must hold cache_lock when calling this function
678 static void *free_cache_item(cache_item_t *ci) /* {{{ */
680 if (ci == NULL) return NULL;
682 remove_from_queue(ci);
684 for (size_t i=0; i < ci->values_num; i++)
690 /* in case anyone is waiting */
691 pthread_cond_broadcast(&ci->flushed);
692 pthread_cond_destroy(&ci->flushed);
697 } /* }}} static void *free_cache_item */
700 * enqueue_cache_item:
701 * `cache_lock' must be acquired before calling this function!
703 static int enqueue_cache_item (cache_item_t *ci, /* {{{ */
709 if (ci->values_num == 0)
714 if (cache_queue_head == ci)
717 /* remove if further down in queue */
718 remove_from_queue(ci);
721 ci->next = cache_queue_head;
722 if (ci->next != NULL)
724 cache_queue_head = ci;
726 if (cache_queue_tail == NULL)
727 cache_queue_tail = cache_queue_head;
729 else /* (side == TAIL) */
731 /* We don't move values back in the list.. */
732 if (ci->flags & CI_FLAGS_IN_QUEUE)
735 assert (ci->next == NULL);
736 assert (ci->prev == NULL);
738 ci->prev = cache_queue_tail;
740 if (cache_queue_tail == NULL)
741 cache_queue_head = ci;
743 cache_queue_tail->next = ci;
745 cache_queue_tail = ci;
748 ci->flags |= CI_FLAGS_IN_QUEUE;
750 pthread_cond_signal(&queue_cond);
751 pthread_mutex_lock (&stats_lock);
752 stats_queue_length++;
753 pthread_mutex_unlock (&stats_lock);
756 } /* }}} int enqueue_cache_item */
759 * tree_callback_flush:
760 * Called via `g_tree_foreach' in `flush_thread_main'. `cache_lock' is held
761 * while this is in progress.
763 static gboolean tree_callback_flush (gpointer key, gpointer value, /* {{{ */
767 callback_flush_data_t *cfd;
769 ci = (cache_item_t *) value;
770 cfd = (callback_flush_data_t *) data;
772 if (ci->flags & CI_FLAGS_IN_QUEUE)
775 if (ci->values_num > 0
776 && (ci->last_flush_time <= cfd->abs_timeout || state != RUNNING))
778 enqueue_cache_item (ci, TAIL);
780 else if (((cfd->now - ci->last_flush_time) >= config_flush_interval)
781 && (ci->values_num <= 0))
783 assert ((char *) key == ci->file);
784 if (!rrd_add_ptr((void ***)&cfd->keys, &cfd->keys_num, (void *)key))
786 RRDD_LOG (LOG_ERR, "tree_callback_flush: rrd_add_ptrs failed.");
792 } /* }}} gboolean tree_callback_flush */
794 static int flush_old_values (int max_age)
796 callback_flush_data_t cfd;
799 memset (&cfd, 0, sizeof (cfd));
800 /* Pass the current time as user data so that we don't need to call
801 * `time' for each node. */
802 cfd.now = time (NULL);
807 cfd.abs_timeout = cfd.now - max_age;
809 cfd.abs_timeout = cfd.now + 2*config_write_jitter + 1;
811 /* `tree_callback_flush' will return the keys of all values that haven't
812 * been touched in the last `config_flush_interval' seconds in `cfd'.
813 * The char*'s in this array point to the same memory as ci->file, so we
814 * don't need to free them separately. */
815 g_tree_foreach (cache_tree, tree_callback_flush, (gpointer) &cfd);
817 for (k = 0; k < cfd.keys_num; k++)
819 /* should never fail, since we have held the cache_lock
821 assert( g_tree_remove(cache_tree, cfd.keys[k]) == TRUE );
824 if (cfd.keys != NULL)
831 } /* int flush_old_values */
833 static void *flush_thread_main (void *args __attribute__((unused))) /* {{{ */
836 struct timespec next_flush;
839 gettimeofday (&now, NULL);
840 next_flush.tv_sec = now.tv_sec + config_flush_interval;
841 next_flush.tv_nsec = 1000 * now.tv_usec;
843 pthread_mutex_lock(&cache_lock);
845 while (state == RUNNING)
847 gettimeofday (&now, NULL);
848 if ((now.tv_sec > next_flush.tv_sec)
849 || ((now.tv_sec == next_flush.tv_sec)
850 && ((1000 * now.tv_usec) > next_flush.tv_nsec)))
852 RRDD_LOG(LOG_DEBUG, "flushing old values");
854 /* Determine the time of the next cache flush. */
855 next_flush.tv_sec = now.tv_sec + config_flush_interval;
857 /* Flush all values that haven't been written in the last
858 * `config_write_interval' seconds. */
859 flush_old_values (config_write_interval);
861 /* unlock the cache while we rotate so we don't block incoming
862 * updates if the fsync() blocks on disk I/O */
863 pthread_mutex_unlock(&cache_lock);
865 pthread_mutex_lock(&cache_lock);
868 status = pthread_cond_timedwait(&flush_cond, &cache_lock, &next_flush);
869 if (status != 0 && status != ETIMEDOUT)
871 RRDD_LOG (LOG_ERR, "flush_thread_main: "
872 "pthread_cond_timedwait returned %i.", status);
876 if (config_flush_at_shutdown)
877 flush_old_values (-1); /* flush everything */
881 pthread_mutex_unlock(&cache_lock);
884 } /* void *flush_thread_main */
886 static void *queue_thread_main (void *args __attribute__((unused))) /* {{{ */
888 pthread_mutex_lock (&cache_lock);
890 while (state != SHUTDOWN
891 || (cache_queue_head != NULL && config_flush_at_shutdown))
899 /* Now, check if there's something to store away. If not, wait until
900 * something comes in. */
901 if (cache_queue_head == NULL)
903 status = pthread_cond_wait (&queue_cond, &cache_lock);
904 if ((status != 0) && (status != ETIMEDOUT))
906 RRDD_LOG (LOG_ERR, "queue_thread_main: "
907 "pthread_cond_wait returned %i.", status);
911 /* Check if a value has arrived. This may be NULL if we timed out or there
912 * was an interrupt such as a signal. */
913 if (cache_queue_head == NULL)
916 ci = cache_queue_head;
918 /* copy the relevant parts */
919 file = strdup (ci->file);
922 RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
926 assert(ci->values != NULL);
927 assert(ci->values_num > 0);
930 values_num = ci->values_num;
932 wipe_ci_values(ci, time(NULL));
933 remove_from_queue(ci);
935 pthread_mutex_unlock (&cache_lock);
938 status = rrd_update_r (file, NULL, (int) values_num, (void *) values);
941 RRDD_LOG (LOG_NOTICE, "queue_thread_main: "
942 "rrd_update_r (%s) failed with status %i. (%s)",
943 file, status, rrd_get_error());
946 journal_write("wrote", file);
948 /* Search again in the tree. It's possible someone issued a "FORGET"
949 * while we were writing the update values. */
950 pthread_mutex_lock(&cache_lock);
951 ci = (cache_item_t *) g_tree_lookup(cache_tree, file);
953 pthread_cond_broadcast(&ci->flushed);
954 pthread_mutex_unlock(&cache_lock);
958 pthread_mutex_lock (&stats_lock);
959 stats_updates_written++;
960 stats_data_sets_written += values_num;
961 pthread_mutex_unlock (&stats_lock);
964 rrd_free_ptrs((void ***) &values, &values_num);
967 pthread_mutex_lock (&cache_lock);
969 pthread_mutex_unlock (&cache_lock);
972 } /* }}} void *queue_thread_main */
974 static int buffer_get_field (char **buffer_ret, /* {{{ */
975 size_t *buffer_size_ret, char **field_ret)
984 buffer = *buffer_ret;
986 buffer_size = *buffer_size_ret;
990 if (buffer_size <= 0)
993 /* This is ensured by `handle_request'. */
994 assert (buffer[buffer_size - 1] == '\0');
997 while (buffer_pos < buffer_size)
999 /* Check for end-of-field or end-of-buffer */
1000 if (buffer[buffer_pos] == ' ' || buffer[buffer_pos] == '\0')
1002 field[field_size] = 0;
1008 /* Handle escaped characters. */
1009 else if (buffer[buffer_pos] == '\\')
1011 if (buffer_pos >= (buffer_size - 1))
1014 field[field_size] = buffer[buffer_pos];
1018 /* Normal operation */
1021 field[field_size] = buffer[buffer_pos];
1025 } /* while (buffer_pos < buffer_size) */
1030 *buffer_ret = buffer + buffer_pos;
1031 *buffer_size_ret = buffer_size - buffer_pos;
1035 } /* }}} int buffer_get_field */
1037 /* if we're restricting writes to the base directory,
1038 * check whether the file falls within the dir
1039 * returns 1 if OK, otherwise 0
1041 static int check_file_access (const char *file, listen_socket_t *sock) /* {{{ */
1043 assert(file != NULL);
1045 if (!config_write_base_only
1046 || sock == NULL /* journal replay */
1047 || config_base_dir == NULL)
1050 if (strstr(file, "../") != NULL) goto err;
1052 /* relative paths without "../" are ok */
1053 if (*file != '/') return 1;
1055 /* file must be of the format base + "/" + <1+ char filename> */
1056 if (strlen(file) < _config_base_dir_len + 2) goto err;
1057 if (strncmp(file, config_base_dir, _config_base_dir_len) != 0) goto err;
1058 if (*(file + _config_base_dir_len) != '/') goto err;
1063 if (sock != NULL && sock->fd >= 0)
1064 send_response(sock, RESP_ERR, "%s\n", rrd_strerror(EACCES));
1067 } /* }}} static int check_file_access */
1069 /* when using a base dir, convert relative paths to absolute paths.
1070 * if necessary, modifies the "filename" pointer to point
1071 * to the new path created in "tmp". "tmp" is provided
1072 * by the caller and sizeof(tmp) must be >= PATH_MAX.
1074 * this allows us to optimize for the expected case (absolute path)
1077 static void get_abs_path(char **filename, char *tmp)
1079 assert(tmp != NULL);
1080 assert(filename != NULL && *filename != NULL);
1082 if (config_base_dir == NULL || **filename == '/')
1085 snprintf(tmp, PATH_MAX, "%s/%s", config_base_dir, *filename);
1087 } /* }}} static int get_abs_path */
1089 static int flush_file (const char *filename) /* {{{ */
1093 pthread_mutex_lock (&cache_lock);
1095 ci = (cache_item_t *) g_tree_lookup (cache_tree, filename);
1098 pthread_mutex_unlock (&cache_lock);
1102 if (ci->values_num > 0)
1104 /* Enqueue at head */
1105 enqueue_cache_item (ci, HEAD);
1106 pthread_cond_wait(&ci->flushed, &cache_lock);
1109 /* DO NOT DO ANYTHING WITH ci HERE!! The entry
1110 * may have been purged during our cond_wait() */
1112 pthread_mutex_unlock(&cache_lock);
1115 } /* }}} int flush_file */
1117 static int syntax_error(listen_socket_t *sock, command_t *cmd) /* {{{ */
1119 char *err = "Syntax error.\n";
1121 if (cmd && cmd->syntax)
1124 return send_response(sock, RESP_ERR, "Usage: %s", err);
1125 } /* }}} static int syntax_error() */
1127 static int handle_request_stats (HANDLER_PROTO) /* {{{ */
1129 uint64_t copy_queue_length;
1130 uint64_t copy_updates_received;
1131 uint64_t copy_flush_received;
1132 uint64_t copy_updates_written;
1133 uint64_t copy_data_sets_written;
1134 uint64_t copy_journal_bytes;
1135 uint64_t copy_journal_rotate;
1137 uint64_t tree_nodes_number;
1138 uint64_t tree_depth;
1140 pthread_mutex_lock (&stats_lock);
1141 copy_queue_length = stats_queue_length;
1142 copy_updates_received = stats_updates_received;
1143 copy_flush_received = stats_flush_received;
1144 copy_updates_written = stats_updates_written;
1145 copy_data_sets_written = stats_data_sets_written;
1146 copy_journal_bytes = stats_journal_bytes;
1147 copy_journal_rotate = stats_journal_rotate;
1148 pthread_mutex_unlock (&stats_lock);
1150 pthread_mutex_lock (&cache_lock);
1151 tree_nodes_number = (uint64_t) g_tree_nnodes (cache_tree);
1152 tree_depth = (uint64_t) g_tree_height (cache_tree);
1153 pthread_mutex_unlock (&cache_lock);
1155 add_response_info(sock,
1156 "QueueLength: %"PRIu64"\n", copy_queue_length);
1157 add_response_info(sock,
1158 "UpdatesReceived: %"PRIu64"\n", copy_updates_received);
1159 add_response_info(sock,
1160 "FlushesReceived: %"PRIu64"\n", copy_flush_received);
1161 add_response_info(sock,
1162 "UpdatesWritten: %"PRIu64"\n", copy_updates_written);
1163 add_response_info(sock,
1164 "DataSetsWritten: %"PRIu64"\n", copy_data_sets_written);
1165 add_response_info(sock, "TreeNodesNumber: %"PRIu64"\n", tree_nodes_number);
1166 add_response_info(sock, "TreeDepth: %"PRIu64"\n", tree_depth);
1167 add_response_info(sock, "JournalBytes: %"PRIu64"\n", copy_journal_bytes);
1168 add_response_info(sock, "JournalRotate: %"PRIu64"\n", copy_journal_rotate);
1170 send_response(sock, RESP_OK, "Statistics follow\n");
1173 } /* }}} int handle_request_stats */
1175 static int handle_request_flush (HANDLER_PROTO) /* {{{ */
1177 char *file, file_tmp[PATH_MAX];
1180 status = buffer_get_field (&buffer, &buffer_size, &file);
1183 return syntax_error(sock,cmd);
1187 pthread_mutex_lock(&stats_lock);
1188 stats_flush_received++;
1189 pthread_mutex_unlock(&stats_lock);
1191 get_abs_path(&file, file_tmp);
1192 if (!check_file_access(file, sock)) return 0;
1194 status = flush_file (file);
1196 return send_response(sock, RESP_OK, "Successfully flushed %s.\n", file);
1197 else if (status == ENOENT)
1199 /* no file in our tree; see whether it exists at all */
1200 struct stat statbuf;
1202 memset(&statbuf, 0, sizeof(statbuf));
1203 if (stat(file, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
1204 return send_response(sock, RESP_OK, "Nothing to flush: %s.\n", file);
1206 return send_response(sock, RESP_ERR, "No such file: %s.\n", file);
1208 else if (status < 0)
1209 return send_response(sock, RESP_ERR, "Internal error.\n");
1211 return send_response(sock, RESP_ERR, "Failed with status %i.\n", status);
1216 } /* }}} int handle_request_flush */
1218 static int handle_request_flushall(HANDLER_PROTO) /* {{{ */
1220 RRDD_LOG(LOG_DEBUG, "Received FLUSHALL");
1222 pthread_mutex_lock(&cache_lock);
1223 flush_old_values(-1);
1224 pthread_mutex_unlock(&cache_lock);
1226 return send_response(sock, RESP_OK, "Started flush.\n");
1227 } /* }}} static int handle_request_flushall */
1229 static int handle_request_pending(HANDLER_PROTO) /* {{{ */
1232 char *file, file_tmp[PATH_MAX];
1235 status = buffer_get_field(&buffer, &buffer_size, &file);
1237 return syntax_error(sock,cmd);
1239 get_abs_path(&file, file_tmp);
1241 pthread_mutex_lock(&cache_lock);
1242 ci = g_tree_lookup(cache_tree, file);
1245 pthread_mutex_unlock(&cache_lock);
1246 return send_response(sock, RESP_ERR, "%s\n", rrd_strerror(ENOENT));
1249 for (size_t i=0; i < ci->values_num; i++)
1250 add_response_info(sock, "%s\n", ci->values[i]);
1252 pthread_mutex_unlock(&cache_lock);
1253 return send_response(sock, RESP_OK, "updates pending\n");
1254 } /* }}} static int handle_request_pending */
1256 static int handle_request_forget(HANDLER_PROTO) /* {{{ */
1260 char *file, file_tmp[PATH_MAX];
1262 status = buffer_get_field(&buffer, &buffer_size, &file);
1264 return syntax_error(sock,cmd);
1266 get_abs_path(&file, file_tmp);
1267 if (!check_file_access(file, sock)) return 0;
1269 pthread_mutex_lock(&cache_lock);
1270 found = g_tree_remove(cache_tree, file);
1271 pthread_mutex_unlock(&cache_lock);
1276 journal_write("forget", file);
1278 return send_response(sock, RESP_OK, "Gone!\n");
1281 return send_response(sock, RESP_ERR, "%s\n", rrd_strerror(ENOENT));
1285 } /* }}} static int handle_request_forget */
1287 static int handle_request_queue (HANDLER_PROTO) /* {{{ */
1291 pthread_mutex_lock(&cache_lock);
1293 ci = cache_queue_head;
1296 add_response_info(sock, "%d %s\n", ci->values_num, ci->file);
1300 pthread_mutex_unlock(&cache_lock);
1302 return send_response(sock, RESP_OK, "in queue.\n");
1303 } /* }}} int handle_request_queue */
1305 static int handle_request_update (HANDLER_PROTO) /* {{{ */
1307 char *file, file_tmp[PATH_MAX];
1310 char orig_buf[CMD_MAX];
1314 /* save it for the journal later */
1315 strncpy(orig_buf, buffer, sizeof(orig_buf)-1);
1317 status = buffer_get_field (&buffer, &buffer_size, &file);
1319 return syntax_error(sock,cmd);
1321 pthread_mutex_lock(&stats_lock);
1322 stats_updates_received++;
1323 pthread_mutex_unlock(&stats_lock);
1325 get_abs_path(&file, file_tmp);
1326 if (!check_file_access(file, sock)) return 0;
1328 pthread_mutex_lock (&cache_lock);
1329 ci = g_tree_lookup (cache_tree, file);
1331 if (ci == NULL) /* {{{ */
1333 struct stat statbuf;
1336 /* don't hold the lock while we setup; stat(2) might block */
1337 pthread_mutex_unlock(&cache_lock);
1339 memset (&statbuf, 0, sizeof (statbuf));
1340 status = stat (file, &statbuf);
1343 RRDD_LOG (LOG_NOTICE, "handle_request_update: stat (%s) failed.", file);
1346 if (status == ENOENT)
1347 return send_response(sock, RESP_ERR, "No such file: %s\n", file);
1349 return send_response(sock, RESP_ERR,
1350 "stat failed with error %i.\n", status);
1352 if (!S_ISREG (statbuf.st_mode))
1353 return send_response(sock, RESP_ERR, "Not a regular file: %s\n", file);
1355 if (access(file, R_OK|W_OK) != 0)
1356 return send_response(sock, RESP_ERR, "Cannot read/write %s: %s\n",
1357 file, rrd_strerror(errno));
1359 ci = (cache_item_t *) malloc (sizeof (cache_item_t));
1362 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
1364 return send_response(sock, RESP_ERR, "malloc failed.\n");
1366 memset (ci, 0, sizeof (cache_item_t));
1368 ci->file = strdup (file);
1369 if (ci->file == NULL)
1372 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
1374 return send_response(sock, RESP_ERR, "strdup failed.\n");
1377 wipe_ci_values(ci, now);
1378 ci->flags = CI_FLAGS_IN_TREE;
1379 pthread_cond_init(&ci->flushed, NULL);
1381 pthread_mutex_lock(&cache_lock);
1383 /* another UPDATE might have added this entry in the meantime */
1384 tmp = g_tree_lookup (cache_tree, file);
1386 g_tree_replace (cache_tree, (void *) ci->file, (void *) ci);
1389 free_cache_item (ci);
1393 /* state may have changed while we were unlocked */
1394 if (state == SHUTDOWN)
1397 assert (ci != NULL);
1399 /* don't re-write updates in replay mode */
1401 journal_write("update", orig_buf);
1403 while (buffer_size > 0)
1409 status = buffer_get_field (&buffer, &buffer_size, &value);
1412 RRDD_LOG (LOG_INFO, "handle_request_update: Error reading field.");
1416 /* make sure update time is always moving forward */
1417 stamp = strtol(value, &eostamp, 10);
1418 if (eostamp == value || eostamp == NULL || *eostamp != ':')
1420 pthread_mutex_unlock(&cache_lock);
1421 return send_response(sock, RESP_ERR,
1422 "Cannot find timestamp in '%s'!\n", value);
1424 else if (stamp <= ci->last_update_stamp)
1426 pthread_mutex_unlock(&cache_lock);
1427 return send_response(sock, RESP_ERR,
1428 "illegal attempt to update using time %ld when last"
1429 " update time is %ld (minimum one second step)\n",
1430 stamp, ci->last_update_stamp);
1433 ci->last_update_stamp = stamp;
1435 if (!rrd_add_strdup(&ci->values, &ci->values_num, value))
1437 RRDD_LOG (LOG_ERR, "handle_request_update: rrd_add_strdup failed.");
1444 if (((now - ci->last_flush_time) >= config_write_interval)
1445 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
1446 && (ci->values_num > 0))
1448 enqueue_cache_item (ci, TAIL);
1451 pthread_mutex_unlock (&cache_lock);
1454 return send_response(sock, RESP_ERR, "No values updated.\n");
1456 return send_response(sock, RESP_OK,
1457 "errors, enqueued %i value(s).\n", values_num);
1462 } /* }}} int handle_request_update */
1464 /* we came across a "WROTE" entry during journal replay.
1465 * throw away any values that we have accumulated for this file
1467 static int handle_request_wrote (HANDLER_PROTO) /* {{{ */
1470 const char *file = buffer;
1472 pthread_mutex_lock(&cache_lock);
1474 ci = g_tree_lookup(cache_tree, file);
1477 pthread_mutex_unlock(&cache_lock);
1482 rrd_free_ptrs((void ***) &ci->values, &ci->values_num);
1484 wipe_ci_values(ci, now);
1485 remove_from_queue(ci);
1487 pthread_mutex_unlock(&cache_lock);
1489 } /* }}} int handle_request_wrote */
1491 /* start "BATCH" processing */
1492 static int batch_start (HANDLER_PROTO) /* {{{ */
1495 if (sock->batch_start)
1496 return send_response(sock, RESP_ERR, "Already in BATCH\n");
1498 status = send_response(sock, RESP_OK,
1499 "Go ahead. End with dot '.' on its own line.\n");
1500 sock->batch_start = time(NULL);
1501 sock->batch_cmd = 0;
1504 } /* }}} static int batch_start */
1506 /* finish "BATCH" processing and return results to the client */
1507 static int batch_done (HANDLER_PROTO) /* {{{ */
1509 assert(sock->batch_start);
1510 sock->batch_start = 0;
1511 sock->batch_cmd = 0;
1512 return send_response(sock, RESP_OK, "errors\n");
1513 } /* }}} static int batch_done */
1515 static int handle_request_quit (HANDLER_PROTO) /* {{{ */
1518 } /* }}} static int handle_request_quit */
1520 static command_t list_of_commands[] = { /* {{{ */
1523 handle_request_update,
1525 "UPDATE <filename> <values> [<values> ...]\n"
1527 "Adds the given file to the internal cache if it is not yet known and\n"
1528 "appends the given value(s) to the entry. See the rrdcached(1) manpage\n"
1531 "Each <values> has the following form:\n"
1532 " <values> = <time>:<value>[:<value>[...]]\n"
1533 "See the rrdupdate(1) manpage for details.\n"
1537 handle_request_wrote,
1538 CMD_CONTEXT_JOURNAL,
1544 handle_request_flush,
1545 CMD_CONTEXT_CLIENT | CMD_CONTEXT_BATCH,
1546 "FLUSH <filename>\n"
1548 "Adds the given filename to the head of the update queue and returns\n"
1549 "after it has been dequeued.\n"
1553 handle_request_flushall,
1557 "Triggers writing of all pending updates. Returns immediately.\n"
1561 handle_request_pending,
1563 "PENDING <filename>\n"
1565 "Shows any 'pending' updates for a file, in order.\n"
1566 "The updates shown have not yet been written to the underlying RRD file.\n"
1570 handle_request_forget,
1572 "FORGET <filename>\n"
1574 "Removes the file completely from the cache.\n"
1575 "Any pending updates for the file will be lost.\n"
1579 handle_request_queue,
1583 "Shows all files in the output queue.\n"
1584 "The output is zero or more lines in the following format:\n"
1585 "(where <num_vals> is the number of values to be written)\n"
1587 "<num_vals> <filename>\n"
1591 handle_request_stats,
1595 "Returns some performance counters, see the rrdcached(1) manpage for\n"
1596 "a description of the values.\n"
1600 handle_request_help,
1602 "HELP [<command>]\n",
1603 NULL, /* special! */
1611 "The 'BATCH' command permits the client to initiate a bulk load\n"
1612 " of commands to rrdcached.\n"
1617 " server: 0 Go ahead. End with dot '.' on its own line.\n"
1618 " client: command #1\n"
1619 " client: command #2\n"
1620 " client: ... and so on\n"
1622 " server: 2 errors\n"
1623 " server: 7 message for command #7\n"
1624 " server: 9 message for command #9\n"
1626 "For more information, consult the rrdcached(1) documentation.\n"
1629 ".", /* BATCH terminator */
1637 handle_request_quit,
1638 CMD_CONTEXT_CLIENT | CMD_CONTEXT_BATCH,
1641 "Disconnect from rrdcached.\n"
1643 }; /* }}} command_t list_of_commands[] */
1644 static size_t list_of_commands_len = sizeof (list_of_commands)
1645 / sizeof (list_of_commands[0]);
1647 static command_t *find_command(char *cmd)
1651 for (i = 0; i < list_of_commands_len; i++)
1652 if (strcasecmp(cmd, list_of_commands[i].cmd) == 0)
1653 return (&list_of_commands[i]);
1657 /* We currently use the index in the `list_of_commands' array as a bit position
1658 * in `listen_socket_t.permissions'. This member schould NEVER be accessed from
1659 * outside these functions so that switching to a more elegant storage method
1660 * is easily possible. */
1661 static ssize_t find_command_index (const char *cmd) /* {{{ */
1665 for (i = 0; i < list_of_commands_len; i++)
1666 if (strcasecmp(cmd, list_of_commands[i].cmd) == 0)
1667 return ((ssize_t) i);
1669 } /* }}} ssize_t find_command_index */
1671 static int socket_permission_check (listen_socket_t *sock, /* {{{ */
1676 if (sock == NULL) /* journal replay */
1682 if ((strcasecmp ("QUIT", cmd) == 0)
1683 || (strcasecmp ("HELP", cmd) == 0))
1685 else if (strcmp (".", cmd) == 0)
1688 i = find_command_index (cmd);
1693 if ((sock->permissions & (1 << i)) != 0)
1696 } /* }}} int socket_permission_check */
1698 static int socket_permission_add (listen_socket_t *sock, /* {{{ */
1703 i = find_command_index (cmd);
1708 sock->permissions |= (1 << i);
1710 } /* }}} int socket_permission_add */
1712 /* check whether commands are received in the expected context */
1713 static int command_check_context(listen_socket_t *sock, command_t *cmd)
1716 return (cmd->context & CMD_CONTEXT_JOURNAL);
1717 else if (sock->batch_start)
1718 return (cmd->context & CMD_CONTEXT_BATCH);
1720 return (cmd->context & CMD_CONTEXT_CLIENT);
1726 static int handle_request_help (HANDLER_PROTO) /* {{{ */
1731 command_t *help = NULL;
1733 status = buffer_get_field (&buffer, &buffer_size, &cmd_str);
1735 help = find_command(cmd_str);
1737 if (help && (help->syntax || help->help))
1741 snprintf(tmp, sizeof(tmp)-1, "Help for %s\n", help->cmd);
1745 add_response_info(sock, "Usage: %s\n", help->syntax);
1748 add_response_info(sock, "%s\n", help->help);
1754 resp_txt = "Command overview\n";
1756 for (i = 0; i < list_of_commands_len; i++)
1758 if (list_of_commands[i].syntax == NULL)
1760 add_response_info (sock, "%s", list_of_commands[i].syntax);
1764 return send_response(sock, RESP_OK, resp_txt);
1765 } /* }}} int handle_request_help */
1767 /* if sock==NULL, we are in journal replay mode */
1768 static int handle_request (DISPATCH_PROTO) /* {{{ */
1770 char *buffer_ptr = buffer;
1771 char *cmd_str = NULL;
1772 command_t *cmd = NULL;
1775 assert (buffer[buffer_size - 1] == '\0');
1777 status = buffer_get_field (&buffer_ptr, &buffer_size, &cmd_str);
1780 RRDD_LOG (LOG_INFO, "handle_request: Unable parse command.");
1784 if (sock != NULL && sock->batch_start)
1787 cmd = find_command(cmd_str);
1789 return send_response(sock, RESP_ERR, "Unknown command: %s\n", cmd_str);
1791 if (!socket_permission_check (sock, cmd->cmd))
1792 return send_response(sock, RESP_ERR, "Permission denied.\n");
1794 if (!command_check_context(sock, cmd))
1795 return send_response(sock, RESP_ERR, "Can't use '%s' here.\n", cmd_str);
1797 return cmd->handler(cmd, sock, now, buffer_ptr, buffer_size);
1798 } /* }}} int handle_request */
1800 static void journal_set_free (journal_set *js) /* {{{ */
1805 rrd_free_ptrs((void ***) &js->files, &js->files_num);
1808 } /* }}} journal_set_free */
1810 static void journal_set_remove (journal_set *js) /* {{{ */
1815 for (uint i=0; i < js->files_num; i++)
1817 RRDD_LOG(LOG_DEBUG, "removing old journal %s", js->files[i]);
1818 unlink(js->files[i]);
1820 } /* }}} journal_set_remove */
1822 /* close current journal file handle.
1823 * MUST hold journal_lock before calling */
1824 static void journal_close(void) /* {{{ */
1826 if (journal_fh != NULL)
1828 if (fclose(journal_fh) != 0)
1829 RRDD_LOG(LOG_ERR, "cannot close journal: %s", rrd_strerror(errno));
1834 } /* }}} journal_close */
1836 /* MUST hold journal_lock before calling */
1837 static void journal_new_file(void) /* {{{ */
1841 char new_file[PATH_MAX + 1];
1843 assert(journal_dir != NULL);
1844 assert(journal_cur != NULL);
1848 gettimeofday(&now, NULL);
1849 /* this format assures that the files sort in strcmp() order */
1850 snprintf(new_file, PATH_MAX, "%s/%s.%010d.%06d",
1851 journal_dir, JOURNAL_BASE, (int)now.tv_sec, (int)now.tv_usec);
1853 new_fd = open(new_file, O_WRONLY|O_CREAT|O_APPEND,
1854 S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
1858 journal_fh = fdopen(new_fd, "a");
1859 if (journal_fh == NULL)
1862 journal_size = ftell(journal_fh);
1863 RRDD_LOG(LOG_DEBUG, "started new journal %s", new_file);
1865 /* record the file in the journal set */
1866 rrd_add_strdup(&journal_cur->files, &journal_cur->files_num, new_file);
1872 "JOURNALING DISABLED: Error while trying to create %s : %s",
1873 new_file, rrd_strerror(errno));
1875 "JOURNALING DISABLED: All values will be flushed at shutdown");
1878 config_flush_at_shutdown = 1;
1880 } /* }}} journal_new_file */
1882 /* MUST NOT hold journal_lock before calling this */
1883 static void journal_rotate(void) /* {{{ */
1885 journal_set *old_js = NULL;
1887 if (journal_dir == NULL)
1890 RRDD_LOG(LOG_DEBUG, "rotating journals");
1892 pthread_mutex_lock(&stats_lock);
1893 ++stats_journal_rotate;
1894 pthread_mutex_unlock(&stats_lock);
1896 pthread_mutex_lock(&journal_lock);
1900 /* rotate the journal sets */
1901 old_js = journal_old;
1902 journal_old = journal_cur;
1903 journal_cur = calloc(1, sizeof(journal_set));
1905 if (journal_cur != NULL)
1908 RRDD_LOG(LOG_CRIT, "journal_rotate: malloc(journal_set) failed\n");
1910 pthread_mutex_unlock(&journal_lock);
1912 journal_set_remove(old_js);
1913 journal_set_free (old_js);
1915 } /* }}} static void journal_rotate */
1917 /* MUST hold journal_lock when calling */
1918 static void journal_done(void) /* {{{ */
1920 if (journal_cur == NULL)
1925 if (config_flush_at_shutdown)
1927 RRDD_LOG(LOG_INFO, "removing journals");
1928 journal_set_remove(journal_old);
1929 journal_set_remove(journal_cur);
1933 RRDD_LOG(LOG_INFO, "expedited shutdown; "
1934 "journals will be used at next startup");
1937 journal_set_free(journal_cur);
1938 journal_set_free(journal_old);
1941 } /* }}} static void journal_done */
1943 static int journal_write(char *cmd, char *args) /* {{{ */
1947 if (journal_fh == NULL)
1950 pthread_mutex_lock(&journal_lock);
1951 chars = fprintf(journal_fh, "%s %s\n", cmd, args);
1952 journal_size += chars;
1954 if (journal_size > JOURNAL_MAX)
1957 pthread_mutex_unlock(&journal_lock);
1961 pthread_mutex_lock(&stats_lock);
1962 stats_journal_bytes += chars;
1963 pthread_mutex_unlock(&stats_lock);
1967 } /* }}} static int journal_write */
1969 static int journal_replay (const char *file) /* {{{ */
1975 char entry[CMD_MAX];
1978 if (file == NULL) return 0;
1981 char *reason = "unknown error";
1983 struct stat statbuf;
1985 memset(&statbuf, 0, sizeof(statbuf));
1986 if (stat(file, &statbuf) != 0)
1988 reason = "stat error";
1991 else if (!S_ISREG(statbuf.st_mode))
1993 reason = "not a regular file";
1996 if (statbuf.st_uid != daemon_uid)
1998 reason = "not owned by daemon user";
2001 if (statbuf.st_mode & (S_IWGRP|S_IWOTH))
2003 reason = "must not be user/group writable";
2009 RRDD_LOG(LOG_ERR, "journal_replay: %s : %s (%s)",
2010 file, rrd_strerror(status), reason);
2015 fh = fopen(file, "r");
2018 if (errno != ENOENT)
2019 RRDD_LOG(LOG_ERR, "journal_replay: cannot open journal file: '%s' (%s)",
2020 file, rrd_strerror(errno));
2024 RRDD_LOG(LOG_NOTICE, "replaying from journal: %s", file);
2033 if (fgets(entry, sizeof(entry), fh) == NULL)
2035 entry_len = strlen(entry);
2037 /* check \n termination in case journal writing crashed mid-line */
2040 else if (entry[entry_len - 1] != '\n')
2042 RRDD_LOG(LOG_NOTICE, "Malformed journal entry at line %"PRIu64, line);
2047 entry[entry_len - 1] = '\0';
2049 if (handle_request(NULL, now, entry, entry_len) == 0)
2057 RRDD_LOG(LOG_INFO, "Replayed %d entries (%d failures)",
2058 entry_cnt, fail_cnt);
2060 return entry_cnt > 0 ? 1 : 0;
2061 } /* }}} static int journal_replay */
2063 static int journal_sort(const void *v1, const void *v2)
2065 char **jn1 = (char **) v1;
2066 char **jn2 = (char **) v2;
2068 return strcmp(*jn1,*jn2);
2071 static void journal_init(void) /* {{{ */
2073 int had_journal = 0;
2075 struct dirent *dent;
2076 char path[PATH_MAX+1];
2078 if (journal_dir == NULL) return;
2080 pthread_mutex_lock(&journal_lock);
2082 journal_cur = calloc(1, sizeof(journal_set));
2083 if (journal_cur == NULL)
2085 RRDD_LOG(LOG_CRIT, "journal_rotate: malloc(journal_set) failed\n");
2089 RRDD_LOG(LOG_INFO, "checking for journal files");
2091 /* Handle old journal files during transition. This gives them the
2092 * correct sort order. TODO: remove after first release
2095 char old_path[PATH_MAX+1];
2096 snprintf(old_path, PATH_MAX, "%s/%s", journal_dir, JOURNAL_BASE ".old" );
2097 snprintf(path, PATH_MAX, "%s/%s", journal_dir, JOURNAL_BASE ".0000");
2098 rename(old_path, path);
2100 snprintf(old_path, PATH_MAX, "%s/%s", journal_dir, JOURNAL_BASE );
2101 snprintf(path, PATH_MAX, "%s/%s", journal_dir, JOURNAL_BASE ".0001");
2102 rename(old_path, path);
2105 dir = opendir(journal_dir);
2106 while ((dent = readdir(dir)) != NULL)
2108 /* looks like a journal file? */
2109 if (strncmp(dent->d_name, JOURNAL_BASE, strlen(JOURNAL_BASE)))
2112 snprintf(path, PATH_MAX, "%s/%s", journal_dir, dent->d_name);
2114 if (!rrd_add_strdup(&journal_cur->files, &journal_cur->files_num, path))
2116 RRDD_LOG(LOG_CRIT, "journal_init: cannot add journal file %s!",
2123 qsort(journal_cur->files, journal_cur->files_num,
2124 sizeof(journal_cur->files[0]), journal_sort);
2126 for (uint i=0; i < journal_cur->files_num; i++)
2127 had_journal += journal_replay(journal_cur->files[i]);
2131 /* it must have been a crash. start a flush */
2132 if (had_journal && config_flush_at_shutdown)
2133 flush_old_values(-1);
2135 pthread_mutex_unlock(&journal_lock);
2137 RRDD_LOG(LOG_INFO, "journal processing complete");
2139 } /* }}} static void journal_init */
2141 static void free_listen_socket(listen_socket_t *sock) /* {{{ */
2143 assert(sock != NULL);
2145 free(sock->rbuf); sock->rbuf = NULL;
2146 free(sock->wbuf); sock->wbuf = NULL;
2148 } /* }}} void free_listen_socket */
2150 static void close_connection(listen_socket_t *sock) /* {{{ */
2158 free_listen_socket(sock);
2160 } /* }}} void close_connection */
2162 static void *connection_thread_main (void *args) /* {{{ */
2164 listen_socket_t *sock;
2167 sock = (listen_socket_t *) args;
2170 /* init read buffers */
2171 sock->next_read = sock->next_cmd = 0;
2172 sock->rbuf = malloc(RBUF_SIZE);
2173 if (sock->rbuf == NULL)
2175 RRDD_LOG(LOG_ERR, "connection_thread_main: cannot malloc read buffer");
2176 close_connection(sock);
2180 pthread_mutex_lock (&connection_threads_lock);
2181 connection_threads_num++;
2182 pthread_mutex_unlock (&connection_threads_lock);
2184 while (state == RUNNING)
2191 struct pollfd pollfd;
2195 pollfd.events = POLLIN | POLLPRI;
2198 status = poll (&pollfd, 1, /* timeout = */ 500);
2199 if (state != RUNNING)
2201 else if (status == 0) /* timeout */
2203 else if (status < 0) /* error */
2206 if (status != EINTR)
2207 RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
2211 if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
2213 else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
2215 RRDD_LOG (LOG_WARNING, "connection_thread_main: "
2216 "poll(2) returned something unexpected: %#04hx",
2221 rbytes = read(fd, sock->rbuf + sock->next_read,
2222 RBUF_SIZE - sock->next_read);
2225 RRDD_LOG(LOG_ERR, "connection_thread_main: read() failed.");
2228 else if (rbytes == 0)
2231 sock->next_read += rbytes;
2233 if (sock->batch_start)
2234 now = sock->batch_start;
2238 while ((cmd = next_cmd(sock, &cmd_len)) != NULL)
2240 status = handle_request (sock, now, cmd, cmd_len+1);
2247 close_connection(sock);
2249 /* Remove this thread from the connection threads list */
2250 pthread_mutex_lock (&connection_threads_lock);
2251 connection_threads_num--;
2252 if (connection_threads_num <= 0)
2253 pthread_cond_broadcast(&connection_threads_done);
2254 pthread_mutex_unlock (&connection_threads_lock);
2257 } /* }}} void *connection_thread_main */
2259 static int open_listen_socket_unix (const listen_socket_t *sock) /* {{{ */
2262 struct sockaddr_un sa;
2263 listen_socket_t *temp;
2266 char *path_copy, *dir;
2269 if (strncmp(path, "unix:", strlen("unix:")) == 0)
2270 path += strlen("unix:");
2272 /* dirname may modify its argument */
2273 path_copy = strdup(path);
2274 if (path_copy == NULL)
2276 fprintf(stderr, "rrdcached: strdup(): %s\n",
2277 rrd_strerror(errno));
2281 dir = dirname(path_copy);
2282 if (rrd_mkdir_p(dir, 0777) != 0)
2284 fprintf(stderr, "Failed to create socket directory '%s': %s\n",
2285 dir, rrd_strerror(errno));
2291 temp = (listen_socket_t *) rrd_realloc (listen_fds,
2292 sizeof (listen_fds[0]) * (listen_fds_num + 1));
2295 fprintf (stderr, "rrdcached: open_listen_socket_unix: realloc failed.\n");
2299 memcpy (listen_fds + listen_fds_num, sock, sizeof (listen_fds[0]));
2301 fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
2304 fprintf (stderr, "rrdcached: unix socket(2) failed: %s\n",
2305 rrd_strerror(errno));
2309 memset (&sa, 0, sizeof (sa));
2310 sa.sun_family = AF_UNIX;
2311 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
2313 /* if we've gotten this far, we own the pid file. any daemon started
2314 * with the same args must not be alive. therefore, ensure that we can
2315 * create the socket...
2319 status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
2322 fprintf (stderr, "rrdcached: bind(%s) failed: %s.\n",
2323 path, rrd_strerror(errno));
2328 status = listen (fd, /* backlog = */ 10);
2331 fprintf (stderr, "rrdcached: listen(%s) failed: %s.\n",
2332 path, rrd_strerror(errno));
2338 listen_fds[listen_fds_num].fd = fd;
2339 listen_fds[listen_fds_num].family = PF_UNIX;
2340 strncpy(listen_fds[listen_fds_num].addr, path,
2341 sizeof (listen_fds[listen_fds_num].addr) - 1);
2345 } /* }}} int open_listen_socket_unix */
2347 static int open_listen_socket_network(const listen_socket_t *sock) /* {{{ */
2349 struct addrinfo ai_hints;
2350 struct addrinfo *ai_res;
2351 struct addrinfo *ai_ptr;
2352 char addr_copy[NI_MAXHOST];
2357 strncpy (addr_copy, sock->addr, sizeof(addr_copy)-1);
2358 addr_copy[sizeof (addr_copy) - 1] = 0;
2361 memset (&ai_hints, 0, sizeof (ai_hints));
2362 ai_hints.ai_flags = 0;
2363 #ifdef AI_ADDRCONFIG
2364 ai_hints.ai_flags |= AI_ADDRCONFIG;
2366 ai_hints.ai_family = AF_UNSPEC;
2367 ai_hints.ai_socktype = SOCK_STREAM;
2370 if (*addr == '[') /* IPv6+port format */
2372 /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
2375 port = strchr (addr, ']');
2378 fprintf (stderr, "rrdcached: Malformed address: %s\n", sock->addr);
2386 else if (*port == 0)
2390 fprintf (stderr, "rrdcached: Garbage after address: %s\n", port);
2393 } /* if (*addr == '[') */
2396 port = rindex(addr, ':');
2404 status = getaddrinfo (addr,
2405 port == NULL ? RRDCACHED_DEFAULT_PORT : port,
2406 &ai_hints, &ai_res);
2409 fprintf (stderr, "rrdcached: getaddrinfo(%s) failed: %s\n",
2410 addr, gai_strerror (status));
2414 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2417 listen_socket_t *temp;
2420 temp = (listen_socket_t *) rrd_realloc (listen_fds,
2421 sizeof (listen_fds[0]) * (listen_fds_num + 1));
2425 "rrdcached: open_listen_socket_network: realloc failed.\n");
2429 memcpy (listen_fds + listen_fds_num, sock, sizeof (listen_fds[0]));
2431 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
2434 fprintf (stderr, "rrdcached: network socket(2) failed: %s.\n",
2435 rrd_strerror(errno));
2439 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
2441 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2444 fprintf (stderr, "rrdcached: bind(%s) failed: %s.\n",
2445 sock->addr, rrd_strerror(errno));
2450 status = listen (fd, /* backlog = */ 10);
2453 fprintf (stderr, "rrdcached: listen(%s) failed: %s\n.",
2454 sock->addr, rrd_strerror(errno));
2456 freeaddrinfo(ai_res);
2460 listen_fds[listen_fds_num].fd = fd;
2461 listen_fds[listen_fds_num].family = ai_ptr->ai_family;
2463 } /* for (ai_ptr) */
2465 freeaddrinfo(ai_res);
2467 } /* }}} static int open_listen_socket_network */
2469 static int open_listen_socket (const listen_socket_t *sock) /* {{{ */
2471 assert(sock != NULL);
2472 assert(sock->addr != NULL);
2474 if (strncmp ("unix:", sock->addr, strlen ("unix:")) == 0
2475 || sock->addr[0] == '/')
2476 return (open_listen_socket_unix(sock));
2478 return (open_listen_socket_network(sock));
2479 } /* }}} int open_listen_socket */
2481 static int close_listen_sockets (void) /* {{{ */
2485 for (i = 0; i < listen_fds_num; i++)
2487 close (listen_fds[i].fd);
2489 if (listen_fds[i].family == PF_UNIX)
2490 unlink(listen_fds[i].addr);
2498 } /* }}} int close_listen_sockets */
2500 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
2502 struct pollfd *pollfds;
2507 if (listen_fds_num < 1)
2509 RRDD_LOG(LOG_ERR, "listen_thread_main: no listen_fds !");
2513 pollfds_num = listen_fds_num;
2514 pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
2515 if (pollfds == NULL)
2517 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
2520 memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
2522 RRDD_LOG(LOG_INFO, "listening for connections");
2524 while (state == RUNNING)
2526 for (i = 0; i < pollfds_num; i++)
2528 pollfds[i].fd = listen_fds[i].fd;
2529 pollfds[i].events = POLLIN | POLLPRI;
2530 pollfds[i].revents = 0;
2533 status = poll (pollfds, pollfds_num, /* timeout = */ 1000);
2534 if (state != RUNNING)
2536 else if (status == 0) /* timeout */
2538 else if (status < 0) /* error */
2541 if (status != EINTR)
2543 RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
2548 for (i = 0; i < pollfds_num; i++)
2550 listen_socket_t *client_sock;
2551 struct sockaddr_storage client_sa;
2552 socklen_t client_sa_size;
2554 pthread_attr_t attr;
2556 if (pollfds[i].revents == 0)
2559 if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
2561 RRDD_LOG (LOG_ERR, "listen_thread_main: "
2562 "poll(2) returned something unexpected for listen FD #%i.",
2567 client_sock = (listen_socket_t *) malloc (sizeof (listen_socket_t));
2568 if (client_sock == NULL)
2570 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
2573 memcpy(client_sock, &listen_fds[i], sizeof(listen_fds[0]));
2575 client_sa_size = sizeof (client_sa);
2576 client_sock->fd = accept (pollfds[i].fd,
2577 (struct sockaddr *) &client_sa, &client_sa_size);
2578 if (client_sock->fd < 0)
2580 RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
2585 pthread_attr_init (&attr);
2586 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
2588 status = pthread_create (&tid, &attr, connection_thread_main,
2592 RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
2593 close_connection(client_sock);
2596 } /* for (pollfds_num) */
2597 } /* while (state == RUNNING) */
2599 RRDD_LOG(LOG_INFO, "starting shutdown");
2601 close_listen_sockets ();
2603 pthread_mutex_lock (&connection_threads_lock);
2604 while (connection_threads_num > 0)
2605 pthread_cond_wait(&connection_threads_done, &connection_threads_lock);
2606 pthread_mutex_unlock (&connection_threads_lock);
2611 } /* }}} void *listen_thread_main */
2613 static int daemonize (void) /* {{{ */
2618 daemon_uid = geteuid();
2620 pid_fd = open_pidfile("create", O_CREAT|O_EXCL|O_WRONLY);
2622 pid_fd = check_pidfile();
2626 /* open all the listen sockets */
2627 if (config_listen_address_list_len > 0)
2629 for (size_t i = 0; i < config_listen_address_list_len; i++)
2630 open_listen_socket (config_listen_address_list[i]);
2632 rrd_free_ptrs((void ***) &config_listen_address_list,
2633 &config_listen_address_list_len);
2637 listen_socket_t sock;
2638 memset(&sock, 0, sizeof(sock));
2639 strncpy(sock.addr, RRDCACHED_DEFAULT_ADDRESS, sizeof(sock.addr)-1);
2640 open_listen_socket (&sock);
2643 if (listen_fds_num < 1)
2645 fprintf (stderr, "rrdcached: FATAL: cannot open any listen sockets\n");
2649 if (!stay_foreground)
2656 fprintf (stderr, "daemonize: fork(2) failed.\n");
2662 /* Become session leader */
2665 /* Open the first three file descriptors to /dev/null */
2670 open ("/dev/null", O_RDWR);
2671 if (dup(0) == -1 || dup(0) == -1){
2672 RRDD_LOG (LOG_ERR, "faild to run dup.\n");
2674 } /* if (!stay_foreground) */
2676 /* Change into the /tmp directory. */
2677 base_dir = (config_base_dir != NULL)
2681 if (chdir (base_dir) != 0)
2683 fprintf (stderr, "daemonize: chdir (%s) failed.\n", base_dir);
2687 install_signal_handlers();
2689 openlog ("rrdcached", LOG_PID, LOG_DAEMON);
2690 RRDD_LOG(LOG_INFO, "starting up");
2692 cache_tree = g_tree_new_full ((GCompareDataFunc) strcmp, NULL, NULL,
2693 (GDestroyNotify) free_cache_item);
2694 if (cache_tree == NULL)
2696 RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
2700 return write_pidfile (pid_fd);
2705 } /* }}} int daemonize */
2707 static int cleanup (void) /* {{{ */
2709 pthread_cond_broadcast (&flush_cond);
2710 pthread_join (flush_thread, NULL);
2712 pthread_cond_broadcast (&queue_cond);
2713 for (int i = 0; i < config_queue_threads; i++)
2714 pthread_join (queue_threads[i], NULL);
2716 if (config_flush_at_shutdown)
2718 assert(cache_queue_head == NULL);
2719 RRDD_LOG(LOG_INFO, "clean shutdown; all RRDs flushed");
2722 free(queue_threads);
2723 free(config_base_dir);
2725 pthread_mutex_lock(&cache_lock);
2726 g_tree_destroy(cache_tree);
2728 pthread_mutex_lock(&journal_lock);
2731 RRDD_LOG(LOG_INFO, "goodbye");
2735 free(config_pid_file);
2738 } /* }}} int cleanup */
2740 static int read_options (int argc, char **argv) /* {{{ */
2745 char **permissions = NULL;
2746 size_t permissions_len = 0;
2748 while ((option = getopt(argc, argv, "gl:P:f:w:z:t:Bb:p:Fj:h?")) != -1)
2758 listen_socket_t *new;
2760 new = malloc(sizeof(listen_socket_t));
2763 fprintf(stderr, "read_options: malloc failed.\n");
2766 memset(new, 0, sizeof(listen_socket_t));
2768 strncpy(new->addr, optarg, sizeof(new->addr)-1);
2770 /* Add permissions to the socket {{{ */
2771 if (permissions_len != 0)
2774 for (i = 0; i < permissions_len; i++)
2776 status = socket_permission_add (new, permissions[i]);
2779 fprintf (stderr, "read_options: Adding permission \"%s\" to "
2780 "socket failed. Most likely, this permission doesn't "
2781 "exist. Check your command line.\n", permissions[i]);
2786 else /* if (permissions_len == 0) */
2788 /* Add permission for ALL commands to the socket. */
2790 for (i = 0; i < list_of_commands_len; i++)
2792 status = socket_permission_add (new, list_of_commands[i].cmd);
2795 fprintf (stderr, "read_options: Adding permission \"%s\" to "
2796 "socket failed. This should never happen, ever! Sorry.\n",
2802 /* }}} Done adding permissions. */
2804 if (!rrd_add_ptr((void ***)&config_listen_address_list,
2805 &config_listen_address_list_len, new))
2807 fprintf(stderr, "read_options: rrd_add_ptr failed.\n");
2820 rrd_free_ptrs ((void *) &permissions, &permissions_len);
2822 optcopy = strdup (optarg);
2825 while ((ptr = strtok_r (dummy, ", ", &saveptr)) != NULL)
2828 rrd_add_strdup ((void *) &permissions, &permissions_len, ptr);
2839 temp = atoi (optarg);
2841 config_flush_interval = temp;
2844 fprintf (stderr, "Invalid flush interval: %s\n", optarg);
2854 temp = atoi (optarg);
2856 config_write_interval = temp;
2859 fprintf (stderr, "Invalid write interval: %s\n", optarg);
2869 temp = atoi(optarg);
2871 config_write_jitter = temp;
2874 fprintf (stderr, "Invalid write jitter: -z %s\n", optarg);
2884 threads = atoi(optarg);
2886 config_queue_threads = threads;
2889 fprintf (stderr, "Invalid thread count: -t %s\n", optarg);
2896 config_write_base_only = 1;
2902 char base_realpath[PATH_MAX];
2904 if (config_base_dir != NULL)
2905 free (config_base_dir);
2906 config_base_dir = strdup (optarg);
2907 if (config_base_dir == NULL)
2909 fprintf (stderr, "read_options: strdup failed.\n");
2913 if (rrd_mkdir_p (config_base_dir, 0777) != 0)
2915 fprintf (stderr, "Failed to create base directory '%s': %s\n",
2916 config_base_dir, rrd_strerror (errno));
2920 /* make sure that the base directory is not resolved via
2921 * symbolic links. this makes some performance-enhancing
2922 * assumptions possible (we don't have to resolve paths
2923 * that start with a "/")
2925 if (realpath(config_base_dir, base_realpath) == NULL)
2927 fprintf (stderr, "Failed to canonicalize the base directory '%s': "
2928 "%s\n", config_base_dir, rrd_strerror(errno));
2932 len = strlen (config_base_dir);
2933 while ((len > 0) && (config_base_dir[len - 1] == '/'))
2935 config_base_dir[len - 1] = 0;
2941 fprintf (stderr, "Invalid base directory: %s\n", optarg);
2945 _config_base_dir_len = len;
2947 len = strlen (base_realpath);
2948 while ((len > 0) && (base_realpath[len - 1] == '/'))
2950 base_realpath[len - 1] = '\0';
2954 if (strncmp(config_base_dir,
2955 base_realpath, sizeof(base_realpath)) != 0)
2958 "Base directory (-b) resolved via file system links!\n"
2959 "Please consult rrdcached '-b' documentation!\n"
2960 "Consider specifying the real directory (%s)\n",
2969 if (config_pid_file != NULL)
2970 free (config_pid_file);
2971 config_pid_file = strdup (optarg);
2972 if (config_pid_file == NULL)
2974 fprintf (stderr, "read_options: strdup failed.\n");
2981 config_flush_at_shutdown = 1;
2986 const char *dir = journal_dir = strdup(optarg);
2988 status = rrd_mkdir_p(dir, 0777);
2991 fprintf(stderr, "Failed to create journal directory '%s': %s\n",
2992 dir, rrd_strerror(errno));
2996 if (access(dir, R_OK|W_OK|X_OK) != 0)
2998 fprintf(stderr, "Must specify a writable directory with -j! (%s)\n",
2999 errno ? rrd_strerror(errno) : "");
3007 printf ("RRDCacheD %s\n"
3008 "Copyright (C) 2008,2009 Florian octo Forster and Kevin Brintnall\n"
3010 "Usage: rrdcached [options]\n"
3012 "Valid options are:\n"
3013 " -l <address> Socket address to listen to.\n"
3014 " -P <perms> Sets the permissions to assign to all following "
3016 " -w <seconds> Interval in which to write data.\n"
3017 " -z <delay> Delay writes up to <delay> seconds to spread load\n"
3018 " -t <threads> Number of write threads.\n"
3019 " -f <seconds> Interval in which to flush dead data.\n"
3020 " -p <file> Location of the PID-file.\n"
3021 " -b <dir> Base directory to change to.\n"
3022 " -B Restrict file access to paths within -b <dir>\n"
3023 " -g Do not fork and run in the foreground.\n"
3024 " -j <dir> Directory in which to create the journal files.\n"
3025 " -F Always flush all updates at shutdown\n"
3027 "For more information and a detailed description of all options "
3029 "to the rrdcached(1) manual page.\n",
3033 } /* switch (option) */
3034 } /* while (getopt) */
3036 /* advise the user when values are not sane */
3037 if (config_flush_interval < 2 * config_write_interval)
3038 fprintf(stderr, "WARNING: flush interval (-f) should be at least"
3039 " 2x write interval (-w) !\n");
3040 if (config_write_jitter > config_write_interval)
3041 fprintf(stderr, "WARNING: write delay (-z) should NOT be larger than"
3042 " write interval (-w) !\n");
3044 if (config_write_base_only && config_base_dir == NULL)
3045 fprintf(stderr, "WARNING: -B does not make sense without -b!\n"
3046 " Consult the rrdcached documentation\n");
3048 if (journal_dir == NULL)
3049 config_flush_at_shutdown = 1;
3051 rrd_free_ptrs ((void *) &permissions, &permissions_len);
3054 } /* }}} int read_options */
3056 int main (int argc, char **argv)
3060 status = read_options (argc, argv);
3068 status = daemonize ();
3071 fprintf (stderr, "rrdcached: daemonize failed, exiting.\n");
3077 /* start the queue threads */
3078 queue_threads = calloc(config_queue_threads, sizeof(*queue_threads));
3079 if (queue_threads == NULL)
3081 RRDD_LOG (LOG_ERR, "FATAL: cannot calloc queue threads");
3085 for (int i = 0; i < config_queue_threads; i++)
3087 memset (&queue_threads[i], 0, sizeof (*queue_threads));
3088 status = pthread_create (&queue_threads[i], NULL, queue_thread_main, NULL);
3091 RRDD_LOG (LOG_ERR, "FATAL: cannot create queue thread");
3097 /* start the flush thread */
3098 memset(&flush_thread, 0, sizeof(flush_thread));
3099 status = pthread_create (&flush_thread, NULL, flush_thread_main, NULL);
3102 RRDD_LOG (LOG_ERR, "FATAL: cannot create flush thread");
3107 listen_thread_main (NULL);
3114 * vim: set sw=2 sts=2 ts=8 et fdm=marker :