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"
70 #include <sys/types.h>
74 #include <sys/socket.h>
85 #include <glib-2.0/glib.h>
88 #define RRDD_LOG(severity, ...) syslog ((severity), __VA_ARGS__)
91 # define __attribute__(x) /**/
97 struct listen_socket_s
100 char path[PATH_MAX + 1];
102 typedef struct listen_socket_s listen_socket_t;
105 typedef struct cache_item_s cache_item_t;
111 time_t last_flush_time;
112 #define CI_FLAGS_IN_TREE 0x01
113 #define CI_FLAGS_IN_QUEUE 0x02
122 static listen_socket_t *listen_fds = NULL;
123 static size_t listen_fds_num = 0;
125 static int do_shutdown = 0;
127 static pthread_t queue_thread;
129 static pthread_t *connetion_threads = NULL;
130 static pthread_mutex_t connetion_threads_lock = PTHREAD_MUTEX_INITIALIZER;
131 static int connetion_threads_num = 0;
134 static GTree *cache_tree = NULL;
135 static cache_item_t *cache_queue_head = NULL;
136 static cache_item_t *cache_queue_tail = NULL;
137 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
138 static pthread_cond_t cache_cond = PTHREAD_COND_INITIALIZER;
140 static int config_write_interval = 300;
141 static int config_flush_interval = 3600;
143 static char **config_listen_address_list = NULL;
144 static int config_listen_address_list_len = 0;
149 static void sig_int_handler (int s __attribute__((unused))) /* {{{ */
152 } /* }}} void sig_int_handler */
154 static void sig_term_handler (int s __attribute__((unused))) /* {{{ */
157 } /* }}} void sig_term_handler */
160 * enqueue_cache_item:
161 * `cache_lock' must be acquired before calling this function!
163 static int enqueue_cache_item (cache_item_t *ci) /* {{{ */
165 RRDD_LOG (LOG_DEBUG, "enqueue_cache_item: Adding %s to the update queue.",
171 if ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
174 assert (ci->next == NULL);
176 if (ci->values_num == 0)
179 if (cache_queue_tail == NULL)
180 cache_queue_head = ci;
182 cache_queue_tail->next = ci;
183 cache_queue_tail = ci;
186 } /* }}} int enqueue_cache_item */
189 * tree_callback_flush:
190 * Called via `g_tree_foreach' in `queue_thread_main'. `cache_lock' is held
191 * while this is in progress.
193 static gboolean tree_callback_flush (gpointer key /* {{{ */
194 __attribute__((unused)), gpointer value, gpointer data)
199 key = NULL; /* make compiler happy */
201 ci = (cache_item_t *) value;
202 now = *((time_t *) data);
204 if (((now - ci->last_flush_time) >= config_write_interval)
205 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0))
206 enqueue_cache_item (ci);
209 } /* }}} gboolean tree_callback_flush */
211 static void *queue_thread_main (void *args __attribute__((unused))) /* {{{ */
214 struct timespec next_flush;
216 gettimeofday (&now, NULL);
217 next_flush.tv_sec = now.tv_sec + config_flush_interval;
218 next_flush.tv_nsec = 1000 * now.tv_usec;
220 pthread_mutex_lock (&cache_lock);
221 while ((do_shutdown == 0) || (cache_queue_head != NULL))
230 /* First, check if it's time to do the cache flush. */
231 gettimeofday (&now, NULL);
232 if ((now.tv_sec > next_flush.tv_sec)
233 || ((now.tv_sec == next_flush.tv_sec)
234 && ((1000 * now.tv_usec) > next_flush.tv_nsec)))
238 /* Pass the current time as user data so that we don't need to call
239 * `time' for each node. */
240 time_now = time (NULL);
242 g_tree_foreach (cache_tree, tree_callback_flush, (gpointer) &time_now);
244 /* Determine the time of the next cache flush. */
245 while (next_flush.tv_sec < now.tv_sec)
246 next_flush.tv_sec += config_flush_interval;
249 /* Now, check if there's something to store away. If not, wait until
250 * something comes in or it's time to do the cache flush. */
251 if (cache_queue_head == NULL)
253 status = pthread_cond_timedwait (&cache_cond, &cache_lock, &next_flush);
254 if ((status != 0) && (status != ETIMEDOUT))
256 RRDD_LOG (LOG_ERR, "queue_thread_main: "
257 "pthread_cond_timedwait returned %i.", status);
261 /* Check if a value has arrived. This may be NULL if we timed out or there
262 * was an interrupt such as a signal. */
263 if (cache_queue_head == NULL)
266 ci = cache_queue_head;
268 /* copy the relevant parts */
269 file = strdup (ci->file);
272 RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
277 values_num = ci->values_num;
282 ci->last_flush_time = time (NULL);
283 ci->flags &= ~(CI_FLAGS_IN_QUEUE);
285 cache_queue_head = ci->next;
286 if (cache_queue_head == NULL)
287 cache_queue_tail = NULL;
290 pthread_mutex_unlock (&cache_lock);
292 RRDD_LOG (LOG_DEBUG, "queue_thread_main: rrd_update (%s, %i, %p)",
293 file, values_num, (void *) values);
295 status = rrd_update_r (file, NULL, values_num, (void *) values);
298 RRDD_LOG (LOG_ERR, "queue_thread_main: "
299 "rrd_update_r failed with status %i.",
304 for (i = 0; i < values_num; i++)
307 pthread_mutex_lock (&cache_lock);
308 } /* while (do_shutdown == 0) */
309 pthread_mutex_unlock (&cache_lock);
311 RRDD_LOG (LOG_DEBUG, "queue_thread_main: Exiting.");
314 } /* }}} void *queue_thread_main */
316 static int handle_request_update (int fd, /* {{{ */
317 char *buffer, int buffer_size __attribute__((unused)))
335 buffer_ptr += strlen (file) + 1;
337 pthread_mutex_lock (&cache_lock);
339 ci = g_tree_lookup (cache_tree, file);
342 ci = (cache_item_t *) malloc (sizeof (cache_item_t));
345 pthread_mutex_unlock (&cache_lock);
346 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
349 memset (ci, 0, sizeof (cache_item_t));
351 ci->file = strdup (file);
352 if (ci->file == NULL)
354 pthread_mutex_unlock (&cache_lock);
355 RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
362 ci->last_flush_time = now;
363 ci->flags = CI_FLAGS_IN_TREE;
365 g_tree_insert (cache_tree, (void *) ci->file, (void *) ci);
367 RRDD_LOG (LOG_DEBUG, "handle_request_update: Created new tree node %s.",
372 while (*buffer_ptr != 0)
377 buffer_ptr += strlen (value) + 1;
379 temp = (char **) realloc (ci->values,
380 sizeof (char *) * (ci->values_num + 1));
383 RRDD_LOG (LOG_ERR, "handle_request_update: realloc failed.");
388 ci->values[ci->values_num] = strdup (value);
389 if (ci->values[ci->values_num] == NULL)
391 RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
399 if (((now - ci->last_flush_time) >= config_write_interval)
400 && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0))
402 enqueue_cache_item (ci);
403 pthread_cond_signal (&cache_cond);
406 pthread_mutex_unlock (&cache_lock);
408 snprintf (answer, sizeof (answer), "0 Enqueued %i value(s)\n", values_num);
409 answer[sizeof (answer) - 1] = 0;
411 status = write (fd, answer, sizeof (answer));
415 RRDD_LOG (LOG_INFO, "handle_request_update: write(2) returned an error.");
420 } /* }}} int handle_request_update */
422 static int handle_request (int fd) /* {{{ */
427 buffer_size = read (fd, buffer, sizeof (buffer));
430 RRDD_LOG (LOG_ERR, "handle_request: read(2) failed.");
433 assert (((size_t) buffer_size) <= sizeof (buffer));
435 if ((buffer[buffer_size - 2] != 0)
436 || (buffer[buffer_size - 1] != 0))
438 RRDD_LOG (LOG_INFO, "handle_request: malformed request.");
442 /* fields in the buffer a separated by null bytes. */
443 if (strcmp (buffer, "update") == 0)
445 int offset = strlen ("update") + 1;
446 return (handle_request_update (fd, buffer + offset,
447 buffer_size - offset));
451 RRDD_LOG (LOG_INFO, "handle_request: unknown command: %s.", buffer);
454 } /* }}} int handle_request */
456 static void *connection_thread_main (void *args /* {{{ */
457 __attribute__((unused)))
463 fd = *((int *) args);
465 pthread_mutex_lock (&connetion_threads_lock);
469 temp = (pthread_t *) realloc (connetion_threads,
470 sizeof (pthread_t) * (connetion_threads_num + 1));
473 RRDD_LOG (LOG_ERR, "connection_thread_main: realloc failed.");
477 connetion_threads = temp;
478 connetion_threads[connetion_threads_num] = pthread_self ();
479 connetion_threads_num++;
482 pthread_mutex_unlock (&connetion_threads_lock);
484 while (do_shutdown == 0)
486 struct pollfd pollfd;
490 pollfd.events = POLLIN | POLLPRI;
493 status = poll (&pollfd, 1, /* timeout = */ 500);
494 if (status == 0) /* timeout */
496 else if (status < 0) /* error */
501 RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
505 if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
510 else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
512 RRDD_LOG (LOG_WARNING, "connection_thread_main: "
513 "poll(2) returned something unexpected: %#04hx",
519 status = handle_request (fd);
527 self = pthread_self ();
528 /* Remove this thread from the connection threads list */
529 pthread_mutex_lock (&connetion_threads_lock);
530 /* Find out own index in the array */
531 for (i = 0; i < connetion_threads_num; i++)
532 if (pthread_equal (connetion_threads[i], self) != 0)
534 assert (i < connetion_threads_num);
536 /* Move the trailing threads forward. */
537 if (i < (connetion_threads_num - 1))
539 memmove (connetion_threads + i,
540 connetion_threads + i + 1,
541 sizeof (pthread_t) * (connetion_threads_num - i - 1));
544 connetion_threads_num--;
545 pthread_mutex_unlock (&connetion_threads_lock);
549 } /* }}} void *connection_thread_main */
551 static int open_listen_socket_unix (const char *path) /* {{{ */
554 struct sockaddr_un sa;
555 listen_socket_t *temp;
558 temp = (listen_socket_t *) realloc (listen_fds,
559 sizeof (listen_fds[0]) * (listen_fds_num + 1));
562 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: realloc failed.");
566 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
568 fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
571 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: socket(2) failed.");
575 memset (&sa, 0, sizeof (sa));
576 sa.sun_family = AF_UNIX;
577 strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
579 status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
582 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: bind(2) failed.");
588 status = listen (fd, /* backlog = */ 10);
591 RRDD_LOG (LOG_ERR, "open_listen_socket_unix: listen(2) failed.");
597 listen_fds[listen_fds_num].fd = fd;
598 snprintf (listen_fds[listen_fds_num].path,
599 sizeof (listen_fds[listen_fds_num].path) - 1,
604 } /* }}} int open_listen_socket_unix */
606 static int open_listen_socket (const char *addr) /* {{{ */
608 struct addrinfo ai_hints;
609 struct addrinfo *ai_res;
610 struct addrinfo *ai_ptr;
613 assert (addr != NULL);
615 if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
616 return (open_listen_socket_unix (addr + strlen ("unix:")));
617 else if (addr[0] == '/')
618 return (open_listen_socket_unix (addr));
620 memset (&ai_hints, 0, sizeof (ai_hints));
621 ai_hints.ai_flags = 0;
623 ai_hints.ai_flags |= AI_ADDRCONFIG;
625 ai_hints.ai_family = AF_UNSPEC;
626 ai_hints.ai_socktype = SOCK_STREAM;
629 status = getaddrinfo (addr, DEFAULT_PORT, &ai_hints, &ai_res);
632 RRDD_LOG (LOG_ERR, "open_listen_socket: getaddrinfo(%s) failed: "
633 "%s", addr, gai_strerror (status));
637 for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
640 listen_socket_t *temp;
642 temp = (listen_socket_t *) realloc (listen_fds,
643 sizeof (listen_fds[0]) * (listen_fds_num + 1));
646 RRDD_LOG (LOG_ERR, "open_listen_socket: realloc failed.");
650 memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
652 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
655 RRDD_LOG (LOG_ERR, "open_listen_socket: socket(2) failed.");
659 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
662 RRDD_LOG (LOG_ERR, "open_listen_socket: bind(2) failed.");
667 status = listen (fd, /* backlog = */ 10);
670 RRDD_LOG (LOG_ERR, "open_listen_socket: listen(2) failed.");
675 listen_fds[listen_fds_num].fd = fd;
676 strncpy (listen_fds[listen_fds_num].path, addr,
677 sizeof (listen_fds[listen_fds_num].path) - 1);
682 } /* }}} int open_listen_socket */
684 static int close_listen_sockets (void) /* {{{ */
688 for (i = 0; i < listen_fds_num; i++)
690 close (listen_fds[i].fd);
691 if (strncmp ("unix:", listen_fds[i].path, strlen ("unix:")) == 0)
692 unlink (listen_fds[i].path + strlen ("unix:"));
700 } /* }}} int close_listen_sockets */
702 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
704 struct pollfd *pollfds;
709 for (i = 0; i < config_listen_address_list_len; i++)
711 RRDD_LOG (LOG_DEBUG, "listen_thread_main: config_listen_address_list[%i] "
712 "= %s", i, config_listen_address_list[i]);
713 open_listen_socket (config_listen_address_list[i]);
716 if (config_listen_address_list_len < 1)
717 open_listen_socket (RRDD_SOCK_PATH);
719 if (listen_fds_num < 1)
721 RRDD_LOG (LOG_ERR, "listen_thread_main: No listen sockets "
722 "could be opened. Sorry.");
726 pollfds_num = listen_fds_num;
727 pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
730 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
733 memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
735 while (do_shutdown == 0)
737 assert (pollfds_num == ((int) listen_fds_num));
738 for (i = 0; i < pollfds_num; i++)
740 pollfds[i].fd = listen_fds[i].fd;
741 pollfds[i].events = POLLIN | POLLPRI;
742 pollfds[i].revents = 0;
745 status = poll (pollfds, pollfds_num, /* timeout = */ -1);
751 RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
756 for (i = 0; i < pollfds_num; i++)
759 struct sockaddr_storage client_sa;
760 socklen_t client_sa_size;
763 if (pollfds[i].revents == 0)
766 if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
768 RRDD_LOG (LOG_ERR, "listen_thread_main: "
769 "poll(2) returned something unexpected for listen FD #%i.",
774 client_sd = (int *) malloc (sizeof (int));
775 if (client_sd == NULL)
777 RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
781 client_sa_size = sizeof (client_sa);
782 *client_sd = accept (pollfds[i].fd,
783 (struct sockaddr *) &client_sa, &client_sa_size);
786 RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
790 status = pthread_create (&tid, /* attr = */ NULL, connection_thread_main,
791 /* args = */ (void *) client_sd);
794 RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
799 } /* for (pollfds_num) */
800 } /* while (do_shutdown == 0) */
802 close_listen_sockets ();
804 pthread_mutex_lock (&connetion_threads_lock);
805 while (connetion_threads_num > 0)
809 wait_for = connetion_threads[0];
811 pthread_mutex_unlock (&connetion_threads_lock);
812 pthread_join (wait_for, /* retval = */ NULL);
813 pthread_mutex_lock (&connetion_threads_lock);
815 pthread_mutex_unlock (&connetion_threads_lock);
817 RRDD_LOG (LOG_DEBUG, "listen_thread_main: Exiting.");
820 } /* }}} void *listen_thread_main */
822 static int daemonize (void) /* {{{ */
830 fprintf (stderr, "daemonize: fork(2) failed.\n");
838 /* Change into the /tmp directory. */
841 /* Become session leader */
844 /* Open the first three file descriptors to /dev/null */
849 open ("/dev/null", O_RDWR);
856 memset (&sa, 0, sizeof (sa));
857 sa.sa_handler = sig_int_handler;
858 sigaction (SIGINT, &sa, NULL);
860 memset (&sa, 0, sizeof (sa));
861 sa.sa_handler = sig_term_handler;
862 sigaction (SIGINT, &sa, NULL);
864 memset (&sa, 0, sizeof (sa));
865 sa.sa_handler = SIG_IGN;
866 sigaction (SIGPIPE, &sa, NULL);
869 openlog ("rrdd", LOG_PID, LOG_DAEMON);
871 cache_tree = g_tree_new ((GCompareFunc) strcmp);
872 if (cache_tree == NULL)
874 RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
878 memset (&queue_thread, 0, sizeof (queue_thread));
879 status = pthread_create (&queue_thread, /* attr = */ NULL,
880 queue_thread_main, /* args = */ NULL);
883 RRDD_LOG (LOG_ERR, "daemonize: pthread_create failed.");
888 } /* }}} int daemonize */
890 static int cleanup (void) /* {{{ */
892 RRDD_LOG (LOG_DEBUG, "cleanup ()");
896 RRDD_LOG (LOG_DEBUG, "cleanup: Joining queue_thread..");
897 pthread_cond_signal (&cache_cond);
898 pthread_join (queue_thread, /* return = */ NULL);
899 RRDD_LOG (LOG_DEBUG, "cleanup: done");
904 } /* }}} int cleanup */
906 static int read_options (int argc, char **argv) /* {{{ */
911 while ((option = getopt(argc, argv, "l:f:w:h?")) != -1)
919 temp = (char **) realloc (config_listen_address_list,
920 sizeof (char *) * (config_listen_address_list_len + 1));
923 fprintf (stderr, "read_options: realloc failed.\n");
926 config_listen_address_list = temp;
928 temp[config_listen_address_list_len] = strdup (optarg);
929 if (temp[config_listen_address_list_len] == NULL)
931 fprintf (stderr, "read_options: strdup failed.\n");
934 config_listen_address_list_len++;
942 temp = atoi (optarg);
944 config_flush_interval = temp;
947 fprintf (stderr, "Invalid flush interval: %s\n", optarg);
957 temp = atoi (optarg);
959 config_write_interval = temp;
962 fprintf (stderr, "Invalid write interval: %s\n", optarg);
970 printf ("RRDd %s Copyright (C) 2008 Florian octo Forster\n"
972 "Usage: rrdd [options]\n"
974 "Valid options are:\n"
975 " -l <address> Socket address to listen to.\n"
976 " -w <seconds> Interval in which to write data.\n"
977 " -f <seconds> Interval in which to flush dead data.\n"
979 "For more information and a detailed description of all options "
981 "to the rrdd(1) manual page.\n",
985 } /* switch (option) */
986 } /* while (getopt) */
989 } /* }}} int read_options */
991 int main (int argc, char **argv)
995 status = read_options (argc, argv);
1003 status = daemonize ();
1006 struct sigaction sigchld;
1008 memset (&sigchld, 0, sizeof (sigchld));
1009 sigchld.sa_handler = SIG_IGN;
1010 sigaction (SIGCHLD, &sigchld, NULL);
1014 else if (status != 0)
1016 fprintf (stderr, "daemonize failed, exiting.\n");
1020 listen_thread_main (NULL);
1028 * vim: set sw=2 sts=2 ts=8 et fdm=marker :