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"
72 #include <sys/types.h>
76 #include <sys/socket.h>
87 #include <glib-2.0/glib.h>
90 #define RRDD_LOG(severity, ...) syslog ((severity), __VA_ARGS__)
93 # define __attribute__(x) /**/
99 struct listen_socket_s
102 char path[PATH_MAX + 1];
104 typedef struct listen_socket_s listen_socket_t;
107 typedef struct cache_item_s cache_item_t;
113 time_t last_flush_time;
114 #define CI_FLAGS_IN_TREE 0x01
115 #define CI_FLAGS_IN_QUEUE 0x02
121 struct callback_flush_data_s
127 typedef struct callback_flush_data_s callback_flush_data_t;
134 typedef enum queue_side_e queue_side_t;
139 static listen_socket_t *listen_fds = NULL;
140 static size_t listen_fds_num = 0;
142 static int do_shutdown = 0;
144 static pthread_t queue_thread;
146 static pthread_t *connetion_threads = NULL;
147 static pthread_mutex_t connetion_threads_lock = PTHREAD_MUTEX_INITIALIZER;
148 static int connetion_threads_num = 0;
151 static GTree *cache_tree = NULL;
152 static cache_item_t *cache_queue_head = NULL;
153 static cache_item_t *cache_queue_tail = NULL;
154 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
155 static pthread_cond_t cache_cond = PTHREAD_COND_INITIALIZER;
157 static pthread_cond_t flush_cond = PTHREAD_COND_INITIALIZER;
159 static int config_write_interval = 300;
160 static int config_flush_interval = 3600;
161 static char *config_pid_file = NULL;
162 static char *config_base_dir = NULL;
164 static char **config_listen_address_list = NULL;
165 static int config_listen_address_list_len = 0;
167 static uint64_t stats_queue_length = 0;
168 static uint64_t stats_updates_total = 0;
169 static uint64_t stats_values_total = 0;
170 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
175 static void sig_int_handler (int s __attribute__((unused))) /* {{{ */
178 } /* }}} void sig_int_handler */
180 static void sig_term_handler (int s __attribute__((unused))) /* {{{ */
183 } /* }}} void sig_term_handler */
185 static int write_pidfile (void) /* {{{ */
193 file = (config_pid_file != NULL)
195 : LOCALSTATEDIR "/run/rrdcached.pid";
197 fh = fopen (file, "w");
200 RRDD_LOG (LOG_ERR, "write_pidfile: Opening `%s' failed.", file);
204 fprintf (fh, "%i\n", (int) pid);
208 } /* }}} int write_pidfile */
210 static int remove_pidfile (void) /* {{{ */
215 file = (config_pid_file != NULL)
217 : LOCALSTATEDIR "/run/rrdcached.pid";
219 status = unlink (file);
223 } /* }}} int remove_pidfile */
226 * enqueue_cache_item:
227 * `cache_lock' must be acquired before calling this function!
229 static int enqueue_cache_item (cache_item_t *ci, /* {{{ */
234 RRDD_LOG (LOG_DEBUG, "enqueue_cache_item: Adding %s to the update queue.",
240 if (ci->values_num == 0)
245 if ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
247 assert (ci->next == NULL);
248 ci->next = cache_queue_head;
249 cache_queue_head = ci;
251 if (cache_queue_tail == NULL)
252 cache_queue_tail = cache_queue_head;
256 else if (cache_queue_head == ci)
260 else /* enqueued, but not first entry */
264 /* find previous entry */
265 for (prev = cache_queue_head; prev != NULL; prev = prev->next)
266 if (prev->next == ci)
268 assert (prev != NULL);
270 /* move to the front */
271 prev->next = ci->next;
272 ci->next = cache_queue_head;
273 cache_queue_head = ci;
275 /* check if we need to adapt the tail */
276 if (cache_queue_tail == ci)
277 cache_queue_tail = prev;
280 else /* (side == TAIL) */
282 /* We don't move values back in the list.. */
283 if ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
286 assert (ci->next == NULL);
288 if (cache_queue_tail == NULL)
289 cache_queue_head = ci;
291 cache_queue_tail->next = ci;
292 cache_queue_tail = ci;
297 ci->flags |= CI_FLAGS_IN_QUEUE;
301 pthread_mutex_lock (&stats_lock);
302 stats_queue_length++;
303 pthread_mutex_unlock (&stats_lock);
307 } /* }}} int enqueue_cache_item */
310 * tree_callback_flush:
311 * Called via `g_tree_foreach' in `queue_thread_main'. `cache_lock' is held
312 * while this is in progress.
314 static gboolean tree_callback_flush (gpointer key, gpointer value, /* {{{ */
318 callback_flush_data_t *cfd;
320 ci = (cache_item_t *) value;
321 cfd = (callback_flush_data_t *) data;
323 if (((cfd->now - ci->last_flush_time) >= config_write_interval)
324 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
325 && (ci->values_num > 0))
327 enqueue_cache_item (ci, TAIL);
329 else if (((cfd->now - ci->last_flush_time) >= config_flush_interval)
330 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
331 && (ci->values_num <= 0))
335 temp = (char **) realloc (cfd->keys,
336 sizeof (char *) * (cfd->keys_num + 1));
339 RRDD_LOG (LOG_ERR, "tree_callback_flush: realloc failed.");
343 /* Make really sure this points to the _same_ place */
344 assert ((char *) key == ci->file);
345 cfd->keys[cfd->keys_num] = (char *) key;
350 } /* }}} gboolean tree_callback_flush */
352 static void *queue_thread_main (void *args __attribute__((unused))) /* {{{ */
355 struct timespec next_flush;
357 gettimeofday (&now, NULL);
358 next_flush.tv_sec = now.tv_sec + config_flush_interval;
359 next_flush.tv_nsec = 1000 * now.tv_usec;
361 pthread_mutex_lock (&cache_lock);
362 while ((do_shutdown == 0) || (cache_queue_head != NULL))
371 /* First, check if it's time to do the cache flush. */
372 gettimeofday (&now, NULL);
373 if ((now.tv_sec > next_flush.tv_sec)
374 || ((now.tv_sec == next_flush.tv_sec)
375 && ((1000 * now.tv_usec) > next_flush.tv_nsec)))
377 callback_flush_data_t cfd;
380 memset (&cfd, 0, sizeof (cfd));
381 /* Pass the current time as user data so that we don't need to call
382 * `time' for each node. */
383 cfd.now = time (NULL);
387 /* `tree_callback_flush' will return the keys of all values that haven't
388 * been touched in the last `config_flush_interval' seconds in `cfd'.
389 * The char*'s in this array point to the same memory as ci->file, so we
390 * don't need to free them separately. */
391 g_tree_foreach (cache_tree, tree_callback_flush, (gpointer) &cfd);
393 for (k = 0; k < cfd.keys_num; k++)
395 /* This must not fail. */
396 ci = (cache_item_t *) g_tree_lookup (cache_tree, cfd.keys[k]);
399 /* If we end up here with values available, something's seriously
401 assert (ci->values_num == 0);
403 /* Remove the node from the tree */
404 g_tree_remove (cache_tree, cfd.keys[k]);
407 /* Now free and clean up `ci'. */
412 } /* for (k = 0; k < cfd.keys_num; k++) */
414 if (cfd.keys != NULL)
420 /* Determine the time of the next cache flush. */
421 while (next_flush.tv_sec < now.tv_sec)
422 next_flush.tv_sec += config_flush_interval;
425 /* Now, check if there's something to store away. If not, wait until
426 * something comes in or it's time to do the cache flush. */
427 if (cache_queue_head == NULL)
429 status = pthread_cond_timedwait (&cache_cond, &cache_lock, &next_flush);
430 if ((status != 0) && (status != ETIMEDOUT))
432 RRDD_LOG (LOG_ERR, "queue_thread_main: "
433 "pthread_cond_timedwait returned %i.", status);
437 /* Check if a value has arrived. This may be NULL if we timed out or there
438 * was an interrupt such as a signal. */
439 if (cache_queue_head == NULL)
442 ci = cache_queue_head;
444 /* copy the relevant parts */
445 file = strdup (ci->file);
448 RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
453 values_num = ci->values_num;
458 ci->last_flush_time = time (NULL);
459 ci->flags &= ~(CI_FLAGS_IN_QUEUE);
461 cache_queue_head = ci->next;
462 if (cache_queue_head == NULL)
463 cache_queue_tail = NULL;
466 pthread_mutex_lock (&stats_lock);
467 assert (stats_queue_length > 0);
468 stats_queue_length--;
469 pthread_mutex_unlock (&stats_lock);
471 pthread_mutex_unlock (&cache_lock);
473 RRDD_LOG (LOG_DEBUG, "queue_thread_main: rrd_update (%s, %i, %p)",
474 file, values_num, (void *) values);
476 status = rrd_update_r (file, NULL, values_num, (void *) values);
479 RRDD_LOG (LOG_ERR, "queue_thread_main: "
480 "rrd_update_r failed with status %i.",
485 for (i = 0; i < values_num; i++)
488 pthread_mutex_lock (&stats_lock);
489 stats_updates_total++;
490 stats_values_total += values_num;
491 pthread_mutex_unlock (&stats_lock);
493 pthread_mutex_lock (&cache_lock);
494 pthread_cond_broadcast (&flush_cond);
495 } /* while (do_shutdown == 0) */
496 pthread_mutex_unlock (&cache_lock);
498 RRDD_LOG (LOG_DEBUG, "queue_thread_main: Exiting.");
501 } /* }}} void *queue_thread_main */
503 static int buffer_get_field (char **buffer_ret, /* {{{ */
504 size_t *buffer_size_ret, char **field_ret)
513 buffer = *buffer_ret;
515 buffer_size = *buffer_size_ret;
519 if (buffer_size <= 0)
522 /* This is ensured by `handle_request'. */
523 assert (buffer[buffer_size - 1] == ' ');
526 while (buffer_pos < buffer_size)
528 /* Check for end-of-field or end-of-buffer */
529 if (buffer[buffer_pos] == ' ')
531 field[field_size] = 0;
537 /* Handle escaped characters. */
538 else if (buffer[buffer_pos] == '\\')
540 if (buffer_pos >= (buffer_size - 1))
543 field[field_size] = buffer[buffer_pos];
547 /* Normal operation */
550 field[field_size] = buffer[buffer_pos];
554 } /* while (buffer_pos < buffer_size) */
559 *buffer_ret = buffer + buffer_pos;
560 *buffer_size_ret = buffer_size - buffer_pos;
564 } /* }}} int buffer_get_field */
566 static int flush_file (const char *filename) /* {{{ */
570 pthread_mutex_lock (&cache_lock);
572 ci = (cache_item_t *) g_tree_lookup (cache_tree, filename);
575 pthread_mutex_unlock (&cache_lock);
579 /* Enqueue at head */
580 enqueue_cache_item (ci, HEAD);
581 pthread_cond_signal (&cache_cond);
583 while ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
587 pthread_cond_wait (&flush_cond, &cache_lock);
589 ci = g_tree_lookup (cache_tree, filename);
592 RRDD_LOG (LOG_ERR, "flush_file: Tree node went away "
593 "while waiting for flush.");
594 pthread_mutex_unlock (&cache_lock);
599 pthread_mutex_unlock (&cache_lock);
601 } /* }}} int flush_file */
603 static int handle_request_stats (int fd, /* {{{ */
604 char *buffer __attribute__((unused)),
605 size_t buffer_size __attribute__((unused)))
610 uint64_t copy_queue_length;
611 uint64_t copy_updates_total;
612 uint64_t copy_values_total;
617 pthread_mutex_lock (&stats_lock);
618 copy_queue_length = stats_queue_length;
619 copy_updates_total = stats_updates_total;
620 copy_values_total = stats_values_total;
621 pthread_mutex_unlock (&stats_lock);
623 pthread_mutex_lock (&cache_lock);
624 tree_nodes = (uint64_t) g_tree_nnodes (cache_tree);
625 tree_depth = (uint64_t) g_tree_height (cache_tree);
626 pthread_mutex_unlock (&cache_lock);
628 #define RRDD_STATS_SEND \
629 outbuf[sizeof (outbuf) - 1] = 0; \
630 status = write (fd, outbuf, strlen (outbuf)); \
634 RRDD_LOG (LOG_INFO, "handle_request_stats: write(2) returned an error."); \
638 strncpy (outbuf, "5 Statistics follow\n", sizeof (outbuf));
641 snprintf (outbuf, sizeof (outbuf),
642 "QueueLength: %"PRIu64"\n", copy_queue_length);
645 snprintf (outbuf, sizeof (outbuf),
646 "UpdatesWritten: %"PRIu64"\n", copy_updates_total);
649 snprintf (outbuf, sizeof (outbuf),
650 "ValuesWritten: %"PRIu64"\n", copy_values_total);
653 snprintf (outbuf, sizeof (outbuf),
654 "TreeNodesNumber: %"PRIu64"\n", tree_nodes);
657 snprintf (outbuf, sizeof (outbuf),
658 "TreeDepth: %"PRIu64"\n", tree_depth);
662 } /* }}} int handle_request_stats */
664 static int handle_request_flush (int fd, /* {{{ */
665 char *buffer, size_t buffer_size)
671 status = buffer_get_field (&buffer, &buffer_size, &file);
674 strncpy (result, "-1 Usage: flush <filename>\n", sizeof (result));
678 status = flush_file (file);
680 snprintf (result, sizeof (result), "0 Successfully flushed %s.\n", file);
681 else if (status == ENOENT)
682 snprintf (result, sizeof (result), "-1 No such file: %s.\n", file);
684 strncpy (result, "-1 Internal error.\n", sizeof (result));
686 snprintf (result, sizeof (result), "-1 Failed with status %i.\n", status);
688 result[sizeof (result) - 1] = 0;
690 status = write (fd, result, strlen (result));
694 RRDD_LOG (LOG_INFO, "handle_request_flush: write(2) returned an error.");
699 } /* }}} int handle_request_flush */
701 static int handle_request_update (int fd, /* {{{ */
702 char *buffer, size_t buffer_size)
715 status = buffer_get_field (&buffer, &buffer_size, &file);
718 RRDD_LOG (LOG_INFO, "handle_request_update: Cannot get file name.");
722 pthread_mutex_lock (&cache_lock);
724 ci = g_tree_lookup (cache_tree, file);
725 if (ci == NULL) /* {{{ */
727 ci = (cache_item_t *) malloc (sizeof (cache_item_t));
730 pthread_mutex_unlock (&cache_lock);
731 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
734 memset (ci, 0, sizeof (cache_item_t));
736 ci->file = strdup (file);
737 if (ci->file == NULL)
739 pthread_mutex_unlock (&cache_lock);
740 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
747 ci->last_flush_time = now;
748 ci->flags = CI_FLAGS_IN_TREE;
750 g_tree_insert (cache_tree, (void *) ci->file, (void *) ci);
752 RRDD_LOG (LOG_DEBUG, "handle_request_update: Created new tree node %s.",
757 while (buffer_size > 0)
762 status = buffer_get_field (&buffer, &buffer_size, &value);
765 RRDD_LOG (LOG_INFO, "handle_request_update: Error reading field.");
769 temp = (char **) realloc (ci->values,
770 sizeof (char *) * (ci->values_num + 1));
773 RRDD_LOG (LOG_ERR, "handle_request_update: realloc failed.");
778 ci->values[ci->values_num] = strdup (value);
779 if (ci->values[ci->values_num] == NULL)
781 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
789 if (((now - ci->last_flush_time) >= config_write_interval)
790 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
791 && (ci->values_num > 0))
793 enqueue_cache_item (ci, TAIL);
794 pthread_cond_signal (&cache_cond);
797 pthread_mutex_unlock (&cache_lock);
799 snprintf (answer, sizeof (answer), "0 Enqueued %i value(s)\n", values_num);
800 answer[sizeof (answer) - 1] = 0;
802 status = write (fd, answer, strlen (answer));
806 RRDD_LOG (LOG_INFO, "handle_request_update: write(2) returned an error.");
811 } /* }}} int handle_request_update */
813 static int handle_request (int fd) /* {{{ */
821 status = read (fd, buffer, sizeof (buffer));
828 RRDD_LOG (LOG_ERR, "handle_request: read(2) failed.");
831 buffer_size = status;
832 assert (((size_t) buffer_size) <= sizeof (buffer));
834 if (buffer[buffer_size - 1] != '\n')
836 RRDD_LOG (LOG_INFO, "handle_request: malformed request.");
840 /* Accept Windows style line endings, too */
841 if ((buffer_size > 2) && (buffer[buffer_size - 2] == '\r'))
844 buffer[buffer_size - 1] = '\n';
847 /* Place the normal field separator at the end to simplify
848 * `buffer_get_field's work. */
849 buffer[buffer_size - 1] = ' ';
853 status = buffer_get_field (&buffer_ptr, &buffer_size, &command);
856 RRDD_LOG (LOG_INFO, "handle_request: Unable parse command.");
860 if (strcmp (command, "update") == 0)
862 return (handle_request_update (fd, buffer_ptr, buffer_size));
864 else if (strcmp (command, "flush") == 0)
866 return (handle_request_flush (fd, buffer_ptr, buffer_size));
868 else if (strcmp (command, "stats") == 0)
870 return (handle_request_stats (fd, buffer_ptr, buffer_size));
874 RRDD_LOG (LOG_INFO, "handle_request: unknown command: %s.", buffer);
877 } /* }}} int handle_request */
879 static void *connection_thread_main (void *args /* {{{ */
880 __attribute__((unused)))
886 fd = *((int *) args);
888 pthread_mutex_lock (&connetion_threads_lock);
892 temp = (pthread_t *) realloc (connetion_threads,
893 sizeof (pthread_t) * (connetion_threads_num + 1));
896 RRDD_LOG (LOG_ERR, "connection_thread_main: realloc failed.");
900 connetion_threads = temp;
901 connetion_threads[connetion_threads_num] = pthread_self ();
902 connetion_threads_num++;
905 pthread_mutex_unlock (&connetion_threads_lock);
907 while (do_shutdown == 0)
909 struct pollfd pollfd;
913 pollfd.events = POLLIN | POLLPRI;
916 status = poll (&pollfd, 1, /* timeout = */ 500);
917 if (status == 0) /* timeout */
919 else if (status < 0) /* error */
924 RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
928 if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
933 else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
935 RRDD_LOG (LOG_WARNING, "connection_thread_main: "
936 "poll(2) returned something unexpected: %#04hx",
942 status = handle_request (fd);
950 self = pthread_self ();
951 /* Remove this thread from the connection threads list */
952 pthread_mutex_lock (&connetion_threads_lock);
953 /* Find out own index in the array */
954 for (i = 0; i < connetion_threads_num; i++)
955 if (pthread_equal (connetion_threads[i], self) != 0)
957 assert (i < connetion_threads_num);
959 /* Move the trailing threads forward. */
960 if (i < (connetion_threads_num - 1))
962 memmove (connetion_threads + i,
963 connetion_threads + i + 1,
964 sizeof (pthread_t) * (connetion_threads_num - i - 1));
967 connetion_threads_num--;
968 pthread_mutex_unlock (&connetion_threads_lock);
972 } /* }}} void *connection_thread_main */
974 static int open_listen_socket_unix (const char *path) /* {{{ */
977 struct sockaddr_un sa;
978 listen_socket_t *temp;
981 temp = (listen_socket_t *) realloc (listen_fds,
982 sizeof (listen_fds[0]) * (listen_fds_num + 1));
985 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: realloc failed.");
989 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
991 fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
994 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: socket(2) failed.");
998 memset (&sa, 0, sizeof (sa));
999 sa.sun_family = AF_UNIX;
1000 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
1002 status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
1005 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: bind(2) failed.");
1011 status = listen (fd, /* backlog = */ 10);
1014 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: listen(2) failed.");
1020 listen_fds[listen_fds_num].fd = fd;
1021 snprintf (listen_fds[listen_fds_num].path,
1022 sizeof (listen_fds[listen_fds_num].path) - 1,
1027 } /* }}} int open_listen_socket_unix */
1029 static int open_listen_socket (const char *addr) /* {{{ */
1031 struct addrinfo ai_hints;
1032 struct addrinfo *ai_res;
1033 struct addrinfo *ai_ptr;
1036 assert (addr != NULL);
1038 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
1039 return (open_listen_socket_unix (addr + strlen ("unix:")));
1040 else if (addr[0] == '/')
1041 return (open_listen_socket_unix (addr));
1043 memset (&ai_hints, 0, sizeof (ai_hints));
1044 ai_hints.ai_flags = 0;
1045 #ifdef AI_ADDRCONFIG
1046 ai_hints.ai_flags |= AI_ADDRCONFIG;
1048 ai_hints.ai_family = AF_UNSPEC;
1049 ai_hints.ai_socktype = SOCK_STREAM;
1052 status = getaddrinfo (addr, RRDCACHED_DEFAULT_PORT, &ai_hints, &ai_res);
1055 RRDD_LOG (LOG_ERR, "open_listen_socket: getaddrinfo(%s) failed: "
1056 "%s", addr, gai_strerror (status));
1060 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1063 listen_socket_t *temp;
1065 temp = (listen_socket_t *) realloc (listen_fds,
1066 sizeof (listen_fds[0]) * (listen_fds_num + 1));
1069 RRDD_LOG (LOG_ERR, "open_listen_socket: realloc failed.");
1073 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1075 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1078 RRDD_LOG (LOG_ERR, "open_listen_socket: socket(2) failed.");
1082 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1085 RRDD_LOG (LOG_ERR, "open_listen_socket: bind(2) failed.");
1090 status = listen (fd, /* backlog = */ 10);
1093 RRDD_LOG (LOG_ERR, "open_listen_socket: listen(2) failed.");
1098 listen_fds[listen_fds_num].fd = fd;
1099 strncpy (listen_fds[listen_fds_num].path, addr,
1100 sizeof (listen_fds[listen_fds_num].path) - 1);
1102 } /* for (ai_ptr) */
1105 } /* }}} int open_listen_socket */
1107 static int close_listen_sockets (void) /* {{{ */
1111 for (i = 0; i < listen_fds_num; i++)
1113 close (listen_fds[i].fd);
1114 if (strncmp ("unix:", listen_fds[i].path, strlen ("unix:")) == 0)
1115 unlink (listen_fds[i].path + strlen ("unix:"));
1123 } /* }}} int close_listen_sockets */
1125 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
1127 struct pollfd *pollfds;
1132 for (i = 0; i < config_listen_address_list_len; i++)
1134 RRDD_LOG (LOG_DEBUG, "listen_thread_main: config_listen_address_list[%i] "
1135 "= %s", i, config_listen_address_list[i]);
1136 open_listen_socket (config_listen_address_list[i]);
1139 if (config_listen_address_list_len < 1)
1140 open_listen_socket (RRDCACHED_DEFAULT_ADDRESS);
1142 if (listen_fds_num < 1)
1144 RRDD_LOG (LOG_ERR, "listen_thread_main: No listen sockets "
1145 "could be opened. Sorry.");
1149 pollfds_num = listen_fds_num;
1150 pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
1151 if (pollfds == NULL)
1153 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1156 memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
1158 while (do_shutdown == 0)
1160 assert (pollfds_num == ((int) listen_fds_num));
1161 for (i = 0; i < pollfds_num; i++)
1163 pollfds[i].fd = listen_fds[i].fd;
1164 pollfds[i].events = POLLIN | POLLPRI;
1165 pollfds[i].revents = 0;
1168 status = poll (pollfds, pollfds_num, /* timeout = */ -1);
1172 if (status != EINTR)
1174 RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
1179 for (i = 0; i < pollfds_num; i++)
1182 struct sockaddr_storage client_sa;
1183 socklen_t client_sa_size;
1186 if (pollfds[i].revents == 0)
1189 if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
1191 RRDD_LOG (LOG_ERR, "listen_thread_main: "
1192 "poll(2) returned something unexpected for listen FD #%i.",
1197 client_sd = (int *) malloc (sizeof (int));
1198 if (client_sd == NULL)
1200 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1204 client_sa_size = sizeof (client_sa);
1205 *client_sd = accept (pollfds[i].fd,
1206 (struct sockaddr *) &client_sa, &client_sa_size);
1209 RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
1213 status = pthread_create (&tid, /* attr = */ NULL, connection_thread_main,
1214 /* args = */ (void *) client_sd);
1217 RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
1222 } /* for (pollfds_num) */
1223 } /* while (do_shutdown == 0) */
1225 close_listen_sockets ();
1227 pthread_mutex_lock (&connetion_threads_lock);
1228 while (connetion_threads_num > 0)
1232 wait_for = connetion_threads[0];
1234 pthread_mutex_unlock (&connetion_threads_lock);
1235 pthread_join (wait_for, /* retval = */ NULL);
1236 pthread_mutex_lock (&connetion_threads_lock);
1238 pthread_mutex_unlock (&connetion_threads_lock);
1240 RRDD_LOG (LOG_DEBUG, "listen_thread_main: Exiting.");
1243 } /* }}} void *listen_thread_main */
1245 static int daemonize (void) /* {{{ */
1251 /* These structures are static, because `sigaction' behaves weird if the are
1253 static struct sigaction sa_int;
1254 static struct sigaction sa_term;
1255 static struct sigaction sa_pipe;
1260 fprintf (stderr, "daemonize: fork(2) failed.\n");
1268 /* Change into the /tmp directory. */
1269 base_dir = (config_base_dir != NULL)
1272 status = chdir (base_dir);
1275 fprintf (stderr, "daemonize: chdir (%s) failed.\n", base_dir);
1279 /* Become session leader */
1282 /* Open the first three file descriptors to /dev/null */
1287 open ("/dev/null", O_RDWR);
1291 /* Install signal handlers */
1292 memset (&sa_int, 0, sizeof (sa_int));
1293 sa_int.sa_handler = sig_int_handler;
1294 sigaction (SIGINT, &sa_int, NULL);
1296 memset (&sa_term, 0, sizeof (sa_term));
1297 sa_term.sa_handler = sig_term_handler;
1298 sigaction (SIGINT, &sa_term, NULL);
1300 memset (&sa_pipe, 0, sizeof (sa_pipe));
1301 sa_pipe.sa_handler = SIG_IGN;
1302 sigaction (SIGPIPE, &sa_pipe, NULL);
1304 openlog ("rrdcached", LOG_PID, LOG_DAEMON);
1306 cache_tree = g_tree_new ((GCompareFunc) strcmp);
1307 if (cache_tree == NULL)
1309 RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
1313 memset (&queue_thread, 0, sizeof (queue_thread));
1314 status = pthread_create (&queue_thread, /* attr = */ NULL,
1315 queue_thread_main, /* args = */ NULL);
1318 RRDD_LOG (LOG_ERR, "daemonize: pthread_create failed.");
1325 } /* }}} int daemonize */
1327 static int cleanup (void) /* {{{ */
1329 RRDD_LOG (LOG_DEBUG, "cleanup ()");
1333 RRDD_LOG (LOG_DEBUG, "cleanup: Joining queue_thread..");
1334 pthread_cond_signal (&cache_cond);
1335 pthread_join (queue_thread, /* return = */ NULL);
1336 RRDD_LOG (LOG_DEBUG, "cleanup: done");
1343 } /* }}} int cleanup */
1345 static int read_options (int argc, char **argv) /* {{{ */
1350 while ((option = getopt(argc, argv, "l:f:w:b:p:h?")) != -1)
1358 temp = (char **) realloc (config_listen_address_list,
1359 sizeof (char *) * (config_listen_address_list_len + 1));
1362 fprintf (stderr, "read_options: realloc failed.\n");
1365 config_listen_address_list = temp;
1367 temp[config_listen_address_list_len] = strdup (optarg);
1368 if (temp[config_listen_address_list_len] == NULL)
1370 fprintf (stderr, "read_options: strdup failed.\n");
1373 config_listen_address_list_len++;
1381 temp = atoi (optarg);
1383 config_flush_interval = temp;
1386 fprintf (stderr, "Invalid flush interval: %s\n", optarg);
1396 temp = atoi (optarg);
1398 config_write_interval = temp;
1401 fprintf (stderr, "Invalid write interval: %s\n", optarg);
1411 if (config_base_dir != NULL)
1412 free (config_base_dir);
1413 config_base_dir = strdup (optarg);
1414 if (config_base_dir == NULL)
1416 fprintf (stderr, "read_options: strdup failed.\n");
1420 len = strlen (config_base_dir);
1421 while ((len > 0) && (config_base_dir[len - 1] == '/'))
1423 config_base_dir[len - 1] = 0;
1429 fprintf (stderr, "Invalid base directory: %s\n", optarg);
1437 if (config_pid_file != NULL)
1438 free (config_pid_file);
1439 config_pid_file = strdup (optarg);
1440 if (config_pid_file == NULL)
1442 fprintf (stderr, "read_options: strdup failed.\n");
1450 printf ("RRDd %s Copyright (C) 2008 Florian octo Forster\n"
1452 "Usage: rrdcached [options]\n"
1454 "Valid options are:\n"
1455 " -l <address> Socket address to listen to.\n"
1456 " -w <seconds> Interval in which to write data.\n"
1457 " -f <seconds> Interval in which to flush dead data.\n"
1458 " -p <file> Location of the PID-file.\n"
1459 " -b <dir> Base directory to change to.\n"
1461 "For more information and a detailed description of all options "
1463 "to the rrdcached(1) manual page.\n",
1467 } /* switch (option) */
1468 } /* while (getopt) */
1471 } /* }}} int read_options */
1473 int main (int argc, char **argv)
1477 status = read_options (argc, argv);
1485 status = daemonize ();
1488 struct sigaction sigchld;
1490 memset (&sigchld, 0, sizeof (sigchld));
1491 sigchld.sa_handler = SIG_IGN;
1492 sigaction (SIGCHLD, &sigchld, NULL);
1496 else if (status != 0)
1498 fprintf (stderr, "daemonize failed, exiting.\n");
1502 listen_thread_main (NULL);
1510 * vim: set sw=2 sts=2 ts=8 et fdm=marker :