2 * RRDTool - src/rrd_daemon.c
3 * Copyright (C) 2008 Florian octo Forster
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Florian octo Forster <octo at verplant.org>
23 * First tell the compiler to stick to the C99 and POSIX standards as close as
26 #ifndef __STRICT_ANSI__ /* {{{ */
27 # define __STRICT_ANSI__
30 #ifndef _ISOC99_SOURCE
31 # define _ISOC99_SOURCE
34 #ifdef _POSIX_C_SOURCE
35 # undef _POSIX_C_SOURCE
37 #define _POSIX_C_SOURCE 200112L
39 /* Single UNIX needed for strdup. */
43 #define _XOPEN_SOURCE 500
59 * Now for some includes..
61 #include "rrd.h" /* {{{ */
62 #include "rrd_client.h"
73 #include <sys/types.h>
77 #include <sys/socket.h>
88 #include <glib-2.0/glib.h>
91 #define RRDD_LOG(severity, ...) syslog ((severity), __VA_ARGS__)
94 # define __attribute__(x) /**/
100 struct listen_socket_s
103 char path[PATH_MAX + 1];
105 typedef struct listen_socket_s listen_socket_t;
108 typedef struct cache_item_s cache_item_t;
114 time_t last_flush_time;
115 #define CI_FLAGS_IN_TREE 0x01
116 #define CI_FLAGS_IN_QUEUE 0x02
122 struct callback_flush_data_s
128 typedef struct callback_flush_data_s callback_flush_data_t;
135 typedef enum queue_side_e queue_side_t;
140 static listen_socket_t *listen_fds = NULL;
141 static size_t listen_fds_num = 0;
143 static int do_shutdown = 0;
145 static pthread_t queue_thread;
147 static pthread_t *connetion_threads = NULL;
148 static pthread_mutex_t connetion_threads_lock = PTHREAD_MUTEX_INITIALIZER;
149 static int connetion_threads_num = 0;
152 static GTree *cache_tree = NULL;
153 static cache_item_t *cache_queue_head = NULL;
154 static cache_item_t *cache_queue_tail = NULL;
155 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
156 static pthread_cond_t cache_cond = PTHREAD_COND_INITIALIZER;
158 static pthread_cond_t flush_cond = PTHREAD_COND_INITIALIZER;
160 static int config_write_interval = 300;
161 static int config_flush_interval = 3600;
162 static char *config_pid_file = NULL;
163 static char *config_base_dir = NULL;
165 static char **config_listen_address_list = NULL;
166 static int config_listen_address_list_len = 0;
168 static uint64_t stats_queue_length = 0;
169 static uint64_t stats_updates_written = 0;
170 static uint64_t stats_data_sets_written = 0;
171 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
176 static void sig_int_handler (int s __attribute__((unused))) /* {{{ */
179 } /* }}} void sig_int_handler */
181 static void sig_term_handler (int s __attribute__((unused))) /* {{{ */
184 } /* }}} void sig_term_handler */
186 static int write_pidfile (void) /* {{{ */
194 file = (config_pid_file != NULL)
196 : LOCALSTATEDIR "/run/rrdcached.pid";
198 fh = fopen (file, "w");
201 RRDD_LOG (LOG_ERR, "write_pidfile: Opening `%s' failed.", file);
205 fprintf (fh, "%i\n", (int) pid);
209 } /* }}} int write_pidfile */
211 static int remove_pidfile (void) /* {{{ */
216 file = (config_pid_file != NULL)
218 : LOCALSTATEDIR "/run/rrdcached.pid";
220 status = unlink (file);
224 } /* }}} int remove_pidfile */
226 static ssize_t sread (int fd, void *buffer_void, size_t buffer_size) /* {{{ */
233 buffer = (char *) buffer_void;
235 buffer_free = buffer_size;
237 while (buffer_free > 0)
239 status = read (fd, buffer + buffer_used, buffer_free);
240 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
249 assert ((0 > status) || (buffer_free >= (size_t) status));
251 buffer_free = buffer_free - status;
252 buffer_used = buffer_used + status;
254 if (buffer[buffer_used - 1] == '\n')
258 assert (buffer_used > 0);
260 if (buffer[buffer_used - 1] != '\n')
266 buffer[buffer_used - 1] = 0;
268 /* Fix network line endings. */
269 if ((buffer_used > 1) && (buffer[buffer_used - 2] == '\r'))
272 buffer[buffer_used - 1] = 0;
275 return (buffer_used);
276 } /* }}} ssize_t sread */
278 static ssize_t swrite (int fd, const void *buf, size_t count) /* {{{ */
284 ptr = (const char *) buf;
289 status = write (fd, (const void *) ptr, nleft);
291 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
297 nleft = nleft - status;
302 } /* }}} ssize_t swrite */
305 * enqueue_cache_item:
306 * `cache_lock' must be acquired before calling this function!
308 static int enqueue_cache_item (cache_item_t *ci, /* {{{ */
316 if (ci->values_num == 0)
321 if ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
323 assert (ci->next == NULL);
324 ci->next = cache_queue_head;
325 cache_queue_head = ci;
327 if (cache_queue_tail == NULL)
328 cache_queue_tail = cache_queue_head;
332 else if (cache_queue_head == ci)
336 else /* enqueued, but not first entry */
340 /* find previous entry */
341 for (prev = cache_queue_head; prev != NULL; prev = prev->next)
342 if (prev->next == ci)
344 assert (prev != NULL);
346 /* move to the front */
347 prev->next = ci->next;
348 ci->next = cache_queue_head;
349 cache_queue_head = ci;
351 /* check if we need to adapt the tail */
352 if (cache_queue_tail == ci)
353 cache_queue_tail = prev;
356 else /* (side == TAIL) */
358 /* We don't move values back in the list.. */
359 if ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
362 assert (ci->next == NULL);
364 if (cache_queue_tail == NULL)
365 cache_queue_head = ci;
367 cache_queue_tail->next = ci;
368 cache_queue_tail = ci;
373 ci->flags |= CI_FLAGS_IN_QUEUE;
377 pthread_mutex_lock (&stats_lock);
378 stats_queue_length++;
379 pthread_mutex_unlock (&stats_lock);
383 } /* }}} int enqueue_cache_item */
386 * tree_callback_flush:
387 * Called via `g_tree_foreach' in `queue_thread_main'. `cache_lock' is held
388 * while this is in progress.
390 static gboolean tree_callback_flush (gpointer key, gpointer value, /* {{{ */
394 callback_flush_data_t *cfd;
396 ci = (cache_item_t *) value;
397 cfd = (callback_flush_data_t *) data;
399 if (((cfd->now - ci->last_flush_time) >= config_write_interval)
400 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
401 && (ci->values_num > 0))
403 enqueue_cache_item (ci, TAIL);
405 else if (((cfd->now - ci->last_flush_time) >= config_flush_interval)
406 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
407 && (ci->values_num <= 0))
411 temp = (char **) realloc (cfd->keys,
412 sizeof (char *) * (cfd->keys_num + 1));
415 RRDD_LOG (LOG_ERR, "tree_callback_flush: realloc failed.");
419 /* Make really sure this points to the _same_ place */
420 assert ((char *) key == ci->file);
421 cfd->keys[cfd->keys_num] = (char *) key;
426 } /* }}} gboolean tree_callback_flush */
428 static void *queue_thread_main (void *args __attribute__((unused))) /* {{{ */
431 struct timespec next_flush;
433 gettimeofday (&now, NULL);
434 next_flush.tv_sec = now.tv_sec + config_flush_interval;
435 next_flush.tv_nsec = 1000 * now.tv_usec;
437 pthread_mutex_lock (&cache_lock);
438 while ((do_shutdown == 0) || (cache_queue_head != NULL))
447 /* First, check if it's time to do the cache flush. */
448 gettimeofday (&now, NULL);
449 if ((now.tv_sec > next_flush.tv_sec)
450 || ((now.tv_sec == next_flush.tv_sec)
451 && ((1000 * now.tv_usec) > next_flush.tv_nsec)))
453 callback_flush_data_t cfd;
456 memset (&cfd, 0, sizeof (cfd));
457 /* Pass the current time as user data so that we don't need to call
458 * `time' for each node. */
459 cfd.now = time (NULL);
463 /* `tree_callback_flush' will return the keys of all values that haven't
464 * been touched in the last `config_flush_interval' seconds in `cfd'.
465 * The char*'s in this array point to the same memory as ci->file, so we
466 * don't need to free them separately. */
467 g_tree_foreach (cache_tree, tree_callback_flush, (gpointer) &cfd);
469 for (k = 0; k < cfd.keys_num; k++)
471 /* This must not fail. */
472 ci = (cache_item_t *) g_tree_lookup (cache_tree, cfd.keys[k]);
475 /* If we end up here with values available, something's seriously
477 assert (ci->values_num == 0);
479 /* Remove the node from the tree */
480 g_tree_remove (cache_tree, cfd.keys[k]);
483 /* Now free and clean up `ci'. */
488 } /* for (k = 0; k < cfd.keys_num; k++) */
490 if (cfd.keys != NULL)
496 /* Determine the time of the next cache flush. */
497 while (next_flush.tv_sec < now.tv_sec)
498 next_flush.tv_sec += config_flush_interval;
501 /* Now, check if there's something to store away. If not, wait until
502 * something comes in or it's time to do the cache flush. */
503 if (cache_queue_head == NULL)
505 status = pthread_cond_timedwait (&cache_cond, &cache_lock, &next_flush);
506 if ((status != 0) && (status != ETIMEDOUT))
508 RRDD_LOG (LOG_ERR, "queue_thread_main: "
509 "pthread_cond_timedwait returned %i.", status);
513 /* Check if a value has arrived. This may be NULL if we timed out or there
514 * was an interrupt such as a signal. */
515 if (cache_queue_head == NULL)
518 ci = cache_queue_head;
520 /* copy the relevant parts */
521 file = strdup (ci->file);
524 RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
529 values_num = ci->values_num;
534 ci->last_flush_time = time (NULL);
535 ci->flags &= ~(CI_FLAGS_IN_QUEUE);
537 cache_queue_head = ci->next;
538 if (cache_queue_head == NULL)
539 cache_queue_tail = NULL;
542 pthread_mutex_lock (&stats_lock);
543 assert (stats_queue_length > 0);
544 stats_queue_length--;
545 pthread_mutex_unlock (&stats_lock);
547 pthread_mutex_unlock (&cache_lock);
549 status = rrd_update_r (file, NULL, values_num, (void *) values);
552 RRDD_LOG (LOG_ERR, "queue_thread_main: "
553 "rrd_update_r failed with status %i.",
558 for (i = 0; i < values_num; i++)
563 pthread_mutex_lock (&stats_lock);
564 stats_updates_written++;
565 stats_data_sets_written += values_num;
566 pthread_mutex_unlock (&stats_lock);
569 pthread_mutex_lock (&cache_lock);
570 pthread_cond_broadcast (&flush_cond);
571 } /* while (do_shutdown == 0) */
572 pthread_mutex_unlock (&cache_lock);
575 } /* }}} void *queue_thread_main */
577 static int buffer_get_field (char **buffer_ret, /* {{{ */
578 size_t *buffer_size_ret, char **field_ret)
587 buffer = *buffer_ret;
589 buffer_size = *buffer_size_ret;
593 if (buffer_size <= 0)
596 /* This is ensured by `handle_request'. */
597 assert (buffer[buffer_size - 1] == ' ');
600 while (buffer_pos < buffer_size)
602 /* Check for end-of-field or end-of-buffer */
603 if (buffer[buffer_pos] == ' ')
605 field[field_size] = 0;
611 /* Handle escaped characters. */
612 else if (buffer[buffer_pos] == '\\')
614 if (buffer_pos >= (buffer_size - 1))
617 field[field_size] = buffer[buffer_pos];
621 /* Normal operation */
624 field[field_size] = buffer[buffer_pos];
628 } /* while (buffer_pos < buffer_size) */
633 *buffer_ret = buffer + buffer_pos;
634 *buffer_size_ret = buffer_size - buffer_pos;
638 } /* }}} int buffer_get_field */
640 static int flush_file (const char *filename) /* {{{ */
644 pthread_mutex_lock (&cache_lock);
646 ci = (cache_item_t *) g_tree_lookup (cache_tree, filename);
649 pthread_mutex_unlock (&cache_lock);
653 /* Enqueue at head */
654 enqueue_cache_item (ci, HEAD);
655 pthread_cond_signal (&cache_cond);
657 while ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
661 pthread_cond_wait (&flush_cond, &cache_lock);
663 ci = g_tree_lookup (cache_tree, filename);
666 RRDD_LOG (LOG_ERR, "flush_file: Tree node went away "
667 "while waiting for flush.");
668 pthread_mutex_unlock (&cache_lock);
673 pthread_mutex_unlock (&cache_lock);
675 } /* }}} int flush_file */
677 static int handle_request_help (int fd, /* {{{ */
678 char *buffer, size_t buffer_size)
682 size_t help_text_len;
688 "4 Command overview\n",
689 "FLUSH <filename>\n",
690 "HELP [<command>]\n",
691 "UPDATE <filename> <values> [<values> ...]\n",
694 size_t help_help_len = sizeof (help_help) / sizeof (help_help[0]);
698 "4 Help for FLUSH\n",
699 "Usage: FLUSH <filename>\n",
701 "Adds the given filename to the head of the update queue and returns\n",
702 "after is has been dequeued.\n"
704 size_t help_flush_len = sizeof (help_flush) / sizeof (help_flush[0]);
706 char *help_update[] =
708 "9 Help for UPDATE\n",
709 "Usage: UPDATE <filename> <values> [<values> ...]\n"
711 "Adds the given file to the internal cache if it is not yet known and\n",
712 "appends the given value(s) to the entry. See the rrdcached(1) manpage\n",
715 "Each <values> has the following form:\n",
716 " <values> = <time>:<value>[:<value>[...]]\n",
717 "See the rrdupdate(1) manpage for details.\n"
719 size_t help_update_len = sizeof (help_update) / sizeof (help_update[0]);
723 "4 Help for STATS\n",
726 "Returns some performance counters, see the rrdcached(1) manpage for\n",
727 "a description of the values.\n"
729 size_t help_stats_len = sizeof (help_stats) / sizeof (help_stats[0]);
731 status = buffer_get_field (&buffer, &buffer_size, &command);
734 help_text = help_help;
735 help_text_len = help_help_len;
739 if (strcasecmp (command, "update") == 0)
741 help_text = help_update;
742 help_text_len = help_update_len;
744 else if (strcasecmp (command, "flush") == 0)
746 help_text = help_flush;
747 help_text_len = help_flush_len;
749 else if (strcasecmp (command, "stats") == 0)
751 help_text = help_stats;
752 help_text_len = help_stats_len;
756 help_text = help_help;
757 help_text_len = help_help_len;
761 for (i = 0; i < help_text_len; i++)
763 status = swrite (fd, help_text[i], strlen (help_text[i]));
767 RRDD_LOG (LOG_ERR, "handle_request_help: swrite returned an error.");
773 } /* }}} int handle_request_help */
775 static int handle_request_stats (int fd, /* {{{ */
776 char *buffer __attribute__((unused)),
777 size_t buffer_size __attribute__((unused)))
782 uint64_t copy_queue_length;
783 uint64_t copy_updates_written;
784 uint64_t copy_data_sets_written;
786 uint64_t tree_nodes_number;
789 pthread_mutex_lock (&stats_lock);
790 copy_queue_length = stats_queue_length;
791 copy_updates_written = stats_updates_written;
792 copy_data_sets_written = stats_data_sets_written;
793 pthread_mutex_unlock (&stats_lock);
795 pthread_mutex_lock (&cache_lock);
796 tree_nodes_number = (uint64_t) g_tree_nnodes (cache_tree);
797 tree_depth = (uint64_t) g_tree_height (cache_tree);
798 pthread_mutex_unlock (&cache_lock);
800 #define RRDD_STATS_SEND \
801 outbuf[sizeof (outbuf) - 1] = 0; \
802 status = swrite (fd, outbuf, strlen (outbuf)); \
806 RRDD_LOG (LOG_INFO, "handle_request_stats: swrite returned an error."); \
810 strncpy (outbuf, "5 Statistics follow\n", sizeof (outbuf));
813 snprintf (outbuf, sizeof (outbuf),
814 "QueueLength: %"PRIu64"\n", copy_queue_length);
817 snprintf (outbuf, sizeof (outbuf),
818 "UpdatesWritten: %"PRIu64"\n", copy_updates_written);
821 snprintf (outbuf, sizeof (outbuf),
822 "DataSetsWritten: %"PRIu64"\n", copy_data_sets_written);
825 snprintf (outbuf, sizeof (outbuf),
826 "TreeNodesNumber: %"PRIu64"\n", tree_nodes_number);
829 snprintf (outbuf, sizeof (outbuf),
830 "TreeDepth: %"PRIu64"\n", tree_depth);
834 #undef RRDD_STATS_SEND
835 } /* }}} int handle_request_stats */
837 static int handle_request_flush (int fd, /* {{{ */
838 char *buffer, size_t buffer_size)
844 status = buffer_get_field (&buffer, &buffer_size, &file);
847 strncpy (result, "-1 Usage: flush <filename>\n", sizeof (result));
851 status = flush_file (file);
853 snprintf (result, sizeof (result), "0 Successfully flushed %s.\n", file);
854 else if (status == ENOENT)
855 snprintf (result, sizeof (result), "-1 No such file: %s.\n", file);
857 strncpy (result, "-1 Internal error.\n", sizeof (result));
859 snprintf (result, sizeof (result), "-1 Failed with status %i.\n", status);
861 result[sizeof (result) - 1] = 0;
863 status = swrite (fd, result, strlen (result));
867 RRDD_LOG (LOG_INFO, "handle_request_flush: swrite returned an error.");
872 } /* }}} int handle_request_flush */
874 static int handle_request_update (int fd, /* {{{ */
875 char *buffer, size_t buffer_size)
886 #define RRDD_UPDATE_SEND \
887 answer[sizeof (answer) - 1] = 0; \
888 status = swrite (fd, answer, strlen (answer)); \
892 RRDD_LOG (LOG_INFO, "handle_request_update: swrite returned an error."); \
898 status = buffer_get_field (&buffer, &buffer_size, &file);
901 strncpy (answer, "-1 Usage: UPDATE <filename> <values> [<values> ...]\n",
907 pthread_mutex_lock (&cache_lock);
909 ci = g_tree_lookup (cache_tree, file);
910 if (ci == NULL) /* {{{ */
914 memset (&statbuf, 0, sizeof (statbuf));
915 status = stat (file, &statbuf);
918 pthread_mutex_unlock (&cache_lock);
919 RRDD_LOG (LOG_ERR, "handle_request_update: stat (%s) failed.", file);
922 if (status == ENOENT)
923 snprintf (answer, sizeof (answer), "-1 No such file: %s", file);
925 snprintf (answer, sizeof (answer), "-1 stat failed with error %i.\n",
930 if (!S_ISREG (statbuf.st_mode))
932 pthread_mutex_unlock (&cache_lock);
934 snprintf (answer, sizeof (answer), "-1 Not a regular file: %s", file);
939 ci = (cache_item_t *) malloc (sizeof (cache_item_t));
942 pthread_mutex_unlock (&cache_lock);
943 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
945 strncpy (answer, "-1 malloc failed.\n", sizeof (answer));
949 memset (ci, 0, sizeof (cache_item_t));
951 ci->file = strdup (file);
952 if (ci->file == NULL)
954 pthread_mutex_unlock (&cache_lock);
956 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
958 strncpy (answer, "-1 strdup failed.\n", sizeof (answer));
965 ci->last_flush_time = now;
966 ci->flags = CI_FLAGS_IN_TREE;
968 g_tree_insert (cache_tree, (void *) ci->file, (void *) ci);
972 while (buffer_size > 0)
977 status = buffer_get_field (&buffer, &buffer_size, &value);
980 RRDD_LOG (LOG_INFO, "handle_request_update: Error reading field.");
984 temp = (char **) realloc (ci->values,
985 sizeof (char *) * (ci->values_num + 1));
988 RRDD_LOG (LOG_ERR, "handle_request_update: realloc failed.");
993 ci->values[ci->values_num] = strdup (value);
994 if (ci->values[ci->values_num] == NULL)
996 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
1004 if (((now - ci->last_flush_time) >= config_write_interval)
1005 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
1006 && (ci->values_num > 0))
1008 enqueue_cache_item (ci, TAIL);
1009 pthread_cond_signal (&cache_cond);
1012 pthread_mutex_unlock (&cache_lock);
1016 strncpy (answer, "-1 No values updated.\n", sizeof (answer));
1020 snprintf (answer, sizeof (answer), "0 Enqueued %i value%s\n", values_num,
1021 (values_num == 1) ? "" : "s");
1025 #undef RRDD_UPDATE_SEND
1026 } /* }}} int handle_request_update */
1028 static int handle_request (int fd) /* {{{ */
1036 status = (int) sread (fd, buffer, sizeof (buffer));
1041 else if (status < 0)
1043 RRDD_LOG (LOG_ERR, "handle_request: sread failed.");
1046 buffer_size = (size_t) status;
1047 assert (buffer_size <= sizeof (buffer));
1048 assert (buffer[buffer_size - 1] == 0);
1050 /* Place the normal field separator at the end to simplify
1051 * `buffer_get_field's work. */
1052 buffer[buffer_size - 1] = ' ';
1054 buffer_ptr = buffer;
1056 status = buffer_get_field (&buffer_ptr, &buffer_size, &command);
1059 RRDD_LOG (LOG_INFO, "handle_request: Unable parse command.");
1063 if (strcasecmp (command, "update") == 0)
1065 return (handle_request_update (fd, buffer_ptr, buffer_size));
1067 else if (strcasecmp (command, "flush") == 0)
1069 return (handle_request_flush (fd, buffer_ptr, buffer_size));
1071 else if (strcasecmp (command, "stats") == 0)
1073 return (handle_request_stats (fd, buffer_ptr, buffer_size));
1075 else if (strcasecmp (command, "help") == 0)
1077 return (handle_request_help (fd, buffer_ptr, buffer_size));
1083 snprintf (result, sizeof (result), "-1 Unknown command: %s\n", command);
1084 result[sizeof (result) - 1] = 0;
1086 status = swrite (fd, result, strlen (result));
1089 RRDD_LOG (LOG_ERR, "handle_request: swrite failed.");
1095 } /* }}} int handle_request */
1097 static void *connection_thread_main (void *args /* {{{ */
1098 __attribute__((unused)))
1104 fd = *((int *) args);
1106 pthread_mutex_lock (&connetion_threads_lock);
1110 temp = (pthread_t *) realloc (connetion_threads,
1111 sizeof (pthread_t) * (connetion_threads_num + 1));
1114 RRDD_LOG (LOG_ERR, "connection_thread_main: realloc failed.");
1118 connetion_threads = temp;
1119 connetion_threads[connetion_threads_num] = pthread_self ();
1120 connetion_threads_num++;
1123 pthread_mutex_unlock (&connetion_threads_lock);
1125 while (do_shutdown == 0)
1127 struct pollfd pollfd;
1131 pollfd.events = POLLIN | POLLPRI;
1134 status = poll (&pollfd, 1, /* timeout = */ 500);
1135 if (status == 0) /* timeout */
1137 else if (status < 0) /* error */
1140 if (status == EINTR)
1142 RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
1146 if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
1151 else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
1153 RRDD_LOG (LOG_WARNING, "connection_thread_main: "
1154 "poll(2) returned something unexpected: %#04hx",
1160 status = handle_request (fd);
1168 self = pthread_self ();
1169 /* Remove this thread from the connection threads list */
1170 pthread_mutex_lock (&connetion_threads_lock);
1171 /* Find out own index in the array */
1172 for (i = 0; i < connetion_threads_num; i++)
1173 if (pthread_equal (connetion_threads[i], self) != 0)
1175 assert (i < connetion_threads_num);
1177 /* Move the trailing threads forward. */
1178 if (i < (connetion_threads_num - 1))
1180 memmove (connetion_threads + i,
1181 connetion_threads + i + 1,
1182 sizeof (pthread_t) * (connetion_threads_num - i - 1));
1185 connetion_threads_num--;
1186 pthread_mutex_unlock (&connetion_threads_lock);
1190 } /* }}} void *connection_thread_main */
1192 static int open_listen_socket_unix (const char *path) /* {{{ */
1195 struct sockaddr_un sa;
1196 listen_socket_t *temp;
1199 temp = (listen_socket_t *) realloc (listen_fds,
1200 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1203 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: realloc failed.");
1207 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1209 fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
1212 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: socket(2) failed.");
1216 memset (&sa, 0, sizeof (sa));
1217 sa.sun_family = AF_UNIX;
1218 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
1220 status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
1223 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: bind(2) failed.");
1229 status = listen (fd, /* backlog = */ 10);
1232 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: listen(2) failed.");
1238 listen_fds[listen_fds_num].fd = fd;
1239 snprintf (listen_fds[listen_fds_num].path,
1240 sizeof (listen_fds[listen_fds_num].path) - 1,
1245 } /* }}} int open_listen_socket_unix */
1247 static int open_listen_socket (const char *addr) /* {{{ */
1249 struct addrinfo ai_hints;
1250 struct addrinfo *ai_res;
1251 struct addrinfo *ai_ptr;
1254 assert (addr != NULL);
1256 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
1257 return (open_listen_socket_unix (addr + strlen ("unix:")));
1258 else if (addr[0] == '/')
1259 return (open_listen_socket_unix (addr));
1261 memset (&ai_hints, 0, sizeof (ai_hints));
1262 ai_hints.ai_flags = 0;
1263 #ifdef AI_ADDRCONFIG
1264 ai_hints.ai_flags |= AI_ADDRCONFIG;
1266 ai_hints.ai_family = AF_UNSPEC;
1267 ai_hints.ai_socktype = SOCK_STREAM;
1270 status = getaddrinfo (addr, RRDCACHED_DEFAULT_PORT, &ai_hints, &ai_res);
1273 RRDD_LOG (LOG_ERR, "open_listen_socket: getaddrinfo(%s) failed: "
1274 "%s", addr, gai_strerror (status));
1278 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1281 listen_socket_t *temp;
1283 temp = (listen_socket_t *) realloc (listen_fds,
1284 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1287 RRDD_LOG (LOG_ERR, "open_listen_socket: realloc failed.");
1291 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1293 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1296 RRDD_LOG (LOG_ERR, "open_listen_socket: socket(2) failed.");
1300 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1303 RRDD_LOG (LOG_ERR, "open_listen_socket: bind(2) failed.");
1308 status = listen (fd, /* backlog = */ 10);
1311 RRDD_LOG (LOG_ERR, "open_listen_socket: listen(2) failed.");
1316 listen_fds[listen_fds_num].fd = fd;
1317 strncpy (listen_fds[listen_fds_num].path, addr,
1318 sizeof (listen_fds[listen_fds_num].path) - 1);
1320 } /* for (ai_ptr) */
1323 } /* }}} int open_listen_socket */
1325 static int close_listen_sockets (void) /* {{{ */
1329 for (i = 0; i < listen_fds_num; i++)
1331 close (listen_fds[i].fd);
1332 if (strncmp ("unix:", listen_fds[i].path, strlen ("unix:")) == 0)
1333 unlink (listen_fds[i].path + strlen ("unix:"));
1341 } /* }}} int close_listen_sockets */
1343 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
1345 struct pollfd *pollfds;
1350 for (i = 0; i < config_listen_address_list_len; i++)
1351 open_listen_socket (config_listen_address_list[i]);
1353 if (config_listen_address_list_len < 1)
1354 open_listen_socket (RRDCACHED_DEFAULT_ADDRESS);
1356 if (listen_fds_num < 1)
1358 RRDD_LOG (LOG_ERR, "listen_thread_main: No listen sockets "
1359 "could be opened. Sorry.");
1363 pollfds_num = listen_fds_num;
1364 pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
1365 if (pollfds == NULL)
1367 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1370 memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
1372 while (do_shutdown == 0)
1374 assert (pollfds_num == ((int) listen_fds_num));
1375 for (i = 0; i < pollfds_num; i++)
1377 pollfds[i].fd = listen_fds[i].fd;
1378 pollfds[i].events = POLLIN | POLLPRI;
1379 pollfds[i].revents = 0;
1382 status = poll (pollfds, pollfds_num, /* timeout = */ -1);
1386 if (status != EINTR)
1388 RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
1393 for (i = 0; i < pollfds_num; i++)
1396 struct sockaddr_storage client_sa;
1397 socklen_t client_sa_size;
1399 pthread_attr_t attr;
1401 if (pollfds[i].revents == 0)
1404 if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
1406 RRDD_LOG (LOG_ERR, "listen_thread_main: "
1407 "poll(2) returned something unexpected for listen FD #%i.",
1412 client_sd = (int *) malloc (sizeof (int));
1413 if (client_sd == NULL)
1415 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1419 client_sa_size = sizeof (client_sa);
1420 *client_sd = accept (pollfds[i].fd,
1421 (struct sockaddr *) &client_sa, &client_sa_size);
1424 RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
1428 pthread_attr_init (&attr);
1429 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
1431 status = pthread_create (&tid, &attr, connection_thread_main,
1432 /* args = */ (void *) client_sd);
1435 RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
1440 } /* for (pollfds_num) */
1441 } /* while (do_shutdown == 0) */
1443 close_listen_sockets ();
1445 pthread_mutex_lock (&connetion_threads_lock);
1446 while (connetion_threads_num > 0)
1450 wait_for = connetion_threads[0];
1452 pthread_mutex_unlock (&connetion_threads_lock);
1453 pthread_join (wait_for, /* retval = */ NULL);
1454 pthread_mutex_lock (&connetion_threads_lock);
1456 pthread_mutex_unlock (&connetion_threads_lock);
1459 } /* }}} void *listen_thread_main */
1461 static int daemonize (void) /* {{{ */
1467 /* These structures are static, because `sigaction' behaves weird if the are
1469 static struct sigaction sa_int;
1470 static struct sigaction sa_term;
1471 static struct sigaction sa_pipe;
1476 fprintf (stderr, "daemonize: fork(2) failed.\n");
1484 /* Change into the /tmp directory. */
1485 base_dir = (config_base_dir != NULL)
1488 status = chdir (base_dir);
1491 fprintf (stderr, "daemonize: chdir (%s) failed.\n", base_dir);
1495 /* Become session leader */
1498 /* Open the first three file descriptors to /dev/null */
1503 open ("/dev/null", O_RDWR);
1507 /* Install signal handlers */
1508 memset (&sa_int, 0, sizeof (sa_int));
1509 sa_int.sa_handler = sig_int_handler;
1510 sigaction (SIGINT, &sa_int, NULL);
1512 memset (&sa_term, 0, sizeof (sa_term));
1513 sa_term.sa_handler = sig_term_handler;
1514 sigaction (SIGTERM, &sa_term, NULL);
1516 memset (&sa_pipe, 0, sizeof (sa_pipe));
1517 sa_pipe.sa_handler = SIG_IGN;
1518 sigaction (SIGPIPE, &sa_pipe, NULL);
1520 openlog ("rrdcached", LOG_PID, LOG_DAEMON);
1522 cache_tree = g_tree_new ((GCompareFunc) strcmp);
1523 if (cache_tree == NULL)
1525 RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
1529 memset (&queue_thread, 0, sizeof (queue_thread));
1530 status = pthread_create (&queue_thread, /* attr = */ NULL,
1531 queue_thread_main, /* args = */ NULL);
1534 RRDD_LOG (LOG_ERR, "daemonize: pthread_create failed.");
1541 } /* }}} int daemonize */
1543 static int cleanup (void) /* {{{ */
1547 pthread_cond_signal (&cache_cond);
1548 pthread_join (queue_thread, /* return = */ NULL);
1555 } /* }}} int cleanup */
1557 static int read_options (int argc, char **argv) /* {{{ */
1562 while ((option = getopt(argc, argv, "l:f:w:b:p:h?")) != -1)
1570 temp = (char **) realloc (config_listen_address_list,
1571 sizeof (char *) * (config_listen_address_list_len + 1));
1574 fprintf (stderr, "read_options: realloc failed.\n");
1577 config_listen_address_list = temp;
1579 temp[config_listen_address_list_len] = strdup (optarg);
1580 if (temp[config_listen_address_list_len] == NULL)
1582 fprintf (stderr, "read_options: strdup failed.\n");
1585 config_listen_address_list_len++;
1593 temp = atoi (optarg);
1595 config_flush_interval = temp;
1598 fprintf (stderr, "Invalid flush interval: %s\n", optarg);
1608 temp = atoi (optarg);
1610 config_write_interval = temp;
1613 fprintf (stderr, "Invalid write interval: %s\n", optarg);
1623 if (config_base_dir != NULL)
1624 free (config_base_dir);
1625 config_base_dir = strdup (optarg);
1626 if (config_base_dir == NULL)
1628 fprintf (stderr, "read_options: strdup failed.\n");
1632 len = strlen (config_base_dir);
1633 while ((len > 0) && (config_base_dir[len - 1] == '/'))
1635 config_base_dir[len - 1] = 0;
1641 fprintf (stderr, "Invalid base directory: %s\n", optarg);
1649 if (config_pid_file != NULL)
1650 free (config_pid_file);
1651 config_pid_file = strdup (optarg);
1652 if (config_pid_file == NULL)
1654 fprintf (stderr, "read_options: strdup failed.\n");
1662 printf ("RRDd %s Copyright (C) 2008 Florian octo Forster\n"
1664 "Usage: rrdcached [options]\n"
1666 "Valid options are:\n"
1667 " -l <address> Socket address to listen to.\n"
1668 " -w <seconds> Interval in which to write data.\n"
1669 " -f <seconds> Interval in which to flush dead data.\n"
1670 " -p <file> Location of the PID-file.\n"
1671 " -b <dir> Base directory to change to.\n"
1673 "For more information and a detailed description of all options "
1675 "to the rrdcached(1) manual page.\n",
1679 } /* switch (option) */
1680 } /* while (getopt) */
1683 } /* }}} int read_options */
1685 int main (int argc, char **argv)
1689 status = read_options (argc, argv);
1697 status = daemonize ();
1700 struct sigaction sigchld;
1702 memset (&sigchld, 0, sizeof (sigchld));
1703 sigchld.sa_handler = SIG_IGN;
1704 sigaction (SIGCHLD, &sigchld, NULL);
1708 else if (status != 0)
1710 fprintf (stderr, "daemonize failed, exiting.\n");
1714 listen_thread_main (NULL);
1722 * vim: set sw=2 sts=2 ts=8 et fdm=marker :