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
129 typedef struct callback_flush_data_s callback_flush_data_t;
136 typedef enum queue_side_e queue_side_t;
141 static listen_socket_t *listen_fds = NULL;
142 static size_t listen_fds_num = 0;
144 static int do_shutdown = 0;
146 static pthread_t queue_thread;
148 static pthread_t *connetion_threads = NULL;
149 static pthread_mutex_t connetion_threads_lock = PTHREAD_MUTEX_INITIALIZER;
150 static int connetion_threads_num = 0;
153 static GTree *cache_tree = NULL;
154 static cache_item_t *cache_queue_head = NULL;
155 static cache_item_t *cache_queue_tail = NULL;
156 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
157 static pthread_cond_t cache_cond = PTHREAD_COND_INITIALIZER;
159 static pthread_cond_t flush_cond = PTHREAD_COND_INITIALIZER;
161 static int config_write_interval = 300;
162 static int config_flush_interval = 3600;
163 static char *config_pid_file = NULL;
164 static char *config_base_dir = NULL;
166 static char **config_listen_address_list = NULL;
167 static int config_listen_address_list_len = 0;
169 static uint64_t stats_queue_length = 0;
170 static uint64_t stats_updates_written = 0;
171 static uint64_t stats_data_sets_written = 0;
172 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
177 static void sig_int_handler (int s __attribute__((unused))) /* {{{ */
180 } /* }}} void sig_int_handler */
182 static void sig_term_handler (int s __attribute__((unused))) /* {{{ */
185 } /* }}} void sig_term_handler */
187 static int write_pidfile (void) /* {{{ */
195 file = (config_pid_file != NULL)
197 : LOCALSTATEDIR "/run/rrdcached.pid";
199 fh = fopen (file, "w");
202 RRDD_LOG (LOG_ERR, "write_pidfile: Opening `%s' failed.", file);
206 fprintf (fh, "%i\n", (int) pid);
210 } /* }}} int write_pidfile */
212 static int remove_pidfile (void) /* {{{ */
217 file = (config_pid_file != NULL)
219 : LOCALSTATEDIR "/run/rrdcached.pid";
221 status = unlink (file);
225 } /* }}} int remove_pidfile */
227 static ssize_t sread (int fd, void *buffer_void, size_t buffer_size) /* {{{ */
234 buffer = (char *) buffer_void;
236 buffer_free = buffer_size;
238 while (buffer_free > 0)
240 status = read (fd, buffer + buffer_used, buffer_free);
241 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
250 assert ((0 > status) || (buffer_free >= (size_t) status));
252 buffer_free = buffer_free - status;
253 buffer_used = buffer_used + status;
255 if (buffer[buffer_used - 1] == '\n')
259 assert (buffer_used > 0);
261 if (buffer[buffer_used - 1] != '\n')
267 buffer[buffer_used - 1] = 0;
269 /* Fix network line endings. */
270 if ((buffer_used > 1) && (buffer[buffer_used - 2] == '\r'))
273 buffer[buffer_used - 1] = 0;
276 return (buffer_used);
277 } /* }}} ssize_t sread */
279 static ssize_t swrite (int fd, const void *buf, size_t count) /* {{{ */
285 ptr = (const char *) buf;
290 status = write (fd, (const void *) ptr, nleft);
292 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
298 nleft = nleft - status;
303 } /* }}} ssize_t swrite */
306 * enqueue_cache_item:
307 * `cache_lock' must be acquired before calling this function!
309 static int enqueue_cache_item (cache_item_t *ci, /* {{{ */
317 if (ci->values_num == 0)
322 if ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
324 assert (ci->next == NULL);
325 ci->next = cache_queue_head;
326 cache_queue_head = ci;
328 if (cache_queue_tail == NULL)
329 cache_queue_tail = cache_queue_head;
333 else if (cache_queue_head == ci)
337 else /* enqueued, but not first entry */
341 /* find previous entry */
342 for (prev = cache_queue_head; prev != NULL; prev = prev->next)
343 if (prev->next == ci)
345 assert (prev != NULL);
347 /* move to the front */
348 prev->next = ci->next;
349 ci->next = cache_queue_head;
350 cache_queue_head = ci;
352 /* check if we need to adapt the tail */
353 if (cache_queue_tail == ci)
354 cache_queue_tail = prev;
357 else /* (side == TAIL) */
359 /* We don't move values back in the list.. */
360 if ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
363 assert (ci->next == NULL);
365 if (cache_queue_tail == NULL)
366 cache_queue_head = ci;
368 cache_queue_tail->next = ci;
369 cache_queue_tail = ci;
374 ci->flags |= CI_FLAGS_IN_QUEUE;
378 pthread_mutex_lock (&stats_lock);
379 stats_queue_length++;
380 pthread_mutex_unlock (&stats_lock);
384 } /* }}} int enqueue_cache_item */
387 * tree_callback_flush:
388 * Called via `g_tree_foreach' in `queue_thread_main'. `cache_lock' is held
389 * while this is in progress.
391 static gboolean tree_callback_flush (gpointer key, gpointer value, /* {{{ */
395 callback_flush_data_t *cfd;
397 ci = (cache_item_t *) value;
398 cfd = (callback_flush_data_t *) data;
400 if ((ci->last_flush_time <= cfd->abs_timeout)
401 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
402 && (ci->values_num > 0))
404 enqueue_cache_item (ci, TAIL);
406 else if ((do_shutdown != 0)
407 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
408 && (ci->values_num > 0))
410 enqueue_cache_item (ci, TAIL);
412 else if (((cfd->now - ci->last_flush_time) >= config_flush_interval)
413 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
414 && (ci->values_num <= 0))
418 temp = (char **) realloc (cfd->keys,
419 sizeof (char *) * (cfd->keys_num + 1));
422 RRDD_LOG (LOG_ERR, "tree_callback_flush: realloc failed.");
426 /* Make really sure this points to the _same_ place */
427 assert ((char *) key == ci->file);
428 cfd->keys[cfd->keys_num] = (char *) key;
433 } /* }}} gboolean tree_callback_flush */
435 static int flush_old_values (int max_age)
437 callback_flush_data_t cfd;
440 memset (&cfd, 0, sizeof (cfd));
441 /* Pass the current time as user data so that we don't need to call
442 * `time' for each node. */
443 cfd.now = time (NULL);
448 cfd.abs_timeout = cfd.now - max_age;
450 cfd.abs_timeout = cfd.now + 1;
452 /* `tree_callback_flush' will return the keys of all values that haven't
453 * been touched in the last `config_flush_interval' seconds in `cfd'.
454 * The char*'s in this array point to the same memory as ci->file, so we
455 * don't need to free them separately. */
456 g_tree_foreach (cache_tree, tree_callback_flush, (gpointer) &cfd);
458 for (k = 0; k < cfd.keys_num; k++)
462 /* This must not fail. */
463 ci = (cache_item_t *) g_tree_lookup (cache_tree, cfd.keys[k]);
466 /* If we end up here with values available, something's seriously
468 assert (ci->values_num == 0);
470 /* Remove the node from the tree */
471 g_tree_remove (cache_tree, cfd.keys[k]);
474 /* Now free and clean up `ci'. */
479 } /* for (k = 0; k < cfd.keys_num; k++) */
481 if (cfd.keys != NULL)
488 } /* int flush_old_values */
490 static void *queue_thread_main (void *args __attribute__((unused))) /* {{{ */
493 struct timespec next_flush;
495 gettimeofday (&now, NULL);
496 next_flush.tv_sec = now.tv_sec + config_flush_interval;
497 next_flush.tv_nsec = 1000 * now.tv_usec;
499 pthread_mutex_lock (&cache_lock);
500 while ((do_shutdown == 0) || (cache_queue_head != NULL))
509 /* First, check if it's time to do the cache flush. */
510 gettimeofday (&now, NULL);
511 if ((now.tv_sec > next_flush.tv_sec)
512 || ((now.tv_sec == next_flush.tv_sec)
513 && ((1000 * now.tv_usec) > next_flush.tv_nsec)))
515 /* Flush all values that haven't been written in the last
516 * `config_write_interval' seconds. */
517 flush_old_values (config_write_interval);
519 /* Determine the time of the next cache flush. */
520 while (next_flush.tv_sec < now.tv_sec)
521 next_flush.tv_sec += config_flush_interval;
524 /* Now, check if there's something to store away. If not, wait until
525 * something comes in or it's time to do the cache flush. */
526 if (cache_queue_head == NULL)
528 status = pthread_cond_timedwait (&cache_cond, &cache_lock, &next_flush);
529 if ((status != 0) && (status != ETIMEDOUT))
531 RRDD_LOG (LOG_ERR, "queue_thread_main: "
532 "pthread_cond_timedwait returned %i.", status);
536 /* We're about to shut down, so lets flush the entire tree. */
537 if ((do_shutdown != 0) && (cache_queue_head == NULL))
538 flush_old_values (/* max age = */ -1);
540 /* Check if a value has arrived. This may be NULL if we timed out or there
541 * was an interrupt such as a signal. */
542 if (cache_queue_head == NULL)
545 ci = cache_queue_head;
547 /* copy the relevant parts */
548 file = strdup (ci->file);
551 RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
556 values_num = ci->values_num;
561 ci->last_flush_time = time (NULL);
562 ci->flags &= ~(CI_FLAGS_IN_QUEUE);
564 cache_queue_head = ci->next;
565 if (cache_queue_head == NULL)
566 cache_queue_tail = NULL;
569 pthread_mutex_lock (&stats_lock);
570 assert (stats_queue_length > 0);
571 stats_queue_length--;
572 pthread_mutex_unlock (&stats_lock);
574 pthread_mutex_unlock (&cache_lock);
576 status = rrd_update_r (file, NULL, values_num, (void *) values);
579 RRDD_LOG (LOG_ERR, "queue_thread_main: "
580 "rrd_update_r failed with status %i.",
585 for (i = 0; i < values_num; i++)
590 pthread_mutex_lock (&stats_lock);
591 stats_updates_written++;
592 stats_data_sets_written += values_num;
593 pthread_mutex_unlock (&stats_lock);
596 pthread_mutex_lock (&cache_lock);
597 pthread_cond_broadcast (&flush_cond);
599 /* We're about to shut down, so lets flush the entire tree. */
600 if ((do_shutdown != 0) && (cache_queue_head == NULL))
601 flush_old_values (/* max age = */ -1);
602 } /* while ((do_shutdown == 0) || (cache_queue_head != NULL)) */
603 pthread_mutex_unlock (&cache_lock);
606 } /* }}} void *queue_thread_main */
608 static int buffer_get_field (char **buffer_ret, /* {{{ */
609 size_t *buffer_size_ret, char **field_ret)
618 buffer = *buffer_ret;
620 buffer_size = *buffer_size_ret;
624 if (buffer_size <= 0)
627 /* This is ensured by `handle_request'. */
628 assert (buffer[buffer_size - 1] == ' ');
631 while (buffer_pos < buffer_size)
633 /* Check for end-of-field or end-of-buffer */
634 if (buffer[buffer_pos] == ' ')
636 field[field_size] = 0;
642 /* Handle escaped characters. */
643 else if (buffer[buffer_pos] == '\\')
645 if (buffer_pos >= (buffer_size - 1))
648 field[field_size] = buffer[buffer_pos];
652 /* Normal operation */
655 field[field_size] = buffer[buffer_pos];
659 } /* while (buffer_pos < buffer_size) */
664 *buffer_ret = buffer + buffer_pos;
665 *buffer_size_ret = buffer_size - buffer_pos;
669 } /* }}} int buffer_get_field */
671 static int flush_file (const char *filename) /* {{{ */
675 pthread_mutex_lock (&cache_lock);
677 ci = (cache_item_t *) g_tree_lookup (cache_tree, filename);
680 pthread_mutex_unlock (&cache_lock);
684 /* Enqueue at head */
685 enqueue_cache_item (ci, HEAD);
686 pthread_cond_signal (&cache_cond);
688 while ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
692 pthread_cond_wait (&flush_cond, &cache_lock);
694 ci = g_tree_lookup (cache_tree, filename);
697 RRDD_LOG (LOG_ERR, "flush_file: Tree node went away "
698 "while waiting for flush.");
699 pthread_mutex_unlock (&cache_lock);
704 pthread_mutex_unlock (&cache_lock);
706 } /* }}} int flush_file */
708 static int handle_request_help (int fd, /* {{{ */
709 char *buffer, size_t buffer_size)
713 size_t help_text_len;
719 "4 Command overview\n",
720 "FLUSH <filename>\n",
721 "HELP [<command>]\n",
722 "UPDATE <filename> <values> [<values> ...]\n",
725 size_t help_help_len = sizeof (help_help) / sizeof (help_help[0]);
729 "4 Help for FLUSH\n",
730 "Usage: FLUSH <filename>\n",
732 "Adds the given filename to the head of the update queue and returns\n",
733 "after is has been dequeued.\n"
735 size_t help_flush_len = sizeof (help_flush) / sizeof (help_flush[0]);
737 char *help_update[] =
739 "9 Help for UPDATE\n",
740 "Usage: UPDATE <filename> <values> [<values> ...]\n"
742 "Adds the given file to the internal cache if it is not yet known and\n",
743 "appends the given value(s) to the entry. See the rrdcached(1) manpage\n",
746 "Each <values> has the following form:\n",
747 " <values> = <time>:<value>[:<value>[...]]\n",
748 "See the rrdupdate(1) manpage for details.\n"
750 size_t help_update_len = sizeof (help_update) / sizeof (help_update[0]);
754 "4 Help for STATS\n",
757 "Returns some performance counters, see the rrdcached(1) manpage for\n",
758 "a description of the values.\n"
760 size_t help_stats_len = sizeof (help_stats) / sizeof (help_stats[0]);
762 status = buffer_get_field (&buffer, &buffer_size, &command);
765 help_text = help_help;
766 help_text_len = help_help_len;
770 if (strcasecmp (command, "update") == 0)
772 help_text = help_update;
773 help_text_len = help_update_len;
775 else if (strcasecmp (command, "flush") == 0)
777 help_text = help_flush;
778 help_text_len = help_flush_len;
780 else if (strcasecmp (command, "stats") == 0)
782 help_text = help_stats;
783 help_text_len = help_stats_len;
787 help_text = help_help;
788 help_text_len = help_help_len;
792 for (i = 0; i < help_text_len; i++)
794 status = swrite (fd, help_text[i], strlen (help_text[i]));
798 RRDD_LOG (LOG_ERR, "handle_request_help: swrite returned an error.");
804 } /* }}} int handle_request_help */
806 static int handle_request_stats (int fd, /* {{{ */
807 char *buffer __attribute__((unused)),
808 size_t buffer_size __attribute__((unused)))
813 uint64_t copy_queue_length;
814 uint64_t copy_updates_written;
815 uint64_t copy_data_sets_written;
817 uint64_t tree_nodes_number;
820 pthread_mutex_lock (&stats_lock);
821 copy_queue_length = stats_queue_length;
822 copy_updates_written = stats_updates_written;
823 copy_data_sets_written = stats_data_sets_written;
824 pthread_mutex_unlock (&stats_lock);
826 pthread_mutex_lock (&cache_lock);
827 tree_nodes_number = (uint64_t) g_tree_nnodes (cache_tree);
828 tree_depth = (uint64_t) g_tree_height (cache_tree);
829 pthread_mutex_unlock (&cache_lock);
831 #define RRDD_STATS_SEND \
832 outbuf[sizeof (outbuf) - 1] = 0; \
833 status = swrite (fd, outbuf, strlen (outbuf)); \
837 RRDD_LOG (LOG_INFO, "handle_request_stats: swrite returned an error."); \
841 strncpy (outbuf, "5 Statistics follow\n", sizeof (outbuf));
844 snprintf (outbuf, sizeof (outbuf),
845 "QueueLength: %"PRIu64"\n", copy_queue_length);
848 snprintf (outbuf, sizeof (outbuf),
849 "UpdatesWritten: %"PRIu64"\n", copy_updates_written);
852 snprintf (outbuf, sizeof (outbuf),
853 "DataSetsWritten: %"PRIu64"\n", copy_data_sets_written);
856 snprintf (outbuf, sizeof (outbuf),
857 "TreeNodesNumber: %"PRIu64"\n", tree_nodes_number);
860 snprintf (outbuf, sizeof (outbuf),
861 "TreeDepth: %"PRIu64"\n", tree_depth);
865 #undef RRDD_STATS_SEND
866 } /* }}} int handle_request_stats */
868 static int handle_request_flush (int fd, /* {{{ */
869 char *buffer, size_t buffer_size)
875 status = buffer_get_field (&buffer, &buffer_size, &file);
878 strncpy (result, "-1 Usage: flush <filename>\n", sizeof (result));
882 status = flush_file (file);
884 snprintf (result, sizeof (result), "0 Successfully flushed %s.\n", file);
885 else if (status == ENOENT)
886 snprintf (result, sizeof (result), "-1 No such file: %s.\n", file);
888 strncpy (result, "-1 Internal error.\n", sizeof (result));
890 snprintf (result, sizeof (result), "-1 Failed with status %i.\n", status);
892 result[sizeof (result) - 1] = 0;
894 status = swrite (fd, result, strlen (result));
898 RRDD_LOG (LOG_INFO, "handle_request_flush: swrite returned an error.");
903 } /* }}} int handle_request_flush */
905 static int handle_request_update (int fd, /* {{{ */
906 char *buffer, size_t buffer_size)
917 #define RRDD_UPDATE_SEND \
918 answer[sizeof (answer) - 1] = 0; \
919 status = swrite (fd, answer, strlen (answer)); \
923 RRDD_LOG (LOG_INFO, "handle_request_update: swrite returned an error."); \
929 status = buffer_get_field (&buffer, &buffer_size, &file);
932 strncpy (answer, "-1 Usage: UPDATE <filename> <values> [<values> ...]\n",
938 pthread_mutex_lock (&cache_lock);
940 ci = g_tree_lookup (cache_tree, file);
941 if (ci == NULL) /* {{{ */
945 memset (&statbuf, 0, sizeof (statbuf));
946 status = stat (file, &statbuf);
949 pthread_mutex_unlock (&cache_lock);
950 RRDD_LOG (LOG_ERR, "handle_request_update: stat (%s) failed.", file);
953 if (status == ENOENT)
954 snprintf (answer, sizeof (answer), "-1 No such file: %s", file);
956 snprintf (answer, sizeof (answer), "-1 stat failed with error %i.\n",
961 if (!S_ISREG (statbuf.st_mode))
963 pthread_mutex_unlock (&cache_lock);
965 snprintf (answer, sizeof (answer), "-1 Not a regular file: %s", file);
970 ci = (cache_item_t *) malloc (sizeof (cache_item_t));
973 pthread_mutex_unlock (&cache_lock);
974 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
976 strncpy (answer, "-1 malloc failed.\n", sizeof (answer));
980 memset (ci, 0, sizeof (cache_item_t));
982 ci->file = strdup (file);
983 if (ci->file == NULL)
985 pthread_mutex_unlock (&cache_lock);
987 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
989 strncpy (answer, "-1 strdup failed.\n", sizeof (answer));
996 ci->last_flush_time = now;
997 ci->flags = CI_FLAGS_IN_TREE;
999 g_tree_insert (cache_tree, (void *) ci->file, (void *) ci);
1001 assert (ci != NULL);
1003 while (buffer_size > 0)
1008 status = buffer_get_field (&buffer, &buffer_size, &value);
1011 RRDD_LOG (LOG_INFO, "handle_request_update: Error reading field.");
1015 temp = (char **) realloc (ci->values,
1016 sizeof (char *) * (ci->values_num + 1));
1019 RRDD_LOG (LOG_ERR, "handle_request_update: realloc failed.");
1024 ci->values[ci->values_num] = strdup (value);
1025 if (ci->values[ci->values_num] == NULL)
1027 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
1035 if (((now - ci->last_flush_time) >= config_write_interval)
1036 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
1037 && (ci->values_num > 0))
1039 enqueue_cache_item (ci, TAIL);
1040 pthread_cond_signal (&cache_cond);
1043 pthread_mutex_unlock (&cache_lock);
1047 strncpy (answer, "-1 No values updated.\n", sizeof (answer));
1051 snprintf (answer, sizeof (answer), "0 Enqueued %i value%s\n", values_num,
1052 (values_num == 1) ? "" : "s");
1056 #undef RRDD_UPDATE_SEND
1057 } /* }}} int handle_request_update */
1059 static int handle_request (int fd) /* {{{ */
1067 status = (int) sread (fd, buffer, sizeof (buffer));
1072 else if (status < 0)
1074 RRDD_LOG (LOG_ERR, "handle_request: sread failed.");
1077 buffer_size = (size_t) status;
1078 assert (buffer_size <= sizeof (buffer));
1079 assert (buffer[buffer_size - 1] == 0);
1081 /* Place the normal field separator at the end to simplify
1082 * `buffer_get_field's work. */
1083 buffer[buffer_size - 1] = ' ';
1085 buffer_ptr = buffer;
1087 status = buffer_get_field (&buffer_ptr, &buffer_size, &command);
1090 RRDD_LOG (LOG_INFO, "handle_request: Unable parse command.");
1094 if (strcasecmp (command, "update") == 0)
1096 return (handle_request_update (fd, buffer_ptr, buffer_size));
1098 else if (strcasecmp (command, "flush") == 0)
1100 return (handle_request_flush (fd, buffer_ptr, buffer_size));
1102 else if (strcasecmp (command, "stats") == 0)
1104 return (handle_request_stats (fd, buffer_ptr, buffer_size));
1106 else if (strcasecmp (command, "help") == 0)
1108 return (handle_request_help (fd, buffer_ptr, buffer_size));
1114 snprintf (result, sizeof (result), "-1 Unknown command: %s\n", command);
1115 result[sizeof (result) - 1] = 0;
1117 status = swrite (fd, result, strlen (result));
1120 RRDD_LOG (LOG_ERR, "handle_request: swrite failed.");
1126 } /* }}} int handle_request */
1128 static void *connection_thread_main (void *args /* {{{ */
1129 __attribute__((unused)))
1135 fd = *((int *) args);
1137 pthread_mutex_lock (&connetion_threads_lock);
1141 temp = (pthread_t *) realloc (connetion_threads,
1142 sizeof (pthread_t) * (connetion_threads_num + 1));
1145 RRDD_LOG (LOG_ERR, "connection_thread_main: realloc failed.");
1149 connetion_threads = temp;
1150 connetion_threads[connetion_threads_num] = pthread_self ();
1151 connetion_threads_num++;
1154 pthread_mutex_unlock (&connetion_threads_lock);
1156 while (do_shutdown == 0)
1158 struct pollfd pollfd;
1162 pollfd.events = POLLIN | POLLPRI;
1165 status = poll (&pollfd, 1, /* timeout = */ 500);
1166 if (status == 0) /* timeout */
1168 else if (status < 0) /* error */
1171 if (status == EINTR)
1173 RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
1177 if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
1182 else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
1184 RRDD_LOG (LOG_WARNING, "connection_thread_main: "
1185 "poll(2) returned something unexpected: %#04hx",
1191 status = handle_request (fd);
1199 self = pthread_self ();
1200 /* Remove this thread from the connection threads list */
1201 pthread_mutex_lock (&connetion_threads_lock);
1202 /* Find out own index in the array */
1203 for (i = 0; i < connetion_threads_num; i++)
1204 if (pthread_equal (connetion_threads[i], self) != 0)
1206 assert (i < connetion_threads_num);
1208 /* Move the trailing threads forward. */
1209 if (i < (connetion_threads_num - 1))
1211 memmove (connetion_threads + i,
1212 connetion_threads + i + 1,
1213 sizeof (pthread_t) * (connetion_threads_num - i - 1));
1216 connetion_threads_num--;
1217 pthread_mutex_unlock (&connetion_threads_lock);
1221 } /* }}} void *connection_thread_main */
1223 static int open_listen_socket_unix (const char *path) /* {{{ */
1226 struct sockaddr_un sa;
1227 listen_socket_t *temp;
1230 temp = (listen_socket_t *) realloc (listen_fds,
1231 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1234 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: realloc failed.");
1238 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1240 fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
1243 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: socket(2) failed.");
1247 memset (&sa, 0, sizeof (sa));
1248 sa.sun_family = AF_UNIX;
1249 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
1251 status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
1254 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: bind(2) failed.");
1260 status = listen (fd, /* backlog = */ 10);
1263 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: listen(2) failed.");
1269 listen_fds[listen_fds_num].fd = fd;
1270 snprintf (listen_fds[listen_fds_num].path,
1271 sizeof (listen_fds[listen_fds_num].path) - 1,
1276 } /* }}} int open_listen_socket_unix */
1278 static int open_listen_socket (const char *addr) /* {{{ */
1280 struct addrinfo ai_hints;
1281 struct addrinfo *ai_res;
1282 struct addrinfo *ai_ptr;
1285 assert (addr != NULL);
1287 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
1288 return (open_listen_socket_unix (addr + strlen ("unix:")));
1289 else if (addr[0] == '/')
1290 return (open_listen_socket_unix (addr));
1292 memset (&ai_hints, 0, sizeof (ai_hints));
1293 ai_hints.ai_flags = 0;
1294 #ifdef AI_ADDRCONFIG
1295 ai_hints.ai_flags |= AI_ADDRCONFIG;
1297 ai_hints.ai_family = AF_UNSPEC;
1298 ai_hints.ai_socktype = SOCK_STREAM;
1301 status = getaddrinfo (addr, RRDCACHED_DEFAULT_PORT, &ai_hints, &ai_res);
1304 RRDD_LOG (LOG_ERR, "open_listen_socket: getaddrinfo(%s) failed: "
1305 "%s", addr, gai_strerror (status));
1309 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1312 listen_socket_t *temp;
1314 temp = (listen_socket_t *) realloc (listen_fds,
1315 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1318 RRDD_LOG (LOG_ERR, "open_listen_socket: realloc failed.");
1322 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1324 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1327 RRDD_LOG (LOG_ERR, "open_listen_socket: socket(2) failed.");
1331 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1334 RRDD_LOG (LOG_ERR, "open_listen_socket: bind(2) failed.");
1339 status = listen (fd, /* backlog = */ 10);
1342 RRDD_LOG (LOG_ERR, "open_listen_socket: listen(2) failed.");
1347 listen_fds[listen_fds_num].fd = fd;
1348 strncpy (listen_fds[listen_fds_num].path, addr,
1349 sizeof (listen_fds[listen_fds_num].path) - 1);
1351 } /* for (ai_ptr) */
1354 } /* }}} int open_listen_socket */
1356 static int close_listen_sockets (void) /* {{{ */
1360 for (i = 0; i < listen_fds_num; i++)
1362 close (listen_fds[i].fd);
1363 if (strncmp ("unix:", listen_fds[i].path, strlen ("unix:")) == 0)
1364 unlink (listen_fds[i].path + strlen ("unix:"));
1372 } /* }}} int close_listen_sockets */
1374 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
1376 struct pollfd *pollfds;
1381 for (i = 0; i < config_listen_address_list_len; i++)
1382 open_listen_socket (config_listen_address_list[i]);
1384 if (config_listen_address_list_len < 1)
1385 open_listen_socket (RRDCACHED_DEFAULT_ADDRESS);
1387 if (listen_fds_num < 1)
1389 RRDD_LOG (LOG_ERR, "listen_thread_main: No listen sockets "
1390 "could be opened. Sorry.");
1394 pollfds_num = listen_fds_num;
1395 pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
1396 if (pollfds == NULL)
1398 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1401 memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
1403 while (do_shutdown == 0)
1405 assert (pollfds_num == ((int) listen_fds_num));
1406 for (i = 0; i < pollfds_num; i++)
1408 pollfds[i].fd = listen_fds[i].fd;
1409 pollfds[i].events = POLLIN | POLLPRI;
1410 pollfds[i].revents = 0;
1413 status = poll (pollfds, pollfds_num, /* timeout = */ -1);
1417 if (status != EINTR)
1419 RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
1424 for (i = 0; i < pollfds_num; i++)
1427 struct sockaddr_storage client_sa;
1428 socklen_t client_sa_size;
1430 pthread_attr_t attr;
1432 if (pollfds[i].revents == 0)
1435 if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
1437 RRDD_LOG (LOG_ERR, "listen_thread_main: "
1438 "poll(2) returned something unexpected for listen FD #%i.",
1443 client_sd = (int *) malloc (sizeof (int));
1444 if (client_sd == NULL)
1446 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1450 client_sa_size = sizeof (client_sa);
1451 *client_sd = accept (pollfds[i].fd,
1452 (struct sockaddr *) &client_sa, &client_sa_size);
1455 RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
1459 pthread_attr_init (&attr);
1460 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
1462 status = pthread_create (&tid, &attr, connection_thread_main,
1463 /* args = */ (void *) client_sd);
1466 RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
1471 } /* for (pollfds_num) */
1472 } /* while (do_shutdown == 0) */
1474 close_listen_sockets ();
1476 pthread_mutex_lock (&connetion_threads_lock);
1477 while (connetion_threads_num > 0)
1481 wait_for = connetion_threads[0];
1483 pthread_mutex_unlock (&connetion_threads_lock);
1484 pthread_join (wait_for, /* retval = */ NULL);
1485 pthread_mutex_lock (&connetion_threads_lock);
1487 pthread_mutex_unlock (&connetion_threads_lock);
1490 } /* }}} void *listen_thread_main */
1492 static int daemonize (void) /* {{{ */
1498 /* These structures are static, because `sigaction' behaves weird if the are
1500 static struct sigaction sa_int;
1501 static struct sigaction sa_term;
1502 static struct sigaction sa_pipe;
1507 fprintf (stderr, "daemonize: fork(2) failed.\n");
1515 /* Change into the /tmp directory. */
1516 base_dir = (config_base_dir != NULL)
1519 status = chdir (base_dir);
1522 fprintf (stderr, "daemonize: chdir (%s) failed.\n", base_dir);
1526 /* Become session leader */
1529 /* Open the first three file descriptors to /dev/null */
1534 open ("/dev/null", O_RDWR);
1538 /* Install signal handlers */
1539 memset (&sa_int, 0, sizeof (sa_int));
1540 sa_int.sa_handler = sig_int_handler;
1541 sigaction (SIGINT, &sa_int, NULL);
1543 memset (&sa_term, 0, sizeof (sa_term));
1544 sa_term.sa_handler = sig_term_handler;
1545 sigaction (SIGTERM, &sa_term, NULL);
1547 memset (&sa_pipe, 0, sizeof (sa_pipe));
1548 sa_pipe.sa_handler = SIG_IGN;
1549 sigaction (SIGPIPE, &sa_pipe, NULL);
1551 openlog ("rrdcached", LOG_PID, LOG_DAEMON);
1553 cache_tree = g_tree_new ((GCompareFunc) strcmp);
1554 if (cache_tree == NULL)
1556 RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
1560 memset (&queue_thread, 0, sizeof (queue_thread));
1561 status = pthread_create (&queue_thread, /* attr = */ NULL,
1562 queue_thread_main, /* args = */ NULL);
1565 RRDD_LOG (LOG_ERR, "daemonize: pthread_create failed.");
1572 } /* }}} int daemonize */
1574 static int cleanup (void) /* {{{ */
1578 pthread_cond_signal (&cache_cond);
1579 pthread_join (queue_thread, /* return = */ NULL);
1586 } /* }}} int cleanup */
1588 static int read_options (int argc, char **argv) /* {{{ */
1593 while ((option = getopt(argc, argv, "l:f:w:b:p:h?")) != -1)
1601 temp = (char **) realloc (config_listen_address_list,
1602 sizeof (char *) * (config_listen_address_list_len + 1));
1605 fprintf (stderr, "read_options: realloc failed.\n");
1608 config_listen_address_list = temp;
1610 temp[config_listen_address_list_len] = strdup (optarg);
1611 if (temp[config_listen_address_list_len] == NULL)
1613 fprintf (stderr, "read_options: strdup failed.\n");
1616 config_listen_address_list_len++;
1624 temp = atoi (optarg);
1626 config_flush_interval = temp;
1629 fprintf (stderr, "Invalid flush interval: %s\n", optarg);
1639 temp = atoi (optarg);
1641 config_write_interval = temp;
1644 fprintf (stderr, "Invalid write interval: %s\n", optarg);
1654 if (config_base_dir != NULL)
1655 free (config_base_dir);
1656 config_base_dir = strdup (optarg);
1657 if (config_base_dir == NULL)
1659 fprintf (stderr, "read_options: strdup failed.\n");
1663 len = strlen (config_base_dir);
1664 while ((len > 0) && (config_base_dir[len - 1] == '/'))
1666 config_base_dir[len - 1] = 0;
1672 fprintf (stderr, "Invalid base directory: %s\n", optarg);
1680 if (config_pid_file != NULL)
1681 free (config_pid_file);
1682 config_pid_file = strdup (optarg);
1683 if (config_pid_file == NULL)
1685 fprintf (stderr, "read_options: strdup failed.\n");
1693 printf ("RRDd %s Copyright (C) 2008 Florian octo Forster\n"
1695 "Usage: rrdcached [options]\n"
1697 "Valid options are:\n"
1698 " -l <address> Socket address to listen to.\n"
1699 " -w <seconds> Interval in which to write data.\n"
1700 " -f <seconds> Interval in which to flush dead data.\n"
1701 " -p <file> Location of the PID-file.\n"
1702 " -b <dir> Base directory to change to.\n"
1704 "For more information and a detailed description of all options "
1706 "to the rrdcached(1) manual page.\n",
1710 } /* switch (option) */
1711 } /* while (getopt) */
1714 } /* }}} int read_options */
1716 int main (int argc, char **argv)
1720 status = read_options (argc, argv);
1728 status = daemonize ();
1731 struct sigaction sigchld;
1733 memset (&sigchld, 0, sizeof (sigchld));
1734 sigchld.sa_handler = SIG_IGN;
1735 sigaction (SIGCHLD, &sigchld, NULL);
1739 else if (status != 0)
1741 fprintf (stderr, "daemonize failed, exiting.\n");
1745 listen_thread_main (NULL);
1753 * vim: set sw=2 sts=2 ts=8 et fdm=marker :