src/rrd_daemon.c: Catch invalid uses of `flush'.
[rrdtool.git] / src / rrd_daemon.c
1 /**
2  * RRDTool - src/rrd_daemon.c
3  * Copyright (C) 2008 Florian octo Forster
4  *
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.
8  *
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.
13  *
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
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 /*
23  * First tell the compiler to stick to the C99 and POSIX standards as close as
24  * possible.
25  */
26 #ifndef __STRICT_ANSI__ /* {{{ */
27 # define __STRICT_ANSI__
28 #endif
29
30 #ifndef _ISOC99_SOURCE
31 # define _ISOC99_SOURCE
32 #endif
33
34 #ifdef _POSIX_C_SOURCE
35 # undef _POSIX_C_SOURCE
36 #endif
37 #define _POSIX_C_SOURCE 200112L
38
39 /* Single UNIX needed for strdup. */
40 #ifdef _XOPEN_SOURCE
41 # undef _XOPEN_SOURCE
42 #endif
43 #define _XOPEN_SOURCE 500
44
45 #ifndef _REENTRANT
46 # define _REENTRANT
47 #endif
48
49 #ifndef _THREAD_SAFE
50 # define _THREAD_SAFE
51 #endif
52
53 #ifdef _GNU_SOURCE
54 # undef _GNU_SOURCE
55 #endif
56 /* }}} */
57
58 /*
59  * Now for some includes..
60  */
61 #include "rrd.h" /* {{{ */
62 #include "rrd_client.h"
63
64 #include <stdlib.h>
65 #include <stdint.h>
66 #include <stdio.h>
67 #include <unistd.h>
68 #include <string.h>
69 #include <stdint.h>
70 #include <inttypes.h>
71
72 #include <sys/types.h>
73 #include <sys/stat.h>
74 #include <fcntl.h>
75 #include <signal.h>
76 #include <sys/socket.h>
77 #include <sys/un.h>
78 #include <netdb.h>
79 #include <poll.h>
80 #include <syslog.h>
81 #include <pthread.h>
82 #include <errno.h>
83 #include <assert.h>
84 #include <sys/time.h>
85 #include <time.h>
86
87 #include <glib-2.0/glib.h>
88 /* }}} */
89
90 #define RRDD_LOG(severity, ...) syslog ((severity), __VA_ARGS__)
91
92 #ifndef __GNUC__
93 # define __attribute__(x) /**/
94 #endif
95
96 /*
97  * Types
98  */
99 struct listen_socket_s
100 {
101   int fd;
102   char path[PATH_MAX + 1];
103 };
104 typedef struct listen_socket_s listen_socket_t;
105
106 struct cache_item_s;
107 typedef struct cache_item_s cache_item_t;
108 struct cache_item_s
109 {
110   char *file;
111   char **values;
112   int values_num;
113   time_t last_flush_time;
114 #define CI_FLAGS_IN_TREE  0x01
115 #define CI_FLAGS_IN_QUEUE 0x02
116   int flags;
117
118   cache_item_t *next;
119 };
120
121 struct callback_flush_data_s
122 {
123   time_t now;
124   char **keys;
125   size_t keys_num;
126 };
127 typedef struct callback_flush_data_s callback_flush_data_t;
128
129 enum queue_side_e
130 {
131   HEAD,
132   TAIL
133 };
134 typedef enum queue_side_e queue_side_t;
135
136 /*
137  * Variables
138  */
139 static listen_socket_t *listen_fds = NULL;
140 static size_t listen_fds_num = 0;
141
142 static int do_shutdown = 0;
143
144 static pthread_t queue_thread;
145
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;
149
150 /* Cache stuff */
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;
156
157 static pthread_cond_t  flush_cond = PTHREAD_COND_INITIALIZER;
158
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;
163
164 static char **config_listen_address_list = NULL;
165 static int config_listen_address_list_len = 0;
166
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;
171
172 /* 
173  * Functions
174  */
175 static void sig_int_handler (int s __attribute__((unused))) /* {{{ */
176 {
177   do_shutdown++;
178 } /* }}} void sig_int_handler */
179
180 static void sig_term_handler (int s __attribute__((unused))) /* {{{ */
181 {
182   do_shutdown++;
183 } /* }}} void sig_term_handler */
184
185 static int write_pidfile (void) /* {{{ */
186 {
187   pid_t pid;
188   char *file;
189   FILE *fh;
190
191   pid = getpid ();
192   
193   file = (config_pid_file != NULL)
194     ? config_pid_file
195     : LOCALSTATEDIR "/run/rrdcached.pid";
196
197   fh = fopen (file, "w");
198   if (fh == NULL)
199   {
200     RRDD_LOG (LOG_ERR, "write_pidfile: Opening `%s' failed.", file);
201     return (-1);
202   }
203
204   fprintf (fh, "%i\n", (int) pid);
205   fclose (fh);
206
207   return (0);
208 } /* }}} int write_pidfile */
209
210 static int remove_pidfile (void) /* {{{ */
211 {
212   char *file;
213   int status;
214
215   file = (config_pid_file != NULL)
216     ? config_pid_file
217     : LOCALSTATEDIR "/run/rrdcached.pid";
218
219   status = unlink (file);
220   if (status == 0)
221     return (0);
222   return (errno);
223 } /* }}} int remove_pidfile */
224
225 /*
226  * enqueue_cache_item:
227  * `cache_lock' must be acquired before calling this function!
228  */
229 static int enqueue_cache_item (cache_item_t *ci, /* {{{ */
230     queue_side_t side)
231 {
232   int did_insert = 0;
233
234   RRDD_LOG (LOG_DEBUG, "enqueue_cache_item: Adding %s to the update queue.",
235       ci->file);
236
237   if (ci == NULL)
238     return (-1);
239
240   if (ci->values_num == 0)
241     return (0);
242
243   if (side == HEAD)
244   {
245     if ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
246     {
247       assert (ci->next == NULL);
248       ci->next = cache_queue_head;
249       cache_queue_head = ci;
250
251       if (cache_queue_tail == NULL)
252         cache_queue_tail = cache_queue_head;
253
254       did_insert = 1;
255     }
256     else if (cache_queue_head == ci)
257     {
258       /* do nothing */
259     }
260     else /* enqueued, but not first entry */
261     {
262       cache_item_t *prev;
263
264       /* find previous entry */
265       for (prev = cache_queue_head; prev != NULL; prev = prev->next)
266         if (prev->next == ci)
267           break;
268       assert (prev != NULL);
269
270       /* move to the front */
271       prev->next = ci->next;
272       ci->next = cache_queue_head;
273       cache_queue_head = ci;
274
275       /* check if we need to adapt the tail */
276       if (cache_queue_tail == ci)
277         cache_queue_tail = prev;
278     }
279   }
280   else /* (side == TAIL) */
281   {
282     /* We don't move values back in the list.. */
283     if ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
284       return (0);
285
286     assert (ci->next == NULL);
287
288     if (cache_queue_tail == NULL)
289       cache_queue_head = ci;
290     else
291       cache_queue_tail->next = ci;
292     cache_queue_tail = ci;
293
294     did_insert = 1;
295   }
296
297   ci->flags |= CI_FLAGS_IN_QUEUE;
298
299   if (did_insert)
300   {
301     pthread_mutex_lock (&stats_lock);
302     stats_queue_length++;
303     pthread_mutex_unlock (&stats_lock);
304   }
305
306   return (0);
307 } /* }}} int enqueue_cache_item */
308
309 /*
310  * tree_callback_flush:
311  * Called via `g_tree_foreach' in `queue_thread_main'. `cache_lock' is held
312  * while this is in progress.
313  */
314 static gboolean tree_callback_flush (gpointer key, gpointer value, /* {{{ */
315     gpointer data)
316 {
317   cache_item_t *ci;
318   callback_flush_data_t *cfd;
319
320   ci = (cache_item_t *) value;
321   cfd = (callback_flush_data_t *) data;
322
323   if (((cfd->now - ci->last_flush_time) >= config_write_interval)
324       && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
325       && (ci->values_num > 0))
326   {
327     enqueue_cache_item (ci, TAIL);
328   }
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))
332   {
333     char **temp;
334
335     temp = (char **) realloc (cfd->keys,
336         sizeof (char *) * (cfd->keys_num + 1));
337     if (temp == NULL)
338     {
339       RRDD_LOG (LOG_ERR, "tree_callback_flush: realloc failed.");
340       return (FALSE);
341     }
342     cfd->keys = temp;
343     /* Make really sure this points to the _same_ place */
344     assert ((char *) key == ci->file);
345     cfd->keys[cfd->keys_num] = (char *) key;
346     cfd->keys_num++;
347   }
348
349   return (FALSE);
350 } /* }}} gboolean tree_callback_flush */
351
352 static void *queue_thread_main (void *args __attribute__((unused))) /* {{{ */
353 {
354   struct timeval now;
355   struct timespec next_flush;
356
357   gettimeofday (&now, NULL);
358   next_flush.tv_sec = now.tv_sec + config_flush_interval;
359   next_flush.tv_nsec = 1000 * now.tv_usec;
360
361   pthread_mutex_lock (&cache_lock);
362   while ((do_shutdown == 0) || (cache_queue_head != NULL))
363   {
364     cache_item_t *ci;
365     char *file;
366     char **values;
367     int values_num;
368     int status;
369     int i;
370
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)))
376     {
377       callback_flush_data_t cfd;
378       size_t k;
379
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);
384       cfd.keys = NULL;
385       cfd.keys_num = 0;
386
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);
392
393       for (k = 0; k < cfd.keys_num; k++)
394       {
395         /* This must not fail. */
396         ci = (cache_item_t *) g_tree_lookup (cache_tree, cfd.keys[k]);
397         assert (ci != NULL);
398
399         /* If we end up here with values available, something's seriously
400          * messed up. */
401         assert (ci->values_num == 0);
402
403         /* Remove the node from the tree */
404         g_tree_remove (cache_tree, cfd.keys[k]);
405         cfd.keys[k] = NULL;
406
407         /* Now free and clean up `ci'. */
408         free (ci->file);
409         ci->file = NULL;
410         free (ci);
411         ci = NULL;
412       } /* for (k = 0; k < cfd.keys_num; k++) */
413
414       if (cfd.keys != NULL)
415       {
416         free (cfd.keys);
417         cfd.keys = NULL;
418       }
419
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;
423     }
424
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)
428     {
429       status = pthread_cond_timedwait (&cache_cond, &cache_lock, &next_flush);
430       if ((status != 0) && (status != ETIMEDOUT))
431       {
432         RRDD_LOG (LOG_ERR, "queue_thread_main: "
433             "pthread_cond_timedwait returned %i.", status);
434       }
435     }
436
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)
440       continue;
441
442     ci = cache_queue_head;
443
444     /* copy the relevant parts */
445     file = strdup (ci->file);
446     if (file == NULL)
447     {
448       RRDD_LOG (LOG_ERR, "queue_thread_main: strdup failed.");
449       continue;
450     }
451
452     values = ci->values;
453     values_num = ci->values_num;
454
455     ci->values = NULL;
456     ci->values_num = 0;
457
458     ci->last_flush_time = time (NULL);
459     ci->flags &= ~(CI_FLAGS_IN_QUEUE);
460
461     cache_queue_head = ci->next;
462     if (cache_queue_head == NULL)
463       cache_queue_tail = NULL;
464     ci->next = NULL;
465
466     pthread_mutex_lock (&stats_lock);
467     assert (stats_queue_length > 0);
468     stats_queue_length--;
469     pthread_mutex_unlock (&stats_lock);
470
471     pthread_mutex_unlock (&cache_lock);
472
473     RRDD_LOG (LOG_DEBUG, "queue_thread_main: rrd_update (%s, %i, %p)",
474         file, values_num, (void *) values);
475
476     status = rrd_update_r (file, NULL, values_num, (void *) values);
477     if (status != 0)
478     {
479       RRDD_LOG (LOG_ERR, "queue_thread_main: "
480           "rrd_update_r failed with status %i.",
481           status);
482     }
483
484     free (file);
485     for (i = 0; i < values_num; i++)
486       free (values[i]);
487
488     pthread_mutex_lock (&stats_lock);
489     stats_updates_total++;
490     stats_values_total += values_num;
491     pthread_mutex_unlock (&stats_lock);
492
493     pthread_mutex_lock (&cache_lock);
494     pthread_cond_broadcast (&flush_cond);
495   } /* while (do_shutdown == 0) */
496   pthread_mutex_unlock (&cache_lock);
497
498   RRDD_LOG (LOG_DEBUG, "queue_thread_main: Exiting.");
499
500   return (NULL);
501 } /* }}} void *queue_thread_main */
502
503 static int buffer_get_field (char **buffer_ret, /* {{{ */
504     size_t *buffer_size_ret, char **field_ret)
505 {
506   char *buffer;
507   size_t buffer_pos;
508   size_t buffer_size;
509   char *field;
510   size_t field_size;
511   int status;
512
513   buffer = *buffer_ret;
514   buffer_pos = 0;
515   buffer_size = *buffer_size_ret;
516   field = *buffer_ret;
517   field_size = 0;
518
519   if (buffer_size <= 0)
520     return (-1);
521
522   /* This is ensured by `handle_request'. */
523   assert (buffer[buffer_size - 1] == ' ');
524
525   status = -1;
526   while (buffer_pos < buffer_size)
527   {
528     /* Check for end-of-field or end-of-buffer */
529     if (buffer[buffer_pos] == ' ')
530     {
531       field[field_size] = 0;
532       field_size++;
533       buffer_pos++;
534       status = 0;
535       break;
536     }
537     /* Handle escaped characters. */
538     else if (buffer[buffer_pos] == '\\')
539     {
540       if (buffer_pos >= (buffer_size - 1))
541         break;
542       buffer_pos++;
543       field[field_size] = buffer[buffer_pos];
544       field_size++;
545       buffer_pos++;
546     }
547     /* Normal operation */ 
548     else
549     {
550       field[field_size] = buffer[buffer_pos];
551       field_size++;
552       buffer_pos++;
553     }
554   } /* while (buffer_pos < buffer_size) */
555
556   if (status != 0)
557     return (status);
558
559   *buffer_ret = buffer + buffer_pos;
560   *buffer_size_ret = buffer_size - buffer_pos;
561   *field_ret = field;
562
563   return (0);
564 } /* }}} int buffer_get_field */
565
566 static int flush_file (const char *filename) /* {{{ */
567 {
568   cache_item_t *ci;
569
570   pthread_mutex_lock (&cache_lock);
571
572   ci = (cache_item_t *) g_tree_lookup (cache_tree, filename);
573   if (ci == NULL)
574   {
575     pthread_mutex_unlock (&cache_lock);
576     return (ENOENT);
577   }
578
579   /* Enqueue at head */
580   enqueue_cache_item (ci, HEAD);
581   pthread_cond_signal (&cache_cond);
582
583   while ((ci->flags & CI_FLAGS_IN_QUEUE) != 0)
584   {
585     ci = NULL;
586
587     pthread_cond_wait (&flush_cond, &cache_lock);
588
589     ci = g_tree_lookup (cache_tree, filename);
590     if (ci == NULL)
591     {
592       RRDD_LOG (LOG_ERR, "flush_file: Tree node went away "
593           "while waiting for flush.");
594       pthread_mutex_unlock (&cache_lock);
595       return (-1);
596     }
597   }
598
599   pthread_mutex_unlock (&cache_lock);
600   return (0);
601 } /* }}} int flush_file */
602
603 static int handle_request_stats (int fd, /* {{{ */
604     char *buffer __attribute__((unused)),
605     size_t buffer_size __attribute__((unused)))
606 {
607   int status;
608   char outbuf[4096];
609
610   uint64_t copy_queue_length;
611   uint64_t copy_updates_total;
612   uint64_t copy_values_total;
613
614   uint64_t tree_nodes;
615   uint64_t tree_depth;
616
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);
622
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);
627
628 #define RRDD_STATS_SEND \
629   outbuf[sizeof (outbuf) - 1] = 0; \
630   status = write (fd, outbuf, strlen (outbuf)); \
631   if (status < 0) \
632   { \
633     status = errno; \
634     RRDD_LOG (LOG_INFO, "handle_request_stats: write(2) returned an error."); \
635     return (status); \
636   }
637
638   strncpy (outbuf, "5 Statistics follow\n", sizeof (outbuf));
639   RRDD_STATS_SEND;
640
641   snprintf (outbuf, sizeof (outbuf),
642       "QueueLength: %"PRIu64"\n", copy_queue_length);
643   RRDD_STATS_SEND;
644
645   snprintf (outbuf, sizeof (outbuf),
646       "UpdatesWritten: %"PRIu64"\n", copy_updates_total);
647   RRDD_STATS_SEND;
648
649   snprintf (outbuf, sizeof (outbuf),
650       "ValuesWritten: %"PRIu64"\n", copy_values_total);
651   RRDD_STATS_SEND;
652
653   snprintf (outbuf, sizeof (outbuf),
654       "TreeNodesNumber: %"PRIu64"\n", tree_nodes);
655   RRDD_STATS_SEND;
656
657   snprintf (outbuf, sizeof (outbuf),
658       "TreeDepth: %"PRIu64"\n", tree_depth);
659   RRDD_STATS_SEND;
660
661   return (0);
662 } /* }}} int handle_request_stats */
663
664 static int handle_request_flush (int fd, /* {{{ */
665     char *buffer, size_t buffer_size)
666 {
667   char *file;
668   int status;
669   char result[4096];
670
671   status = buffer_get_field (&buffer, &buffer_size, &file);
672   if (status != 0)
673   {
674     strncpy (result, "-1 Usage: flush <filename>\n", sizeof (result));
675   }
676   else
677   {
678     status = flush_file (file);
679     if (status == 0)
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);
683     else if (status < 0)
684       strncpy (result, "-1 Internal error.\n", sizeof (result));
685     else
686       snprintf (result, sizeof (result), "-1 Failed with status %i.\n", status);
687   }
688   result[sizeof (result) - 1] = 0;
689
690   status = write (fd, result, strlen (result));
691   if (status < 0)
692   {
693     status = errno;
694     RRDD_LOG (LOG_INFO, "handle_request_flush: write(2) returned an error.");
695     return (status);
696   }
697
698   return (0);
699 } /* }}} int handle_request_flush */
700
701 static int handle_request_update (int fd, /* {{{ */
702     char *buffer, size_t buffer_size)
703 {
704   char *file;
705   int values_num = 0;
706   int status;
707
708   time_t now;
709
710   cache_item_t *ci;
711   char answer[4096];
712
713   now = time (NULL);
714
715   status = buffer_get_field (&buffer, &buffer_size, &file);
716   if (status != 0)
717   {
718     RRDD_LOG (LOG_INFO, "handle_request_update: Cannot get file name.");
719     return (-1);
720   }
721
722   pthread_mutex_lock (&cache_lock);
723
724   ci = g_tree_lookup (cache_tree, file);
725   if (ci == NULL) /* {{{ */
726   {
727     ci = (cache_item_t *) malloc (sizeof (cache_item_t));
728     if (ci == NULL)
729     {
730       pthread_mutex_unlock (&cache_lock);
731       RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
732       return (-1);
733     }
734     memset (ci, 0, sizeof (cache_item_t));
735
736     ci->file = strdup (file);
737     if (ci->file == NULL)
738     {
739       pthread_mutex_unlock (&cache_lock);
740       RRDD_LOG (LOG_ERR, "handle_request_update: malloc failed.");
741       free (ci);
742       return (-1);
743     }
744
745     ci->values = NULL;
746     ci->values_num = 0;
747     ci->last_flush_time = now;
748     ci->flags = CI_FLAGS_IN_TREE;
749
750     g_tree_insert (cache_tree, (void *) ci->file, (void *) ci);
751
752     RRDD_LOG (LOG_DEBUG, "handle_request_update: Created new tree node %s.",
753         ci->file);
754   } /* }}} */
755   assert (ci != NULL);
756
757   while (buffer_size > 0)
758   {
759     char **temp;
760     char *value;
761
762     status = buffer_get_field (&buffer, &buffer_size, &value);
763     if (status != 0)
764     {
765       RRDD_LOG (LOG_INFO, "handle_request_update: Error reading field.");
766       break;
767     }
768
769     temp = (char **) realloc (ci->values,
770         sizeof (char *) * (ci->values_num + 1));
771     if (temp == NULL)
772     {
773       RRDD_LOG (LOG_ERR, "handle_request_update: realloc failed.");
774       continue;
775     }
776     ci->values = temp;
777
778     ci->values[ci->values_num] = strdup (value);
779     if (ci->values[ci->values_num] == NULL)
780     {
781       RRDD_LOG (LOG_ERR, "handle_request_update: strdup failed.");
782       continue;
783     }
784     ci->values_num++;
785
786     values_num++;
787   }
788
789   if (((now - ci->last_flush_time) >= config_write_interval)
790       && ((ci->flags & CI_FLAGS_IN_QUEUE) == 0)
791       && (ci->values_num > 0))
792   {
793     enqueue_cache_item (ci, TAIL);
794     pthread_cond_signal (&cache_cond);
795   }
796
797   pthread_mutex_unlock (&cache_lock);
798
799   snprintf (answer, sizeof (answer), "0 Enqueued %i value(s)\n", values_num);
800   answer[sizeof (answer) - 1] = 0;
801
802   status = write (fd, answer, strlen (answer));
803   if (status < 0)
804   {
805     status = errno;
806     RRDD_LOG (LOG_INFO, "handle_request_update: write(2) returned an error.");
807     return (status);
808   }
809
810   return (0);
811 } /* }}} int handle_request_update */
812
813 static int handle_request (int fd) /* {{{ */
814 {
815   char buffer[4096];
816   size_t buffer_size;
817   char *buffer_ptr;
818   char *command;
819   int status;
820
821   status = read (fd, buffer, sizeof (buffer));
822   if (status == 0)
823   {
824     return (1);
825   }
826   else if (status < 0)
827   {
828     RRDD_LOG (LOG_ERR, "handle_request: read(2) failed.");
829     return (-1);
830   }
831   buffer_size = status;
832   assert (((size_t) buffer_size) <= sizeof (buffer));
833
834   if (buffer[buffer_size - 1] != '\n')
835   {
836     RRDD_LOG (LOG_INFO, "handle_request: malformed request.");
837     return (-1);
838   }
839
840   /* Accept Windows style line endings, too */
841   if ((buffer_size > 2) && (buffer[buffer_size - 2] == '\r'))
842   {
843     buffer_size--;
844     buffer[buffer_size - 1] = '\n';
845   }
846
847   /* Place the normal field separator at the end to simplify
848    * `buffer_get_field's work. */
849   buffer[buffer_size - 1] = ' ';
850
851   buffer_ptr = buffer;
852   command = NULL;
853   status = buffer_get_field (&buffer_ptr, &buffer_size, &command);
854   if (status != 0)
855   {
856     RRDD_LOG (LOG_INFO, "handle_request: Unable parse command.");
857     return (-1);
858   }
859
860   if (strcmp (command, "update") == 0)
861   {
862     return (handle_request_update (fd, buffer_ptr, buffer_size));
863   }
864   else if (strcmp (command, "flush") == 0)
865   {
866     return (handle_request_flush (fd, buffer_ptr, buffer_size));
867   }
868   else if (strcmp (command, "stats") == 0)
869   {
870     return (handle_request_stats (fd, buffer_ptr, buffer_size));
871   }
872   else
873   {
874     RRDD_LOG (LOG_INFO, "handle_request: unknown command: %s.", buffer);
875     return (-1);
876   }
877 } /* }}} int handle_request */
878
879 static void *connection_thread_main (void *args /* {{{ */
880     __attribute__((unused)))
881 {
882   pthread_t self;
883   int i;
884   int fd;
885   
886   fd = *((int *) args);
887
888   pthread_mutex_lock (&connetion_threads_lock);
889   {
890     pthread_t *temp;
891
892     temp = (pthread_t *) realloc (connetion_threads,
893         sizeof (pthread_t) * (connetion_threads_num + 1));
894     if (temp == NULL)
895     {
896       RRDD_LOG (LOG_ERR, "connection_thread_main: realloc failed.");
897     }
898     else
899     {
900       connetion_threads = temp;
901       connetion_threads[connetion_threads_num] = pthread_self ();
902       connetion_threads_num++;
903     }
904   }
905   pthread_mutex_unlock (&connetion_threads_lock);
906
907   while (do_shutdown == 0)
908   {
909     struct pollfd pollfd;
910     int status;
911
912     pollfd.fd = fd;
913     pollfd.events = POLLIN | POLLPRI;
914     pollfd.revents = 0;
915
916     status = poll (&pollfd, 1, /* timeout = */ 500);
917     if (status == 0) /* timeout */
918       continue;
919     else if (status < 0) /* error */
920     {
921       status = errno;
922       if (status == EINTR)
923         continue;
924       RRDD_LOG (LOG_ERR, "connection_thread_main: poll(2) failed.");
925       continue;
926     }
927
928     if ((pollfd.revents & POLLHUP) != 0) /* normal shutdown */
929     {
930       close (fd);
931       break;
932     }
933     else if ((pollfd.revents & (POLLIN | POLLPRI)) == 0)
934     {
935       RRDD_LOG (LOG_WARNING, "connection_thread_main: "
936           "poll(2) returned something unexpected: %#04hx",
937           pollfd.revents);
938       close (fd);
939       break;
940     }
941
942     status = handle_request (fd);
943     if (status != 0)
944     {
945       close (fd);
946       break;
947     }
948   }
949
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)
956       break;
957   assert (i < connetion_threads_num);
958
959   /* Move the trailing threads forward. */
960   if (i < (connetion_threads_num - 1))
961   {
962     memmove (connetion_threads + i,
963         connetion_threads + i + 1,
964         sizeof (pthread_t) * (connetion_threads_num - i - 1));
965   }
966
967   connetion_threads_num--;
968   pthread_mutex_unlock (&connetion_threads_lock);
969
970   free (args);
971   return (NULL);
972 } /* }}} void *connection_thread_main */
973
974 static int open_listen_socket_unix (const char *path) /* {{{ */
975 {
976   int fd;
977   struct sockaddr_un sa;
978   listen_socket_t *temp;
979   int status;
980
981   temp = (listen_socket_t *) realloc (listen_fds,
982       sizeof (listen_fds[0]) * (listen_fds_num + 1));
983   if (temp == NULL)
984   {
985     RRDD_LOG (LOG_ERR, "open_listen_socket_unix: realloc failed.");
986     return (-1);
987   }
988   listen_fds = temp;
989   memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
990
991   fd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
992   if (fd < 0)
993   {
994     RRDD_LOG (LOG_ERR, "open_listen_socket_unix: socket(2) failed.");
995     return (-1);
996   }
997
998   memset (&sa, 0, sizeof (sa));
999   sa.sun_family = AF_UNIX;
1000   strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
1001
1002   status = bind (fd, (struct sockaddr *) &sa, sizeof (sa));
1003   if (status != 0)
1004   {
1005     RRDD_LOG (LOG_ERR, "open_listen_socket_unix: bind(2) failed.");
1006     close (fd);
1007     unlink (path);
1008     return (-1);
1009   }
1010
1011   status = listen (fd, /* backlog = */ 10);
1012   if (status != 0)
1013   {
1014     RRDD_LOG (LOG_ERR, "open_listen_socket_unix: listen(2) failed.");
1015     close (fd);
1016     unlink (path);
1017     return (-1);
1018   }
1019   
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,
1023       "unix:%s", path);
1024   listen_fds_num++;
1025
1026   return (0);
1027 } /* }}} int open_listen_socket_unix */
1028
1029 static int open_listen_socket (const char *addr) /* {{{ */
1030 {
1031   struct addrinfo ai_hints;
1032   struct addrinfo *ai_res;
1033   struct addrinfo *ai_ptr;
1034   int status;
1035
1036   assert (addr != NULL);
1037
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));
1042
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;
1047 #endif
1048   ai_hints.ai_family = AF_UNSPEC;
1049   ai_hints.ai_socktype = SOCK_STREAM;
1050
1051   ai_res = NULL;
1052   status = getaddrinfo (addr, RRDCACHED_DEFAULT_PORT, &ai_hints, &ai_res);
1053   if (status != 0)
1054   {
1055     RRDD_LOG (LOG_ERR, "open_listen_socket: getaddrinfo(%s) failed: "
1056         "%s", addr, gai_strerror (status));
1057     return (-1);
1058   }
1059
1060   for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1061   {
1062     int fd;
1063     listen_socket_t *temp;
1064
1065     temp = (listen_socket_t *) realloc (listen_fds,
1066         sizeof (listen_fds[0]) * (listen_fds_num + 1));
1067     if (temp == NULL)
1068     {
1069       RRDD_LOG (LOG_ERR, "open_listen_socket: realloc failed.");
1070       continue;
1071     }
1072     listen_fds = temp;
1073     memset (listen_fds + listen_fds_num, 0, sizeof (listen_fds[0]));
1074
1075     fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1076     if (fd < 0)
1077     {
1078       RRDD_LOG (LOG_ERR, "open_listen_socket: socket(2) failed.");
1079       continue;
1080     }
1081
1082     status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1083     if (status != 0)
1084     {
1085       RRDD_LOG (LOG_ERR, "open_listen_socket: bind(2) failed.");
1086       close (fd);
1087       continue;
1088     }
1089
1090     status = listen (fd, /* backlog = */ 10);
1091     if (status != 0)
1092     {
1093       RRDD_LOG (LOG_ERR, "open_listen_socket: listen(2) failed.");
1094       close (fd);
1095       return (-1);
1096     }
1097
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);
1101     listen_fds_num++;
1102   } /* for (ai_ptr) */
1103
1104   return (0);
1105 } /* }}} int open_listen_socket */
1106
1107 static int close_listen_sockets (void) /* {{{ */
1108 {
1109   size_t i;
1110
1111   for (i = 0; i < listen_fds_num; i++)
1112   {
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:"));
1116   }
1117
1118   free (listen_fds);
1119   listen_fds = NULL;
1120   listen_fds_num = 0;
1121
1122   return (0);
1123 } /* }}} int close_listen_sockets */
1124
1125 static void *listen_thread_main (void *args __attribute__((unused))) /* {{{ */
1126 {
1127   struct pollfd *pollfds;
1128   int pollfds_num;
1129   int status;
1130   int i;
1131
1132   for (i = 0; i < config_listen_address_list_len; i++)
1133   {
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]);
1137   }
1138
1139   if (config_listen_address_list_len < 1)
1140     open_listen_socket (RRDCACHED_DEFAULT_ADDRESS);
1141
1142   if (listen_fds_num < 1)
1143   {
1144     RRDD_LOG (LOG_ERR, "listen_thread_main: No listen sockets "
1145         "could be opened. Sorry.");
1146     return (NULL);
1147   }
1148
1149   pollfds_num = listen_fds_num;
1150   pollfds = (struct pollfd *) malloc (sizeof (*pollfds) * pollfds_num);
1151   if (pollfds == NULL)
1152   {
1153     RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1154     return (NULL);
1155   }
1156   memset (pollfds, 0, sizeof (*pollfds) * pollfds_num);
1157
1158   while (do_shutdown == 0)
1159   {
1160     assert (pollfds_num == ((int) listen_fds_num));
1161     for (i = 0; i < pollfds_num; i++)
1162     {
1163       pollfds[i].fd = listen_fds[i].fd;
1164       pollfds[i].events = POLLIN | POLLPRI;
1165       pollfds[i].revents = 0;
1166     }
1167
1168     status = poll (pollfds, pollfds_num, /* timeout = */ -1);
1169     if (status < 1)
1170     {
1171       status = errno;
1172       if (status != EINTR)
1173       {
1174         RRDD_LOG (LOG_ERR, "listen_thread_main: poll(2) failed.");
1175       }
1176       continue;
1177     }
1178
1179     for (i = 0; i < pollfds_num; i++)
1180     {
1181       int *client_sd;
1182       struct sockaddr_storage client_sa;
1183       socklen_t client_sa_size;
1184       pthread_t tid;
1185
1186       if (pollfds[i].revents == 0)
1187         continue;
1188
1189       if ((pollfds[i].revents & (POLLIN | POLLPRI)) == 0)
1190       {
1191         RRDD_LOG (LOG_ERR, "listen_thread_main: "
1192             "poll(2) returned something unexpected for listen FD #%i.",
1193             pollfds[i].fd);
1194         continue;
1195       }
1196
1197       client_sd = (int *) malloc (sizeof (int));
1198       if (client_sd == NULL)
1199       {
1200         RRDD_LOG (LOG_ERR, "listen_thread_main: malloc failed.");
1201         continue;
1202       }
1203
1204       client_sa_size = sizeof (client_sa);
1205       *client_sd = accept (pollfds[i].fd,
1206           (struct sockaddr *) &client_sa, &client_sa_size);
1207       if (*client_sd < 0)
1208       {
1209         RRDD_LOG (LOG_ERR, "listen_thread_main: accept(2) failed.");
1210         continue;
1211       }
1212
1213       status = pthread_create (&tid, /* attr = */ NULL, connection_thread_main,
1214           /* args = */ (void *) client_sd);
1215       if (status != 0)
1216       {
1217         RRDD_LOG (LOG_ERR, "listen_thread_main: pthread_create failed.");
1218         close (*client_sd);
1219         free (client_sd);
1220         continue;
1221       }
1222     } /* for (pollfds_num) */
1223   } /* while (do_shutdown == 0) */
1224
1225   close_listen_sockets ();
1226
1227   pthread_mutex_lock (&connetion_threads_lock);
1228   while (connetion_threads_num > 0)
1229   {
1230     pthread_t wait_for;
1231
1232     wait_for = connetion_threads[0];
1233
1234     pthread_mutex_unlock (&connetion_threads_lock);
1235     pthread_join (wait_for, /* retval = */ NULL);
1236     pthread_mutex_lock (&connetion_threads_lock);
1237   }
1238   pthread_mutex_unlock (&connetion_threads_lock);
1239
1240   RRDD_LOG (LOG_DEBUG, "listen_thread_main: Exiting.");
1241
1242   return (NULL);
1243 } /* }}} void *listen_thread_main */
1244
1245 static int daemonize (void) /* {{{ */
1246 {
1247   pid_t child;
1248   int status;
1249   char *base_dir;
1250
1251   /* These structures are static, because `sigaction' behaves weird if the are
1252    * overwritten.. */
1253   static struct sigaction sa_int;
1254   static struct sigaction sa_term;
1255   static struct sigaction sa_pipe;
1256
1257   child = fork ();
1258   if (child < 0)
1259   {
1260     fprintf (stderr, "daemonize: fork(2) failed.\n");
1261     return (-1);
1262   }
1263   else if (child > 0)
1264   {
1265     return (1);
1266   }
1267
1268   /* Change into the /tmp directory. */
1269   base_dir = (config_base_dir != NULL)
1270     ? config_base_dir
1271     : "/tmp";
1272   status = chdir (base_dir);
1273   if (status != 0)
1274   {
1275     fprintf (stderr, "daemonize: chdir (%s) failed.\n", base_dir);
1276     return (-1);
1277   }
1278
1279   /* Become session leader */
1280   setsid ();
1281
1282   /* Open the first three file descriptors to /dev/null */
1283   close (2);
1284   close (1);
1285   close (0);
1286
1287   open ("/dev/null", O_RDWR);
1288   dup (0);
1289   dup (0);
1290
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);
1295
1296   memset (&sa_term, 0, sizeof (sa_term));
1297   sa_term.sa_handler = sig_term_handler;
1298   sigaction (SIGINT, &sa_term, NULL);
1299
1300   memset (&sa_pipe, 0, sizeof (sa_pipe));
1301   sa_pipe.sa_handler = SIG_IGN;
1302   sigaction (SIGPIPE, &sa_pipe, NULL);
1303
1304   openlog ("rrdcached", LOG_PID, LOG_DAEMON);
1305
1306   cache_tree = g_tree_new ((GCompareFunc) strcmp);
1307   if (cache_tree == NULL)
1308   {
1309     RRDD_LOG (LOG_ERR, "daemonize: g_tree_new failed.");
1310     return (-1);
1311   }
1312
1313   memset (&queue_thread, 0, sizeof (queue_thread));
1314   status = pthread_create (&queue_thread, /* attr = */ NULL,
1315       queue_thread_main, /* args = */ NULL);
1316   if (status != 0)
1317   {
1318     RRDD_LOG (LOG_ERR, "daemonize: pthread_create failed.");
1319     return (-1);
1320   }
1321
1322   write_pidfile ();
1323
1324   return (0);
1325 } /* }}} int daemonize */
1326
1327 static int cleanup (void) /* {{{ */
1328 {
1329   RRDD_LOG (LOG_DEBUG, "cleanup ()");
1330
1331   do_shutdown++;
1332
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");
1337
1338   remove_pidfile ();
1339
1340   closelog ();
1341
1342   return (0);
1343 } /* }}} int cleanup */
1344
1345 static int read_options (int argc, char **argv) /* {{{ */
1346 {
1347   int option;
1348   int status = 0;
1349
1350   while ((option = getopt(argc, argv, "l:f:w:b:p:h?")) != -1)
1351   {
1352     switch (option)
1353     {
1354       case 'l':
1355       {
1356         char **temp;
1357
1358         temp = (char **) realloc (config_listen_address_list,
1359             sizeof (char *) * (config_listen_address_list_len + 1));
1360         if (temp == NULL)
1361         {
1362           fprintf (stderr, "read_options: realloc failed.\n");
1363           return (2);
1364         }
1365         config_listen_address_list = temp;
1366
1367         temp[config_listen_address_list_len] = strdup (optarg);
1368         if (temp[config_listen_address_list_len] == NULL)
1369         {
1370           fprintf (stderr, "read_options: strdup failed.\n");
1371           return (2);
1372         }
1373         config_listen_address_list_len++;
1374       }
1375       break;
1376
1377       case 'f':
1378       {
1379         int temp;
1380
1381         temp = atoi (optarg);
1382         if (temp > 0)
1383           config_flush_interval = temp;
1384         else
1385         {
1386           fprintf (stderr, "Invalid flush interval: %s\n", optarg);
1387           status = 3;
1388         }
1389       }
1390       break;
1391
1392       case 'w':
1393       {
1394         int temp;
1395
1396         temp = atoi (optarg);
1397         if (temp > 0)
1398           config_write_interval = temp;
1399         else
1400         {
1401           fprintf (stderr, "Invalid write interval: %s\n", optarg);
1402           status = 2;
1403         }
1404       }
1405       break;
1406
1407       case 'b':
1408       {
1409         size_t len;
1410
1411         if (config_base_dir != NULL)
1412           free (config_base_dir);
1413         config_base_dir = strdup (optarg);
1414         if (config_base_dir == NULL)
1415         {
1416           fprintf (stderr, "read_options: strdup failed.\n");
1417           return (3);
1418         }
1419
1420         len = strlen (config_base_dir);
1421         while ((len > 0) && (config_base_dir[len - 1] == '/'))
1422         {
1423           config_base_dir[len - 1] = 0;
1424           len--;
1425         }
1426
1427         if (len < 1)
1428         {
1429           fprintf (stderr, "Invalid base directory: %s\n", optarg);
1430           return (4);
1431         }
1432       }
1433       break;
1434
1435       case 'p':
1436       {
1437         if (config_pid_file != NULL)
1438           free (config_pid_file);
1439         config_pid_file = strdup (optarg);
1440         if (config_pid_file == NULL)
1441         {
1442           fprintf (stderr, "read_options: strdup failed.\n");
1443           return (3);
1444         }
1445       }
1446       break;
1447
1448       case 'h':
1449       case '?':
1450         printf ("RRDd %s  Copyright (C) 2008 Florian octo Forster\n"
1451             "\n"
1452             "Usage: rrdcached [options]\n"
1453             "\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"
1460             "\n"
1461             "For more information and a detailed description of all options "
1462             "please refer\n"
1463             "to the rrdcached(1) manual page.\n",
1464             VERSION);
1465         status = -1;
1466         break;
1467     } /* switch (option) */
1468   } /* while (getopt) */
1469
1470   return (status);
1471 } /* }}} int read_options */
1472
1473 int main (int argc, char **argv)
1474 {
1475   int status;
1476
1477   status = read_options (argc, argv);
1478   if (status != 0)
1479   {
1480     if (status < 0)
1481       status = 0;
1482     return (status);
1483   }
1484
1485   status = daemonize ();
1486   if (status == 1)
1487   {
1488     struct sigaction sigchld;
1489
1490     memset (&sigchld, 0, sizeof (sigchld));
1491     sigchld.sa_handler = SIG_IGN;
1492     sigaction (SIGCHLD, &sigchld, NULL);
1493
1494     return (0);
1495   }
1496   else if (status != 0)
1497   {
1498     fprintf (stderr, "daemonize failed, exiting.\n");
1499     return (1);
1500   }
1501
1502   listen_thread_main (NULL);
1503
1504   cleanup ();
1505
1506   return (0);
1507 } /* int main */
1508
1509 /*
1510  * vim: set sw=2 sts=2 ts=8 et fdm=marker :
1511  */