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, /* {{{ */
313 RRDD_LOG (LOG_DEBUG, "enqueue_cache_item: Adding %s to the update queue.",
319 if (ci->values_num == 0)
324 if ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
326 assert (ci->next == NULL);
327 ci->next = cache_queue_head;
328 cache_queue_head = ci;
330 if (cache_queue_tail == NULL)
331 cache_queue_tail = cache_queue_head;
335 else if (cache_queue_head == ci)
339 else /* enqueued, but not first entry */
343 /* find previous entry */
344 for (prev = cache_queue_head; prev != NULL; prev = prev->next)
345 if (prev->next == ci)
347 assert (prev != NULL);
349 /* move to the front */
350 prev->next = ci->next;
351 ci->next = cache_queue_head;
352 cache_queue_head = ci;
354 /* check if we need to adapt the tail */
355 if (cache_queue_tail == ci)
356 cache_queue_tail = prev;
359 else /* (side == TAIL) */
361 /* We don't move values back in the list.. */
362 if ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
365 assert (ci->next == NULL);
367 if (cache_queue_tail == NULL)
368 cache_queue_head = ci;
370 cache_queue_tail->next = ci;
371 cache_queue_tail = ci;
376 ci->flags |= CI_FLAGS_IN_QUEUE;
380 pthread_mutex_lock (&stats_lock);
381 stats_queue_length++;
382 pthread_mutex_unlock (&stats_lock);
386 } /* }}} int enqueue_cache_item */
389 * tree_callback_flush:
390 * Called via `g_tree_foreach' in `queue_thread_main'. `cache_lock' is held
391 * while this is in progress.
393 static gboolean tree_callback_flush (gpointer key, gpointer value, /* {{{ */
397 callback_flush_data_t *cfd;
399 ci = (cache_item_t *) value;
400 cfd = (callback_flush_data_t *) data;
402 if (((cfd->now - ci->last_flush_time) >= config_write_interval)
403 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
404 && (ci->values_num > 0))
406 enqueue_cache_item (ci, TAIL);
408 else if (((cfd->now - ci->last_flush_time) >= config_flush_interval)
409 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
410 && (ci->values_num <= 0))
414 temp = (char **) realloc (cfd->keys,
415 sizeof (char *) * (cfd->keys_num + 1));
418 RRDD_LOG (LOG_ERR, "tree_callback_flush: realloc failed.");
422 /* Make really sure this points to the _same_ place */
423 assert ((char *) key == ci->file);
424 cfd->keys[cfd->keys_num] = (char *) key;
429 } /* }}} gboolean tree_callback_flush */
431 static void *queue_thread_main (void *args __attribute__((unused))) /* {{{ */
434 struct timespec next_flush;
436 gettimeofday (&now, NULL);
437 next_flush.tv_sec = now.tv_sec + config_flush_interval;
438 next_flush.tv_nsec = 1000 * now.tv_usec;
440 pthread_mutex_lock (&cache_lock);
441 while ((do_shutdown == 0) || (cache_queue_head != NULL))
450 /* First, check if it's time to do the cache flush. */
451 gettimeofday (&now, NULL);
452 if ((now.tv_sec > next_flush.tv_sec)
453 || ((now.tv_sec == next_flush.tv_sec)
454 && ((1000 * now.tv_usec) > next_flush.tv_nsec)))
456 callback_flush_data_t cfd;
459 memset (&cfd, 0, sizeof (cfd));
460 /* Pass the current time as user data so that we don't need to call
461 * `time' for each node. */
462 cfd.now = time (NULL);
466 /* `tree_callback_flush' will return the keys of all values that haven't
467 * been touched in the last `config_flush_interval' seconds in `cfd'.
468 * The char*'s in this array point to the same memory as ci->file, so we
469 * don't need to free them separately. */
470 g_tree_foreach (cache_tree, tree_callback_flush, (gpointer) &cfd);
472 for (k = 0; k < cfd.keys_num; k++)
474 /* This must not fail. */
475 ci = (cache_item_t *) g_tree_lookup (cache_tree, cfd.keys[k]);
478 /* If we end up here with values available, something's seriously
480 assert (ci->values_num == 0);
482 /* Remove the node from the tree */
483 g_tree_remove (cache_tree, cfd.keys[k]);
486 /* Now free and clean up `ci'. */
491 } /* for (k = 0; k < cfd.keys_num; k++) */
493 if (cfd.keys != NULL)
499 /* Determine the time of the next cache flush. */
500 while (next_flush.tv_sec < now.tv_sec)
501 next_flush.tv_sec += config_flush_interval;
504 /* Now, check if there's something to store away. If not, wait until
505 * something comes in or it's time to do the cache flush. */
506 if (cache_queue_head == NULL)
508 status = pthread_cond_timedwait (&cache_cond, &cache_lock, &next_flush);
509 if ((status != 0) && (status != ETIMEDOUT))
511 RRDD_LOG (LOG_ERR, "queue_thread_main: "
512 "pthread_cond_timedwait returned %i.", status);
516 /* Check if a value has arrived. This may be NULL if we timed out or there
517 * was an interrupt such as a signal. */
518 if (cache_queue_head == NULL)
521 ci = cache_queue_head;
523 /* copy the relevant parts */
524 file = strdup (ci->file);
527 RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
532 values_num = ci->values_num;
537 ci->last_flush_time = time (NULL);
538 ci->flags &= ~(CI_FLAGS_IN_QUEUE);
540 cache_queue_head = ci->next;
541 if (cache_queue_head == NULL)
542 cache_queue_tail = NULL;
545 pthread_mutex_lock (&stats_lock);
546 assert (stats_queue_length > 0);
547 stats_queue_length--;
548 pthread_mutex_unlock (&stats_lock);
550 pthread_mutex_unlock (&cache_lock);
552 RRDD_LOG (LOG_DEBUG, "queue_thread_main: rrd_update (%s, %i, %p)",
553 file, values_num, (void *) values);
555 status = rrd_update_r (file, NULL, values_num, (void *) values);
558 RRDD_LOG (LOG_ERR, "queue_thread_main: "
559 "rrd_update_r failed with status %i.",
564 for (i = 0; i < values_num; i++)
567 pthread_mutex_lock (&stats_lock);
568 stats_updates_written++;
569 stats_data_sets_written += values_num;
570 pthread_mutex_unlock (&stats_lock);
572 pthread_mutex_lock (&cache_lock);
573 pthread_cond_broadcast (&flush_cond);
574 } /* while (do_shutdown == 0) */
575 pthread_mutex_unlock (&cache_lock);
577 RRDD_LOG (LOG_DEBUG, "queue_thread_main: Exiting.");
580 } /* }}} void *queue_thread_main */
582 static int buffer_get_field (char **buffer_ret, /* {{{ */
583 size_t *buffer_size_ret, char **field_ret)
592 buffer = *buffer_ret;
594 buffer_size = *buffer_size_ret;
598 if (buffer_size <= 0)
601 /* This is ensured by `handle_request'. */
602 assert (buffer[buffer_size - 1] == ' ');
605 while (buffer_pos < buffer_size)
607 /* Check for end-of-field or end-of-buffer */
608 if (buffer[buffer_pos] == ' ')
610 field[field_size] = 0;
616 /* Handle escaped characters. */
617 else if (buffer[buffer_pos] == '\\')
619 if (buffer_pos >= (buffer_size - 1))
622 field[field_size] = buffer[buffer_pos];
626 /* Normal operation */
629 field[field_size] = buffer[buffer_pos];
633 } /* while (buffer_pos < buffer_size) */
638 *buffer_ret = buffer + buffer_pos;
639 *buffer_size_ret = buffer_size - buffer_pos;
643 } /* }}} int buffer_get_field */
645 static int flush_file (const char *filename) /* {{{ */
649 pthread_mutex_lock (&cache_lock);
651 ci = (cache_item_t *) g_tree_lookup (cache_tree, filename);
654 pthread_mutex_unlock (&cache_lock);
658 /* Enqueue at head */
659 enqueue_cache_item (ci, HEAD);
660 pthread_cond_signal (&cache_cond);
662 while ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
666 pthread_cond_wait (&flush_cond, &cache_lock);
668 ci = g_tree_lookup (cache_tree, filename);
671 RRDD_LOG (LOG_ERR, "flush_file: Tree node went away "
672 "while waiting for flush.");
673 pthread_mutex_unlock (&cache_lock);
678 pthread_mutex_unlock (&cache_lock);
680 } /* }}} int flush_file */
682 static int handle_request_help (int fd, /* {{{ */
683 char *buffer, size_t buffer_size)
687 size_t help_text_len;
693 "4 Command overview\n",
694 "FLUSH <filename>\n",
695 "HELP [<command>]\n",
696 "UPDATE <filename> <values> [<values> ...]\n",
699 size_t help_help_len = sizeof (help_help) / sizeof (help_help[0]);
703 "4 Help for FLUSH\n",
704 "Usage: FLUSH <filename>\n",
706 "Adds the given filename to the head of the update queue and returns\n",
707 "after is has been dequeued.\n"
709 size_t help_flush_len = sizeof (help_flush) / sizeof (help_flush[0]);
711 char *help_update[] =
713 "9 Help for UPDATE\n",
714 "Usage: UPDATE <filename> <values> [<values> ...]\n"
716 "Adds the given file to the internal cache if it is not yet known and\n",
717 "appends the given value(s) to the entry. See the rrdcached(1) manpage\n",
720 "Each <values> has the following form:\n",
721 " <values> = <time>:<value>[:<value>[...]]\n",
722 "See the rrdupdate(1) manpage for details.\n"
724 size_t help_update_len = sizeof (help_update) / sizeof (help_update[0]);
728 "4 Help for STATS\n",
731 "Returns some performance counters, see the rrdcached(1) manpage for\n",
732 "a description of the values.\n"
734 size_t help_stats_len = sizeof (help_stats) / sizeof (help_stats[0]);
736 status = buffer_get_field (&buffer, &buffer_size, &command);
739 help_text = help_help;
740 help_text_len = help_help_len;
744 if (strcasecmp (command, "update") == 0)
746 help_text = help_update;
747 help_text_len = help_update_len;
749 else if (strcasecmp (command, "flush") == 0)
751 help_text = help_flush;
752 help_text_len = help_flush_len;
754 else if (strcasecmp (command, "stats") == 0)
756 help_text = help_stats;
757 help_text_len = help_stats_len;
761 help_text = help_help;
762 help_text_len = help_help_len;
766 for (i = 0; i < help_text_len; i++)
768 status = swrite (fd, help_text[i], strlen (help_text[i]));
772 RRDD_LOG (LOG_ERR, "handle_request_help: swrite returned an error.");
778 } /* }}} int handle_request_help */
780 static int handle_request_stats (int fd, /* {{{ */
781 char *buffer __attribute__((unused)),
782 size_t buffer_size __attribute__((unused)))
787 uint64_t copy_queue_length;
788 uint64_t copy_updates_written;
789 uint64_t copy_data_sets_written;
791 uint64_t tree_nodes_number;
794 pthread_mutex_lock (&stats_lock);
795 copy_queue_length = stats_queue_length;
796 copy_updates_written = stats_updates_written;
797 copy_data_sets_written = stats_data_sets_written;
798 pthread_mutex_unlock (&stats_lock);
800 pthread_mutex_lock (&cache_lock);
801 tree_nodes_number = (uint64_t) g_tree_nnodes (cache_tree);
802 tree_depth = (uint64_t) g_tree_height (cache_tree);
803 pthread_mutex_unlock (&cache_lock);
805 #define RRDD_STATS_SEND \
806 outbuf[sizeof (outbuf) - 1] = 0; \
807 status = swrite (fd, outbuf, strlen (outbuf)); \
811 RRDD_LOG (LOG_INFO, "handle_request_stats: swrite returned an error."); \
815 strncpy (outbuf, "5 Statistics follow\n", sizeof (outbuf));
818 snprintf (outbuf, sizeof (outbuf),
819 "QueueLength: %"PRIu64"\n", copy_queue_length);
822 snprintf (outbuf, sizeof (outbuf),
823 "UpdatesWritten: %"PRIu64"\n", copy_updates_written);
826 snprintf (outbuf, sizeof (outbuf),
827 "DataSetsWritten: %"PRIu64"\n", copy_data_sets_written);
830 snprintf (outbuf, sizeof (outbuf),
831 "TreeNodesNumber: %"PRIu64"\n", tree_nodes_number);
834 snprintf (outbuf, sizeof (outbuf),
835 "TreeDepth: %"PRIu64"\n", tree_depth);
839 #undef RRDD_STATS_SEND
840 } /* }}} int handle_request_stats */
842 static int handle_request_flush (int fd, /* {{{ */
843 char *buffer, size_t buffer_size)
849 status = buffer_get_field (&buffer, &buffer_size, &file);
852 strncpy (result, "-1 Usage: flush <filename>\n", sizeof (result));
856 status = flush_file (file);
858 snprintf (result, sizeof (result), "0 Successfully flushed %s.\n", file);
859 else if (status == ENOENT)
860 snprintf (result, sizeof (result), "-1 No such file: %s.\n", file);
862 strncpy (result, "-1 Internal error.\n", sizeof (result));
864 snprintf (result, sizeof (result), "-1 Failed with status %i.\n", status);
866 result[sizeof (result) - 1] = 0;
868 status = swrite (fd, result, strlen (result));
872 RRDD_LOG (LOG_INFO, "handle_request_flush: swrite returned an error.");
877 } /* }}} int handle_request_flush */
879 static int handle_request_update (int fd, /* {{{ */
880 char *buffer, size_t buffer_size)
891 #define RRDD_UPDATE_SEND \
892 answer[sizeof (answer) - 1] = 0; \
893 status = swrite (fd, answer, strlen (answer)); \
897 RRDD_LOG (LOG_INFO, "handle_request_update: swrite returned an error."); \
903 status = buffer_get_field (&buffer, &buffer_size, &file);
906 strncpy (answer, "-1 Usage: UPDATE <filename> <values> [<values> ...]\n",
912 pthread_mutex_lock (&cache_lock);
914 ci = g_tree_lookup (cache_tree, file);
915 if (ci == NULL) /* {{{ */
917 ci = (cache_item_t *) malloc (sizeof (cache_item_t));
920 pthread_mutex_unlock (&cache_lock);
921 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
923 strncpy (answer, "-1 malloc failed.\n", sizeof (answer));
927 memset (ci, 0, sizeof (cache_item_t));
929 ci->file = strdup (file);
930 if (ci->file == NULL)
932 pthread_mutex_unlock (&cache_lock);
934 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
936 strncpy (answer, "-1 strdup failed.\n", sizeof (answer));
943 ci->last_flush_time = now;
944 ci->flags = CI_FLAGS_IN_TREE;
946 g_tree_insert (cache_tree, (void *) ci->file, (void *) ci);
948 RRDD_LOG (LOG_DEBUG, "handle_request_update: Created new tree node %s.",
953 while (buffer_size > 0)
958 status = buffer_get_field (&buffer, &buffer_size, &value);
961 RRDD_LOG (LOG_INFO, "handle_request_update: Error reading field.");
965 temp = (char **) realloc (ci->values,
966 sizeof (char *) * (ci->values_num + 1));
969 RRDD_LOG (LOG_ERR, "handle_request_update: realloc failed.");
974 ci->values[ci->values_num] = strdup (value);
975 if (ci->values[ci->values_num] == NULL)
977 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
985 if (((now - ci->last_flush_time) >= config_write_interval)
986 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
987 && (ci->values_num > 0))
989 enqueue_cache_item (ci, TAIL);
990 pthread_cond_signal (&cache_cond);
993 pthread_mutex_unlock (&cache_lock);
997 strncpy (answer, "-1 No values updated.\n", sizeof (answer));
1001 snprintf (answer, sizeof (answer), "0 Enqueued %i value%s\n", values_num,
1002 (values_num == 1) ? "" : "s");
1006 #undef RRDD_UPDATE_SEND
1007 } /* }}} int handle_request_update */
1009 static int handle_request (int fd) /* {{{ */
1017 status = (int) sread (fd, buffer, sizeof (buffer));
1022 else if (status < 0)
1024 RRDD_LOG (LOG_ERR, "handle_request: sread failed.");
1027 buffer_size = (size_t) status;
1028 assert (buffer_size <= sizeof (buffer));
1029 assert (buffer[buffer_size - 1] == 0);
1031 /* Place the normal field separator at the end to simplify
1032 * `buffer_get_field's work. */
1033 buffer[buffer_size - 1] = ' ';
1035 buffer_ptr = buffer;
1037 status = buffer_get_field (&buffer_ptr, &buffer_size, &command);
1040 RRDD_LOG (LOG_INFO, "handle_request: Unable parse command.");
1044 if (strcasecmp (command, "update") == 0)
1046 return (handle_request_update (fd, buffer_ptr, buffer_size));
1048 else if (strcasecmp (command, "flush") == 0)
1050 return (handle_request_flush (fd, buffer_ptr, buffer_size));
1052 else if (strcasecmp (command, "stats") == 0)
1054 return (handle_request_stats (fd, buffer_ptr, buffer_size));
1056 else if (strcasecmp (command, "help") == 0)
1058 return (handle_request_help (fd, buffer_ptr, buffer_size));
1064 snprintf (result, sizeof (result), "-1 Unknown command: %s\n", command);
1065 result[sizeof (result) - 1] = 0;
1067 status = swrite (fd, result, strlen (result));
1070 RRDD_LOG (LOG_ERR, "handle_request: swrite failed.");
1076 } /* }}} int handle_request */
1078 static void *connection_thread_main (void *args /* {{{ */
1079 __attribute__((unused)))
1085 fd = *((int *) args);
1087 pthread_mutex_lock (&connetion_threads_lock);
1091 temp = (pthread_t *) realloc (connetion_threads,
1092 sizeof (pthread_t) * (connetion_threads_num + 1));
1095 RRDD_LOG (LOG_ERR, "connection_thread_main: realloc failed.");
1099 connetion_threads = temp;
1100 connetion_threads[connetion_threads_num] = pthread_self ();
1101 connetion_threads_num++;
1104 pthread_mutex_unlock (&connetion_threads_lock);
1106 while (do_shutdown == 0)
1108 struct pollfd pollfd;
1112 pollfd.events = POLLIN | POLLPRI;
1115 status = poll (&pollfd, 1, /* timeout = */ 500);
1116 if (status == 0) /* timeout */
1118 else if (status < 0) /* error */
1121 if (status == EINTR)
1123 RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
1127 if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
1132 else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
1134 RRDD_LOG (LOG_WARNING, "connection_thread_main: "
1135 "poll(2) returned something unexpected: %#04hx",
1141 status = handle_request (fd);
1149 self = pthread_self ();
1150 /* Remove this thread from the connection threads list */
1151 pthread_mutex_lock (&connetion_threads_lock);
1152 /* Find out own index in the array */
1153 for (i = 0; i < connetion_threads_num; i++)
1154 if (pthread_equal (connetion_threads[i], self) != 0)
1156 assert (i < connetion_threads_num);
1158 /* Move the trailing threads forward. */
1159 if (i < (connetion_threads_num - 1))
1161 memmove (connetion_threads + i,
1162 connetion_threads + i + 1,
1163 sizeof (pthread_t) * (connetion_threads_num - i - 1));
1166 connetion_threads_num--;
1167 pthread_mutex_unlock (&connetion_threads_lock);
1171 } /* }}} void *connection_thread_main */
1173 static int open_listen_socket_unix (const char *path) /* {{{ */
1176 struct sockaddr_un sa;
1177 listen_socket_t *temp;
1180 temp = (listen_socket_t *) realloc (listen_fds,
1181 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1184 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: realloc failed.");
1188 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1190 fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
1193 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: socket(2) failed.");
1197 memset (&sa, 0, sizeof (sa));
1198 sa.sun_family = AF_UNIX;
1199 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
1201 status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
1204 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: bind(2) failed.");
1210 status = listen (fd, /* backlog = */ 10);
1213 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: listen(2) failed.");
1219 listen_fds[listen_fds_num].fd = fd;
1220 snprintf (listen_fds[listen_fds_num].path,
1221 sizeof (listen_fds[listen_fds_num].path) - 1,
1226 } /* }}} int open_listen_socket_unix */
1228 static int open_listen_socket (const char *addr) /* {{{ */
1230 struct addrinfo ai_hints;
1231 struct addrinfo *ai_res;
1232 struct addrinfo *ai_ptr;
1235 assert (addr != NULL);
1237 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
1238 return (open_listen_socket_unix (addr + strlen ("unix:")));
1239 else if (addr[0] == '/')
1240 return (open_listen_socket_unix (addr));
1242 memset (&ai_hints, 0, sizeof (ai_hints));
1243 ai_hints.ai_flags = 0;
1244 #ifdef AI_ADDRCONFIG
1245 ai_hints.ai_flags |= AI_ADDRCONFIG;
1247 ai_hints.ai_family = AF_UNSPEC;
1248 ai_hints.ai_socktype = SOCK_STREAM;
1251 status = getaddrinfo (addr, RRDCACHED_DEFAULT_PORT, &ai_hints, &ai_res);
1254 RRDD_LOG (LOG_ERR, "open_listen_socket: getaddrinfo(%s) failed: "
1255 "%s", addr, gai_strerror (status));
1259 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1262 listen_socket_t *temp;
1264 temp = (listen_socket_t *) realloc (listen_fds,
1265 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1268 RRDD_LOG (LOG_ERR, "open_listen_socket: realloc failed.");
1272 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1274 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1277 RRDD_LOG (LOG_ERR, "open_listen_socket: socket(2) failed.");
1281 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1284 RRDD_LOG (LOG_ERR, "open_listen_socket: bind(2) failed.");
1289 status = listen (fd, /* backlog = */ 10);
1292 RRDD_LOG (LOG_ERR, "open_listen_socket: listen(2) failed.");
1297 listen_fds[listen_fds_num].fd = fd;
1298 strncpy (listen_fds[listen_fds_num].path, addr,
1299 sizeof (listen_fds[listen_fds_num].path) - 1);
1301 } /* for (ai_ptr) */
1304 } /* }}} int open_listen_socket */
1306 static int close_listen_sockets (void) /* {{{ */
1310 for (i = 0; i < listen_fds_num; i++)
1312 close (listen_fds[i].fd);
1313 if (strncmp ("unix:", listen_fds[i].path, strlen ("unix:")) == 0)
1314 unlink (listen_fds[i].path + strlen ("unix:"));
1322 } /* }}} int close_listen_sockets */
1324 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
1326 struct pollfd *pollfds;
1331 for (i = 0; i < config_listen_address_list_len; i++)
1333 RRDD_LOG (LOG_DEBUG, "listen_thread_main: config_listen_address_list[%i] "
1334 "= %s", i, config_listen_address_list[i]);
1335 open_listen_socket (config_listen_address_list[i]);
1338 if (config_listen_address_list_len < 1)
1339 open_listen_socket (RRDCACHED_DEFAULT_ADDRESS);
1341 if (listen_fds_num < 1)
1343 RRDD_LOG (LOG_ERR, "listen_thread_main: No listen sockets "
1344 "could be opened. Sorry.");
1348 pollfds_num = listen_fds_num;
1349 pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
1350 if (pollfds == NULL)
1352 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1355 memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
1357 while (do_shutdown == 0)
1359 assert (pollfds_num == ((int) listen_fds_num));
1360 for (i = 0; i < pollfds_num; i++)
1362 pollfds[i].fd = listen_fds[i].fd;
1363 pollfds[i].events = POLLIN | POLLPRI;
1364 pollfds[i].revents = 0;
1367 status = poll (pollfds, pollfds_num, /* timeout = */ -1);
1371 if (status != EINTR)
1373 RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
1378 for (i = 0; i < pollfds_num; i++)
1381 struct sockaddr_storage client_sa;
1382 socklen_t client_sa_size;
1385 if (pollfds[i].revents == 0)
1388 if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
1390 RRDD_LOG (LOG_ERR, "listen_thread_main: "
1391 "poll(2) returned something unexpected for listen FD #%i.",
1396 client_sd = (int *) malloc (sizeof (int));
1397 if (client_sd == NULL)
1399 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1403 client_sa_size = sizeof (client_sa);
1404 *client_sd = accept (pollfds[i].fd,
1405 (struct sockaddr *) &client_sa, &client_sa_size);
1408 RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
1412 status = pthread_create (&tid, /* attr = */ NULL, connection_thread_main,
1413 /* args = */ (void *) client_sd);
1416 RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
1421 } /* for (pollfds_num) */
1422 } /* while (do_shutdown == 0) */
1424 close_listen_sockets ();
1426 pthread_mutex_lock (&connetion_threads_lock);
1427 while (connetion_threads_num > 0)
1431 wait_for = connetion_threads[0];
1433 pthread_mutex_unlock (&connetion_threads_lock);
1434 pthread_join (wait_for, /* retval = */ NULL);
1435 pthread_mutex_lock (&connetion_threads_lock);
1437 pthread_mutex_unlock (&connetion_threads_lock);
1439 RRDD_LOG (LOG_DEBUG, "listen_thread_main: Exiting.");
1442 } /* }}} void *listen_thread_main */
1444 static int daemonize (void) /* {{{ */
1450 /* These structures are static, because `sigaction' behaves weird if the are
1452 static struct sigaction sa_int;
1453 static struct sigaction sa_term;
1454 static struct sigaction sa_pipe;
1459 fprintf (stderr, "daemonize: fork(2) failed.\n");
1467 /* Change into the /tmp directory. */
1468 base_dir = (config_base_dir != NULL)
1471 status = chdir (base_dir);
1474 fprintf (stderr, "daemonize: chdir (%s) failed.\n", base_dir);
1478 /* Become session leader */
1481 /* Open the first three file descriptors to /dev/null */
1486 open ("/dev/null", O_RDWR);
1490 /* Install signal handlers */
1491 memset (&sa_int, 0, sizeof (sa_int));
1492 sa_int.sa_handler = sig_int_handler;
1493 sigaction (SIGINT, &sa_int, NULL);
1495 memset (&sa_term, 0, sizeof (sa_term));
1496 sa_term.sa_handler = sig_term_handler;
1497 sigaction (SIGINT, &sa_term, NULL);
1499 memset (&sa_pipe, 0, sizeof (sa_pipe));
1500 sa_pipe.sa_handler = SIG_IGN;
1501 sigaction (SIGPIPE, &sa_pipe, NULL);
1503 openlog ("rrdcached", LOG_PID, LOG_DAEMON);
1505 cache_tree = g_tree_new ((GCompareFunc) strcmp);
1506 if (cache_tree == NULL)
1508 RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
1512 memset (&queue_thread, 0, sizeof (queue_thread));
1513 status = pthread_create (&queue_thread, /* attr = */ NULL,
1514 queue_thread_main, /* args = */ NULL);
1517 RRDD_LOG (LOG_ERR, "daemonize: pthread_create failed.");
1524 } /* }}} int daemonize */
1526 static int cleanup (void) /* {{{ */
1528 RRDD_LOG (LOG_DEBUG, "cleanup ()");
1532 RRDD_LOG (LOG_DEBUG, "cleanup: Joining queue_thread..");
1533 pthread_cond_signal (&cache_cond);
1534 pthread_join (queue_thread, /* return = */ NULL);
1535 RRDD_LOG (LOG_DEBUG, "cleanup: done");
1542 } /* }}} int cleanup */
1544 static int read_options (int argc, char **argv) /* {{{ */
1549 while ((option = getopt(argc, argv, "l:f:w:b:p:h?")) != -1)
1557 temp = (char **) realloc (config_listen_address_list,
1558 sizeof (char *) * (config_listen_address_list_len + 1));
1561 fprintf (stderr, "read_options: realloc failed.\n");
1564 config_listen_address_list = temp;
1566 temp[config_listen_address_list_len] = strdup (optarg);
1567 if (temp[config_listen_address_list_len] == NULL)
1569 fprintf (stderr, "read_options: strdup failed.\n");
1572 config_listen_address_list_len++;
1580 temp = atoi (optarg);
1582 config_flush_interval = temp;
1585 fprintf (stderr, "Invalid flush interval: %s\n", optarg);
1595 temp = atoi (optarg);
1597 config_write_interval = temp;
1600 fprintf (stderr, "Invalid write interval: %s\n", optarg);
1610 if (config_base_dir != NULL)
1611 free (config_base_dir);
1612 config_base_dir = strdup (optarg);
1613 if (config_base_dir == NULL)
1615 fprintf (stderr, "read_options: strdup failed.\n");
1619 len = strlen (config_base_dir);
1620 while ((len > 0) && (config_base_dir[len - 1] == '/'))
1622 config_base_dir[len - 1] = 0;
1628 fprintf (stderr, "Invalid base directory: %s\n", optarg);
1636 if (config_pid_file != NULL)
1637 free (config_pid_file);
1638 config_pid_file = strdup (optarg);
1639 if (config_pid_file == NULL)
1641 fprintf (stderr, "read_options: strdup failed.\n");
1649 printf ("RRDd %s Copyright (C) 2008 Florian octo Forster\n"
1651 "Usage: rrdcached [options]\n"
1653 "Valid options are:\n"
1654 " -l <address> Socket address to listen to.\n"
1655 " -w <seconds> Interval in which to write data.\n"
1656 " -f <seconds> Interval in which to flush dead data.\n"
1657 " -p <file> Location of the PID-file.\n"
1658 " -b <dir> Base directory to change to.\n"
1660 "For more information and a detailed description of all options "
1662 "to the rrdcached(1) manual page.\n",
1666 } /* switch (option) */
1667 } /* while (getopt) */
1670 } /* }}} int read_options */
1672 int main (int argc, char **argv)
1676 status = read_options (argc, argv);
1684 status = daemonize ();
1687 struct sigaction sigchld;
1689 memset (&sigchld, 0, sizeof (sigchld));
1690 sigchld.sa_handler = SIG_IGN;
1691 sigaction (SIGCHLD, &sigchld, NULL);
1695 else if (status != 0)
1697 fprintf (stderr, "daemonize failed, exiting.\n");
1701 listen_thread_main (NULL);
1709 * vim: set sw=2 sts=2 ts=8 et fdm=marker :