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_total = 0;
170 static uint64_t stats_values_total = 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 */
227 * enqueue_cache_item:
228 * `cache_lock' must be acquired before calling this function!
230 static int enqueue_cache_item (cache_item_t *ci, /* {{{ */
235 RRDD_LOG (LOG_DEBUG, "enqueue_cache_item: Adding %s to the update queue.",
241 if (ci->values_num == 0)
246 if ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
248 assert (ci->next == NULL);
249 ci->next = cache_queue_head;
250 cache_queue_head = ci;
252 if (cache_queue_tail == NULL)
253 cache_queue_tail = cache_queue_head;
257 else if (cache_queue_head == ci)
261 else /* enqueued, but not first entry */
265 /* find previous entry */
266 for (prev = cache_queue_head; prev != NULL; prev = prev->next)
267 if (prev->next == ci)
269 assert (prev != NULL);
271 /* move to the front */
272 prev->next = ci->next;
273 ci->next = cache_queue_head;
274 cache_queue_head = ci;
276 /* check if we need to adapt the tail */
277 if (cache_queue_tail == ci)
278 cache_queue_tail = prev;
281 else /* (side == TAIL) */
283 /* We don't move values back in the list.. */
284 if ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
287 assert (ci->next == NULL);
289 if (cache_queue_tail == NULL)
290 cache_queue_head = ci;
292 cache_queue_tail->next = ci;
293 cache_queue_tail = ci;
298 ci->flags |= CI_FLAGS_IN_QUEUE;
302 pthread_mutex_lock (&stats_lock);
303 stats_queue_length++;
304 pthread_mutex_unlock (&stats_lock);
308 } /* }}} int enqueue_cache_item */
311 * tree_callback_flush:
312 * Called via `g_tree_foreach' in `queue_thread_main'. `cache_lock' is held
313 * while this is in progress.
315 static gboolean tree_callback_flush (gpointer key, gpointer value, /* {{{ */
319 callback_flush_data_t *cfd;
321 ci = (cache_item_t *) value;
322 cfd = (callback_flush_data_t *) data;
324 if (((cfd->now - ci->last_flush_time) >= config_write_interval)
325 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
326 && (ci->values_num > 0))
328 enqueue_cache_item (ci, TAIL);
330 else if (((cfd->now - ci->last_flush_time) >= config_flush_interval)
331 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
332 && (ci->values_num <= 0))
336 temp = (char **) realloc (cfd->keys,
337 sizeof (char *) * (cfd->keys_num + 1));
340 RRDD_LOG (LOG_ERR, "tree_callback_flush: realloc failed.");
344 /* Make really sure this points to the _same_ place */
345 assert ((char *) key == ci->file);
346 cfd->keys[cfd->keys_num] = (char *) key;
351 } /* }}} gboolean tree_callback_flush */
353 static void *queue_thread_main (void *args __attribute__((unused))) /* {{{ */
356 struct timespec next_flush;
358 gettimeofday (&now, NULL);
359 next_flush.tv_sec = now.tv_sec + config_flush_interval;
360 next_flush.tv_nsec = 1000 * now.tv_usec;
362 pthread_mutex_lock (&cache_lock);
363 while ((do_shutdown == 0) || (cache_queue_head != NULL))
372 /* First, check if it's time to do the cache flush. */
373 gettimeofday (&now, NULL);
374 if ((now.tv_sec > next_flush.tv_sec)
375 || ((now.tv_sec == next_flush.tv_sec)
376 && ((1000 * now.tv_usec) > next_flush.tv_nsec)))
378 callback_flush_data_t cfd;
381 memset (&cfd, 0, sizeof (cfd));
382 /* Pass the current time as user data so that we don't need to call
383 * `time' for each node. */
384 cfd.now = time (NULL);
388 /* `tree_callback_flush' will return the keys of all values that haven't
389 * been touched in the last `config_flush_interval' seconds in `cfd'.
390 * The char*'s in this array point to the same memory as ci->file, so we
391 * don't need to free them separately. */
392 g_tree_foreach (cache_tree, tree_callback_flush, (gpointer) &cfd);
394 for (k = 0; k < cfd.keys_num; k++)
396 /* This must not fail. */
397 ci = (cache_item_t *) g_tree_lookup (cache_tree, cfd.keys[k]);
400 /* If we end up here with values available, something's seriously
402 assert (ci->values_num == 0);
404 /* Remove the node from the tree */
405 g_tree_remove (cache_tree, cfd.keys[k]);
408 /* Now free and clean up `ci'. */
413 } /* for (k = 0; k < cfd.keys_num; k++) */
415 if (cfd.keys != NULL)
421 /* Determine the time of the next cache flush. */
422 while (next_flush.tv_sec < now.tv_sec)
423 next_flush.tv_sec += config_flush_interval;
426 /* Now, check if there's something to store away. If not, wait until
427 * something comes in or it's time to do the cache flush. */
428 if (cache_queue_head == NULL)
430 status = pthread_cond_timedwait (&cache_cond, &cache_lock, &next_flush);
431 if ((status != 0) && (status != ETIMEDOUT))
433 RRDD_LOG (LOG_ERR, "queue_thread_main: "
434 "pthread_cond_timedwait returned %i.", status);
438 /* Check if a value has arrived. This may be NULL if we timed out or there
439 * was an interrupt such as a signal. */
440 if (cache_queue_head == NULL)
443 ci = cache_queue_head;
445 /* copy the relevant parts */
446 file = strdup (ci->file);
449 RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
454 values_num = ci->values_num;
459 ci->last_flush_time = time (NULL);
460 ci->flags &= ~(CI_FLAGS_IN_QUEUE);
462 cache_queue_head = ci->next;
463 if (cache_queue_head == NULL)
464 cache_queue_tail = NULL;
467 pthread_mutex_lock (&stats_lock);
468 assert (stats_queue_length > 0);
469 stats_queue_length--;
470 pthread_mutex_unlock (&stats_lock);
472 pthread_mutex_unlock (&cache_lock);
474 RRDD_LOG (LOG_DEBUG, "queue_thread_main: rrd_update (%s, %i, %p)",
475 file, values_num, (void *) values);
477 status = rrd_update_r (file, NULL, values_num, (void *) values);
480 RRDD_LOG (LOG_ERR, "queue_thread_main: "
481 "rrd_update_r failed with status %i.",
486 for (i = 0; i < values_num; i++)
489 pthread_mutex_lock (&stats_lock);
490 stats_updates_total++;
491 stats_values_total += values_num;
492 pthread_mutex_unlock (&stats_lock);
494 pthread_mutex_lock (&cache_lock);
495 pthread_cond_broadcast (&flush_cond);
496 } /* while (do_shutdown == 0) */
497 pthread_mutex_unlock (&cache_lock);
499 RRDD_LOG (LOG_DEBUG, "queue_thread_main: Exiting.");
502 } /* }}} void *queue_thread_main */
504 static int buffer_get_field (char **buffer_ret, /* {{{ */
505 size_t *buffer_size_ret, char **field_ret)
514 buffer = *buffer_ret;
516 buffer_size = *buffer_size_ret;
520 if (buffer_size <= 0)
523 /* This is ensured by `handle_request'. */
524 assert (buffer[buffer_size - 1] == ' ');
527 while (buffer_pos < buffer_size)
529 /* Check for end-of-field or end-of-buffer */
530 if (buffer[buffer_pos] == ' ')
532 field[field_size] = 0;
538 /* Handle escaped characters. */
539 else if (buffer[buffer_pos] == '\\')
541 if (buffer_pos >= (buffer_size - 1))
544 field[field_size] = buffer[buffer_pos];
548 /* Normal operation */
551 field[field_size] = buffer[buffer_pos];
555 } /* while (buffer_pos < buffer_size) */
560 *buffer_ret = buffer + buffer_pos;
561 *buffer_size_ret = buffer_size - buffer_pos;
565 } /* }}} int buffer_get_field */
567 static int flush_file (const char *filename) /* {{{ */
571 pthread_mutex_lock (&cache_lock);
573 ci = (cache_item_t *) g_tree_lookup (cache_tree, filename);
576 pthread_mutex_unlock (&cache_lock);
580 /* Enqueue at head */
581 enqueue_cache_item (ci, HEAD);
582 pthread_cond_signal (&cache_cond);
584 while ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
588 pthread_cond_wait (&flush_cond, &cache_lock);
590 ci = g_tree_lookup (cache_tree, filename);
593 RRDD_LOG (LOG_ERR, "flush_file: Tree node went away "
594 "while waiting for flush.");
595 pthread_mutex_unlock (&cache_lock);
600 pthread_mutex_unlock (&cache_lock);
602 } /* }}} int flush_file */
604 static int handle_request_stats (int fd, /* {{{ */
605 char *buffer __attribute__((unused)),
606 size_t buffer_size __attribute__((unused)))
611 uint64_t copy_queue_length;
612 uint64_t copy_updates_total;
613 uint64_t copy_values_total;
618 pthread_mutex_lock (&stats_lock);
619 copy_queue_length = stats_queue_length;
620 copy_updates_total = stats_updates_total;
621 copy_values_total = stats_values_total;
622 pthread_mutex_unlock (&stats_lock);
624 pthread_mutex_lock (&cache_lock);
625 tree_nodes = (uint64_t) g_tree_nnodes (cache_tree);
626 tree_depth = (uint64_t) g_tree_height (cache_tree);
627 pthread_mutex_unlock (&cache_lock);
629 #define RRDD_STATS_SEND \
630 outbuf[sizeof (outbuf) - 1] = 0; \
631 status = write (fd, outbuf, strlen (outbuf)); \
635 RRDD_LOG (LOG_INFO, "handle_request_stats: write(2) returned an error."); \
639 strncpy (outbuf, "5 Statistics follow\n", sizeof (outbuf));
642 snprintf (outbuf, sizeof (outbuf),
643 "QueueLength: %"PRIu64"\n", copy_queue_length);
646 snprintf (outbuf, sizeof (outbuf),
647 "UpdatesWritten: %"PRIu64"\n", copy_updates_total);
650 snprintf (outbuf, sizeof (outbuf),
651 "ValuesWritten: %"PRIu64"\n", copy_values_total);
654 snprintf (outbuf, sizeof (outbuf),
655 "TreeNodesNumber: %"PRIu64"\n", tree_nodes);
658 snprintf (outbuf, sizeof (outbuf),
659 "TreeDepth: %"PRIu64"\n", tree_depth);
663 } /* }}} int handle_request_stats */
665 static int handle_request_flush (int fd, /* {{{ */
666 char *buffer, size_t buffer_size)
672 status = buffer_get_field (&buffer, &buffer_size, &file);
675 strncpy (result, "-1 Usage: flush <filename>\n", sizeof (result));
679 status = flush_file (file);
681 snprintf (result, sizeof (result), "0 Successfully flushed %s.\n", file);
682 else if (status == ENOENT)
683 snprintf (result, sizeof (result), "-1 No such file: %s.\n", file);
685 strncpy (result, "-1 Internal error.\n", sizeof (result));
687 snprintf (result, sizeof (result), "-1 Failed with status %i.\n", status);
689 result[sizeof (result) - 1] = 0;
691 status = write (fd, result, strlen (result));
695 RRDD_LOG (LOG_INFO, "handle_request_flush: write(2) returned an error.");
700 } /* }}} int handle_request_flush */
702 static int handle_request_update (int fd, /* {{{ */
703 char *buffer, size_t buffer_size)
716 status = buffer_get_field (&buffer, &buffer_size, &file);
719 RRDD_LOG (LOG_INFO, "handle_request_update: Cannot get file name.");
723 pthread_mutex_lock (&cache_lock);
725 ci = g_tree_lookup (cache_tree, file);
726 if (ci == NULL) /* {{{ */
728 ci = (cache_item_t *) malloc (sizeof (cache_item_t));
731 pthread_mutex_unlock (&cache_lock);
732 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
735 memset (ci, 0, sizeof (cache_item_t));
737 ci->file = strdup (file);
738 if (ci->file == NULL)
740 pthread_mutex_unlock (&cache_lock);
741 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
748 ci->last_flush_time = now;
749 ci->flags = CI_FLAGS_IN_TREE;
751 g_tree_insert (cache_tree, (void *) ci->file, (void *) ci);
753 RRDD_LOG (LOG_DEBUG, "handle_request_update: Created new tree node %s.",
758 while (buffer_size > 0)
763 status = buffer_get_field (&buffer, &buffer_size, &value);
766 RRDD_LOG (LOG_INFO, "handle_request_update: Error reading field.");
770 temp = (char **) realloc (ci->values,
771 sizeof (char *) * (ci->values_num + 1));
774 RRDD_LOG (LOG_ERR, "handle_request_update: realloc failed.");
779 ci->values[ci->values_num] = strdup (value);
780 if (ci->values[ci->values_num] == NULL)
782 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
790 if (((now - ci->last_flush_time) >= config_write_interval)
791 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
792 && (ci->values_num > 0))
794 enqueue_cache_item (ci, TAIL);
795 pthread_cond_signal (&cache_cond);
798 pthread_mutex_unlock (&cache_lock);
800 snprintf (answer, sizeof (answer), "0 Enqueued %i value(s)\n", values_num);
801 answer[sizeof (answer) - 1] = 0;
803 status = write (fd, answer, strlen (answer));
807 RRDD_LOG (LOG_INFO, "handle_request_update: write(2) returned an error.");
812 } /* }}} int handle_request_update */
814 static int handle_request (int fd) /* {{{ */
822 status = read (fd, buffer, sizeof (buffer));
829 RRDD_LOG (LOG_ERR, "handle_request: read(2) failed.");
832 buffer_size = status;
833 assert (((size_t) buffer_size) <= sizeof (buffer));
835 if (buffer[buffer_size - 1] != '\n')
837 RRDD_LOG (LOG_INFO, "handle_request: malformed request.");
841 /* Accept Windows style line endings, too */
842 if ((buffer_size > 2) && (buffer[buffer_size - 2] == '\r'))
845 buffer[buffer_size - 1] = '\n';
848 /* Place the normal field separator at the end to simplify
849 * `buffer_get_field's work. */
850 buffer[buffer_size - 1] = ' ';
854 status = buffer_get_field (&buffer_ptr, &buffer_size, &command);
857 RRDD_LOG (LOG_INFO, "handle_request: Unable parse command.");
861 if (strcasecmp (command, "update") == 0)
863 return (handle_request_update (fd, buffer_ptr, buffer_size));
865 else if (strcasecmp (command, "flush") == 0)
867 return (handle_request_flush (fd, buffer_ptr, buffer_size));
869 else if (strcasecmp (command, "stats") == 0)
871 return (handle_request_stats (fd, buffer_ptr, buffer_size));
877 snprintf (result, sizeof (result), "-1 Unknown command: %s\n", command);
878 result[sizeof (result) - 1] = 0;
880 status = write (fd, result, strlen (result));
883 RRDD_LOG (LOG_ERR, "handle_request: write(2) failed.");
889 } /* }}} int handle_request */
891 static void *connection_thread_main (void *args /* {{{ */
892 __attribute__((unused)))
898 fd = *((int *) args);
900 pthread_mutex_lock (&connetion_threads_lock);
904 temp = (pthread_t *) realloc (connetion_threads,
905 sizeof (pthread_t) * (connetion_threads_num + 1));
908 RRDD_LOG (LOG_ERR, "connection_thread_main: realloc failed.");
912 connetion_threads = temp;
913 connetion_threads[connetion_threads_num] = pthread_self ();
914 connetion_threads_num++;
917 pthread_mutex_unlock (&connetion_threads_lock);
919 while (do_shutdown == 0)
921 struct pollfd pollfd;
925 pollfd.events = POLLIN | POLLPRI;
928 status = poll (&pollfd, 1, /* timeout = */ 500);
929 if (status == 0) /* timeout */
931 else if (status < 0) /* error */
936 RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
940 if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
945 else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
947 RRDD_LOG (LOG_WARNING, "connection_thread_main: "
948 "poll(2) returned something unexpected: %#04hx",
954 status = handle_request (fd);
962 self = pthread_self ();
963 /* Remove this thread from the connection threads list */
964 pthread_mutex_lock (&connetion_threads_lock);
965 /* Find out own index in the array */
966 for (i = 0; i < connetion_threads_num; i++)
967 if (pthread_equal (connetion_threads[i], self) != 0)
969 assert (i < connetion_threads_num);
971 /* Move the trailing threads forward. */
972 if (i < (connetion_threads_num - 1))
974 memmove (connetion_threads + i,
975 connetion_threads + i + 1,
976 sizeof (pthread_t) * (connetion_threads_num - i - 1));
979 connetion_threads_num--;
980 pthread_mutex_unlock (&connetion_threads_lock);
984 } /* }}} void *connection_thread_main */
986 static int open_listen_socket_unix (const char *path) /* {{{ */
989 struct sockaddr_un sa;
990 listen_socket_t *temp;
993 temp = (listen_socket_t *) realloc (listen_fds,
994 sizeof (listen_fds[0]) * (listen_fds_num + 1));
997 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: realloc failed.");
1001 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1003 fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
1006 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: socket(2) failed.");
1010 memset (&sa, 0, sizeof (sa));
1011 sa.sun_family = AF_UNIX;
1012 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
1014 status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
1017 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: bind(2) failed.");
1023 status = listen (fd, /* backlog = */ 10);
1026 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: listen(2) failed.");
1032 listen_fds[listen_fds_num].fd = fd;
1033 snprintf (listen_fds[listen_fds_num].path,
1034 sizeof (listen_fds[listen_fds_num].path) - 1,
1039 } /* }}} int open_listen_socket_unix */
1041 static int open_listen_socket (const char *addr) /* {{{ */
1043 struct addrinfo ai_hints;
1044 struct addrinfo *ai_res;
1045 struct addrinfo *ai_ptr;
1048 assert (addr != NULL);
1050 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
1051 return (open_listen_socket_unix (addr + strlen ("unix:")));
1052 else if (addr[0] == '/')
1053 return (open_listen_socket_unix (addr));
1055 memset (&ai_hints, 0, sizeof (ai_hints));
1056 ai_hints.ai_flags = 0;
1057 #ifdef AI_ADDRCONFIG
1058 ai_hints.ai_flags |= AI_ADDRCONFIG;
1060 ai_hints.ai_family = AF_UNSPEC;
1061 ai_hints.ai_socktype = SOCK_STREAM;
1064 status = getaddrinfo (addr, RRDCACHED_DEFAULT_PORT, &ai_hints, &ai_res);
1067 RRDD_LOG (LOG_ERR, "open_listen_socket: getaddrinfo(%s) failed: "
1068 "%s", addr, gai_strerror (status));
1072 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1075 listen_socket_t *temp;
1077 temp = (listen_socket_t *) realloc (listen_fds,
1078 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1081 RRDD_LOG (LOG_ERR, "open_listen_socket: realloc failed.");
1085 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1087 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1090 RRDD_LOG (LOG_ERR, "open_listen_socket: socket(2) failed.");
1094 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1097 RRDD_LOG (LOG_ERR, "open_listen_socket: bind(2) failed.");
1102 status = listen (fd, /* backlog = */ 10);
1105 RRDD_LOG (LOG_ERR, "open_listen_socket: listen(2) failed.");
1110 listen_fds[listen_fds_num].fd = fd;
1111 strncpy (listen_fds[listen_fds_num].path, addr,
1112 sizeof (listen_fds[listen_fds_num].path) - 1);
1114 } /* for (ai_ptr) */
1117 } /* }}} int open_listen_socket */
1119 static int close_listen_sockets (void) /* {{{ */
1123 for (i = 0; i < listen_fds_num; i++)
1125 close (listen_fds[i].fd);
1126 if (strncmp ("unix:", listen_fds[i].path, strlen ("unix:")) == 0)
1127 unlink (listen_fds[i].path + strlen ("unix:"));
1135 } /* }}} int close_listen_sockets */
1137 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
1139 struct pollfd *pollfds;
1144 for (i = 0; i < config_listen_address_list_len; i++)
1146 RRDD_LOG (LOG_DEBUG, "listen_thread_main: config_listen_address_list[%i] "
1147 "= %s", i, config_listen_address_list[i]);
1148 open_listen_socket (config_listen_address_list[i]);
1151 if (config_listen_address_list_len < 1)
1152 open_listen_socket (RRDCACHED_DEFAULT_ADDRESS);
1154 if (listen_fds_num < 1)
1156 RRDD_LOG (LOG_ERR, "listen_thread_main: No listen sockets "
1157 "could be opened. Sorry.");
1161 pollfds_num = listen_fds_num;
1162 pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
1163 if (pollfds == NULL)
1165 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1168 memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
1170 while (do_shutdown == 0)
1172 assert (pollfds_num == ((int) listen_fds_num));
1173 for (i = 0; i < pollfds_num; i++)
1175 pollfds[i].fd = listen_fds[i].fd;
1176 pollfds[i].events = POLLIN | POLLPRI;
1177 pollfds[i].revents = 0;
1180 status = poll (pollfds, pollfds_num, /* timeout = */ -1);
1184 if (status != EINTR)
1186 RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
1191 for (i = 0; i < pollfds_num; i++)
1194 struct sockaddr_storage client_sa;
1195 socklen_t client_sa_size;
1198 if (pollfds[i].revents == 0)
1201 if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
1203 RRDD_LOG (LOG_ERR, "listen_thread_main: "
1204 "poll(2) returned something unexpected for listen FD #%i.",
1209 client_sd = (int *) malloc (sizeof (int));
1210 if (client_sd == NULL)
1212 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1216 client_sa_size = sizeof (client_sa);
1217 *client_sd = accept (pollfds[i].fd,
1218 (struct sockaddr *) &client_sa, &client_sa_size);
1221 RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
1225 status = pthread_create (&tid, /* attr = */ NULL, connection_thread_main,
1226 /* args = */ (void *) client_sd);
1229 RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
1234 } /* for (pollfds_num) */
1235 } /* while (do_shutdown == 0) */
1237 close_listen_sockets ();
1239 pthread_mutex_lock (&connetion_threads_lock);
1240 while (connetion_threads_num > 0)
1244 wait_for = connetion_threads[0];
1246 pthread_mutex_unlock (&connetion_threads_lock);
1247 pthread_join (wait_for, /* retval = */ NULL);
1248 pthread_mutex_lock (&connetion_threads_lock);
1250 pthread_mutex_unlock (&connetion_threads_lock);
1252 RRDD_LOG (LOG_DEBUG, "listen_thread_main: Exiting.");
1255 } /* }}} void *listen_thread_main */
1257 static int daemonize (void) /* {{{ */
1263 /* These structures are static, because `sigaction' behaves weird if the are
1265 static struct sigaction sa_int;
1266 static struct sigaction sa_term;
1267 static struct sigaction sa_pipe;
1272 fprintf (stderr, "daemonize: fork(2) failed.\n");
1280 /* Change into the /tmp directory. */
1281 base_dir = (config_base_dir != NULL)
1284 status = chdir (base_dir);
1287 fprintf (stderr, "daemonize: chdir (%s) failed.\n", base_dir);
1291 /* Become session leader */
1294 /* Open the first three file descriptors to /dev/null */
1299 open ("/dev/null", O_RDWR);
1303 /* Install signal handlers */
1304 memset (&sa_int, 0, sizeof (sa_int));
1305 sa_int.sa_handler = sig_int_handler;
1306 sigaction (SIGINT, &sa_int, NULL);
1308 memset (&sa_term, 0, sizeof (sa_term));
1309 sa_term.sa_handler = sig_term_handler;
1310 sigaction (SIGINT, &sa_term, NULL);
1312 memset (&sa_pipe, 0, sizeof (sa_pipe));
1313 sa_pipe.sa_handler = SIG_IGN;
1314 sigaction (SIGPIPE, &sa_pipe, NULL);
1316 openlog ("rrdcached", LOG_PID, LOG_DAEMON);
1318 cache_tree = g_tree_new ((GCompareFunc) strcmp);
1319 if (cache_tree == NULL)
1321 RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
1325 memset (&queue_thread, 0, sizeof (queue_thread));
1326 status = pthread_create (&queue_thread, /* attr = */ NULL,
1327 queue_thread_main, /* args = */ NULL);
1330 RRDD_LOG (LOG_ERR, "daemonize: pthread_create failed.");
1337 } /* }}} int daemonize */
1339 static int cleanup (void) /* {{{ */
1341 RRDD_LOG (LOG_DEBUG, "cleanup ()");
1345 RRDD_LOG (LOG_DEBUG, "cleanup: Joining queue_thread..");
1346 pthread_cond_signal (&cache_cond);
1347 pthread_join (queue_thread, /* return = */ NULL);
1348 RRDD_LOG (LOG_DEBUG, "cleanup: done");
1355 } /* }}} int cleanup */
1357 static int read_options (int argc, char **argv) /* {{{ */
1362 while ((option = getopt(argc, argv, "l:f:w:b:p:h?")) != -1)
1370 temp = (char **) realloc (config_listen_address_list,
1371 sizeof (char *) * (config_listen_address_list_len + 1));
1374 fprintf (stderr, "read_options: realloc failed.\n");
1377 config_listen_address_list = temp;
1379 temp[config_listen_address_list_len] = strdup (optarg);
1380 if (temp[config_listen_address_list_len] == NULL)
1382 fprintf (stderr, "read_options: strdup failed.\n");
1385 config_listen_address_list_len++;
1393 temp = atoi (optarg);
1395 config_flush_interval = temp;
1398 fprintf (stderr, "Invalid flush interval: %s\n", optarg);
1408 temp = atoi (optarg);
1410 config_write_interval = temp;
1413 fprintf (stderr, "Invalid write interval: %s\n", optarg);
1423 if (config_base_dir != NULL)
1424 free (config_base_dir);
1425 config_base_dir = strdup (optarg);
1426 if (config_base_dir == NULL)
1428 fprintf (stderr, "read_options: strdup failed.\n");
1432 len = strlen (config_base_dir);
1433 while ((len > 0) && (config_base_dir[len - 1] == '/'))
1435 config_base_dir[len - 1] = 0;
1441 fprintf (stderr, "Invalid base directory: %s\n", optarg);
1449 if (config_pid_file != NULL)
1450 free (config_pid_file);
1451 config_pid_file = strdup (optarg);
1452 if (config_pid_file == NULL)
1454 fprintf (stderr, "read_options: strdup failed.\n");
1462 printf ("RRDd %s Copyright (C) 2008 Florian octo Forster\n"
1464 "Usage: rrdcached [options]\n"
1466 "Valid options are:\n"
1467 " -l <address> Socket address to listen to.\n"
1468 " -w <seconds> Interval in which to write data.\n"
1469 " -f <seconds> Interval in which to flush dead data.\n"
1470 " -p <file> Location of the PID-file.\n"
1471 " -b <dir> Base directory to change to.\n"
1473 "For more information and a detailed description of all options "
1475 "to the rrdcached(1) manual page.\n",
1479 } /* switch (option) */
1480 } /* while (getopt) */
1483 } /* }}} int read_options */
1485 int main (int argc, char **argv)
1489 status = read_options (argc, argv);
1497 status = daemonize ();
1500 struct sigaction sigchld;
1502 memset (&sigchld, 0, sizeof (sigchld));
1503 sigchld.sa_handler = SIG_IGN;
1504 sigaction (SIGCHLD, &sigchld, NULL);
1508 else if (status != 0)
1510 fprintf (stderr, "daemonize failed, exiting.\n");
1514 listen_thread_main (NULL);
1522 * vim: set sw=2 sts=2 ts=8 et fdm=marker :