1 /**
2 * collectd - src/rrdtool.c
3 * Copyright (C) 2006-2013 Florian octo Forster
4 * Copyright (C) 2008-2008 Sebastian Harl
5 * Copyright (C) 2009 Mariusz Gronczewski
6 *
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; only version 2 of the License is applicable.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 *
20 * Authors:
21 * Florian octo Forster <octo at collectd.org>
22 * Sebastian Harl <sh at tokkee.org>
23 * Mariusz Gronczewski <xani666 at gmail.com>
24 **/
26 #include "collectd.h"
27 #include "plugin.h"
28 #include "common.h"
29 #include "utils_avltree.h"
30 #include "utils_random.h"
31 #include "utils_rrdcreate.h"
33 #include <rrd.h>
35 #if HAVE_PTHREAD_H
36 # include <pthread.h>
37 #endif
39 /*
40 * Private types
41 */
42 struct rrd_cache_s
43 {
44 int values_num;
45 char **values;
46 cdtime_t first_value;
47 cdtime_t last_value;
48 int64_t random_variation;
49 enum
50 {
51 FLAG_NONE = 0x00,
52 FLAG_QUEUED = 0x01,
53 FLAG_FLUSHQ = 0x02
54 } flags;
55 };
56 typedef struct rrd_cache_s rrd_cache_t;
58 enum rrd_queue_dir_e
59 {
60 QUEUE_INSERT_FRONT,
61 QUEUE_INSERT_BACK
62 };
63 typedef enum rrd_queue_dir_e rrd_queue_dir_t;
65 struct rrd_queue_s
66 {
67 char *filename;
68 struct rrd_queue_s *next;
69 };
70 typedef struct rrd_queue_s rrd_queue_t;
72 /*
73 * Private variables
74 */
75 static const char *config_keys[] =
76 {
77 "CacheTimeout",
78 "CacheFlush",
79 "CreateFilesAsync",
80 "DataDir",
81 "StepSize",
82 "HeartBeat",
83 "RRARows",
84 "RRATimespan",
85 "XFF",
86 "WritesPerSecond",
87 "RandomTimeout"
88 };
89 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
91 /* If datadir is zero, the daemon's basedir is used. If stepsize or heartbeat
92 * is zero a default, depending on the `interval' member of the value list is
93 * being used. */
94 static char *datadir = NULL;
95 static double write_rate = 0.0;
96 static rrdcreate_config_t rrdcreate_config =
97 {
98 /* stepsize = */ 0,
99 /* heartbeat = */ 0,
100 /* rrarows = */ 1200,
101 /* xff = */ 0.1,
103 /* timespans = */ NULL,
104 /* timespans_num = */ 0,
106 /* consolidation_functions = */ NULL,
107 /* consolidation_functions_num = */ 0,
109 /* async = */ 0
110 };
112 /* XXX: If you need to lock both, cache_lock and queue_lock, at the same time,
113 * ALWAYS lock `cache_lock' first! */
114 static cdtime_t cache_timeout = 0;
115 static cdtime_t cache_flush_timeout = 0;
116 static cdtime_t random_timeout = TIME_T_TO_CDTIME_T (1);
117 static cdtime_t cache_flush_last;
118 static c_avl_tree_t *cache = NULL;
119 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
121 static rrd_queue_t *queue_head = NULL;
122 static rrd_queue_t *queue_tail = NULL;
123 static rrd_queue_t *flushq_head = NULL;
124 static rrd_queue_t *flushq_tail = NULL;
125 static pthread_t queue_thread;
126 static int queue_thread_running = 1;
127 static pthread_mutex_t queue_lock = PTHREAD_MUTEX_INITIALIZER;
128 static pthread_cond_t queue_cond = PTHREAD_COND_INITIALIZER;
130 #if !HAVE_THREADSAFE_LIBRRD
131 static pthread_mutex_t librrd_lock = PTHREAD_MUTEX_INITIALIZER;
132 #endif
134 static int do_shutdown = 0;
136 #if HAVE_THREADSAFE_LIBRRD
137 static int srrd_update (char *filename, char *template,
138 int argc, const char **argv)
139 {
140 int status;
142 optind = 0; /* bug in librrd? */
143 rrd_clear_error ();
145 status = rrd_update_r (filename, template, argc, (void *) argv);
147 if (status != 0)
148 {
149 WARNING ("rrdtool plugin: rrd_update_r (%s) failed: %s",
150 filename, rrd_get_error ());
151 }
153 return (status);
154 } /* int srrd_update */
155 /* #endif HAVE_THREADSAFE_LIBRRD */
157 #else /* !HAVE_THREADSAFE_LIBRRD */
158 static int srrd_update (char *filename, char *template,
159 int argc, const char **argv)
160 {
161 int status;
163 int new_argc;
164 char **new_argv;
166 assert (template == NULL);
168 new_argc = 2 + argc;
169 new_argv = (char **) malloc ((new_argc + 1) * sizeof (char *));
170 if (new_argv == NULL)
171 {
172 ERROR ("rrdtool plugin: malloc failed.");
173 return (-1);
174 }
176 new_argv[0] = "update";
177 new_argv[1] = filename;
179 memcpy (new_argv + 2, argv, argc * sizeof (char *));
180 new_argv[new_argc] = NULL;
182 pthread_mutex_lock (&librrd_lock);
183 optind = 0; /* bug in librrd? */
184 rrd_clear_error ();
186 status = rrd_update (new_argc, new_argv);
187 pthread_mutex_unlock (&librrd_lock);
189 if (status != 0)
190 {
191 WARNING ("rrdtool plugin: rrd_update_r failed: %s: %s",
192 filename, rrd_get_error ());
193 }
195 sfree (new_argv);
197 return (status);
198 } /* int srrd_update */
199 #endif /* !HAVE_THREADSAFE_LIBRRD */
201 static int value_list_to_string_multiple (char *buffer, int buffer_len,
202 const data_set_t *ds, const value_list_t *vl)
203 {
204 int offset;
205 int status;
206 time_t tt;
207 int i;
209 memset (buffer, '\0', buffer_len);
211 tt = CDTIME_T_TO_TIME_T (vl->time);
212 status = ssnprintf (buffer, buffer_len, "%u", (unsigned int) tt);
213 if ((status < 1) || (status >= buffer_len))
214 return (-1);
215 offset = status;
217 for (i = 0; i < ds->ds_num; i++)
218 {
219 if ((ds->ds[i].type != DS_TYPE_COUNTER)
220 && (ds->ds[i].type != DS_TYPE_GAUGE)
221 && (ds->ds[i].type != DS_TYPE_DERIVE)
222 && (ds->ds[i].type != DS_TYPE_ABSOLUTE))
223 return (-1);
225 if (ds->ds[i].type == DS_TYPE_COUNTER)
226 status = ssnprintf (buffer + offset, buffer_len - offset,
227 ":%llu", vl->values[i].counter);
228 else if (ds->ds[i].type == DS_TYPE_GAUGE)
229 status = ssnprintf (buffer + offset, buffer_len - offset,
230 ":"GAUGE_FORMAT, vl->values[i].gauge);
231 else if (ds->ds[i].type == DS_TYPE_DERIVE)
232 status = ssnprintf (buffer + offset, buffer_len - offset,
233 ":%"PRIi64, vl->values[i].derive);
234 else /*if (ds->ds[i].type == DS_TYPE_ABSOLUTE) */
235 status = ssnprintf (buffer + offset, buffer_len - offset,
236 ":%"PRIu64, vl->values[i].absolute);
238 if ((status < 1) || (status >= (buffer_len - offset)))
239 return (-1);
241 offset += status;
242 } /* for ds->ds_num */
244 return (0);
245 } /* int value_list_to_string_multiple */
247 static int value_list_to_string (char *buffer, int buffer_len,
248 const data_set_t *ds, const value_list_t *vl)
249 {
250 int status;
251 time_t tt;
253 if (ds->ds_num != 1)
254 return (value_list_to_string_multiple (buffer, buffer_len,
255 ds, vl));
257 tt = CDTIME_T_TO_TIME_T (vl->time);
258 switch (ds->ds[0].type)
259 {
260 case DS_TYPE_DERIVE:
261 status = ssnprintf (buffer, buffer_len, "%u:%"PRIi64,
262 (unsigned) tt, vl->values[0].derive);
263 break;
264 case DS_TYPE_GAUGE:
265 status = ssnprintf (buffer, buffer_len, "%u:"GAUGE_FORMAT,
266 (unsigned) tt, vl->values[0].gauge);
267 break;
268 case DS_TYPE_COUNTER:
269 status = ssnprintf (buffer, buffer_len, "%u:%llu",
270 (unsigned) tt, vl->values[0].counter);
271 break;
272 case DS_TYPE_ABSOLUTE:
273 status = ssnprintf (buffer, buffer_len, "%u:%"PRIu64,
274 (unsigned) tt, vl->values[0].absolute);
275 break;
276 default:
277 return (EINVAL);
278 }
280 if ((status < 1) || (status >= buffer_len))
281 return (ENOMEM);
283 return (0);
284 } /* int value_list_to_string */
286 static int value_list_to_filename (char *buffer, size_t buffer_size,
287 value_list_t const *vl)
288 {
289 char const suffix[] = ".rrd";
290 int status;
291 size_t len;
293 if (datadir != NULL)
294 {
295 size_t datadir_len = strlen (datadir) + 1;
297 if (datadir_len >= buffer_size)
298 return (ENOMEM);
300 sstrncpy (buffer, datadir, buffer_size);
301 buffer[datadir_len - 1] = '/';
302 buffer[datadir_len] = 0;
304 buffer += datadir_len;
305 buffer_size -= datadir_len;
306 }
308 status = FORMAT_VL (buffer, buffer_size, vl);
309 if (status != 0)
310 return (status);
312 len = strlen (buffer);
313 assert (len < buffer_size);
314 buffer += len;
315 buffer_size -= len;
317 if (buffer_size <= sizeof (suffix))
318 return (ENOMEM);
320 memcpy (buffer, suffix, sizeof (suffix));
321 return (0);
322 } /* int value_list_to_filename */
324 static void *rrd_queue_thread (void __attribute__((unused)) *data)
325 {
326 struct timeval tv_next_update;
327 struct timeval tv_now;
329 gettimeofday (&tv_next_update, /* timezone = */ NULL);
331 while (42)
332 {
333 rrd_queue_t *queue_entry;
334 rrd_cache_t *cache_entry;
335 char **values;
336 int values_num;
337 int status;
338 int i;
340 values = NULL;
341 values_num = 0;
343 pthread_mutex_lock (&queue_lock);
344 /* Wait for values to arrive */
345 while (42)
346 {
347 struct timespec ts_wait;
349 while ((flushq_head == NULL) && (queue_head == NULL)
350 && (do_shutdown == 0))
351 pthread_cond_wait (&queue_cond, &queue_lock);
353 if ((flushq_head == NULL) && (queue_head == NULL))
354 break;
356 /* Don't delay if there's something to flush */
357 if (flushq_head != NULL)
358 break;
360 /* Don't delay if we're shutting down */
361 if (do_shutdown != 0)
362 break;
364 /* Don't delay if no delay was configured. */
365 if (write_rate <= 0.0)
366 break;
368 gettimeofday (&tv_now, /* timezone = */ NULL);
369 status = timeval_cmp (tv_next_update, tv_now, NULL);
370 /* We're good to go */
371 if (status <= 0)
372 break;
374 /* We're supposed to wait a bit with this update, so we'll
375 * wait for the next addition to the queue or to the end of
376 * the wait period - whichever comes first. */
377 ts_wait.tv_sec = tv_next_update.tv_sec;
378 ts_wait.tv_nsec = 1000 * tv_next_update.tv_usec;
380 status = pthread_cond_timedwait (&queue_cond, &queue_lock,
381 &ts_wait);
382 if (status == ETIMEDOUT)
383 break;
384 } /* while (42) */
386 /* XXX: If you need to lock both, cache_lock and queue_lock, at
387 * the same time, ALWAYS lock `cache_lock' first! */
389 /* We're in the shutdown phase */
390 if ((flushq_head == NULL) && (queue_head == NULL))
391 {
392 pthread_mutex_unlock (&queue_lock);
393 break;
394 }
396 if (flushq_head != NULL)
397 {
398 /* Dequeue the first flush entry */
399 queue_entry = flushq_head;
400 if (flushq_head == flushq_tail)
401 flushq_head = flushq_tail = NULL;
402 else
403 flushq_head = flushq_head->next;
404 }
405 else /* if (queue_head != NULL) */
406 {
407 /* Dequeue the first regular entry */
408 queue_entry = queue_head;
409 if (queue_head == queue_tail)
410 queue_head = queue_tail = NULL;
411 else
412 queue_head = queue_head->next;
413 }
415 /* Unlock the queue again */
416 pthread_mutex_unlock (&queue_lock);
418 /* We now need the cache lock so the entry isn't updated while
419 * we make a copy of it's values */
420 pthread_mutex_lock (&cache_lock);
422 status = c_avl_get (cache, queue_entry->filename,
423 (void *) &cache_entry);
425 if (status == 0)
426 {
427 values = cache_entry->values;
428 values_num = cache_entry->values_num;
430 cache_entry->values = NULL;
431 cache_entry->values_num = 0;
432 cache_entry->flags = FLAG_NONE;
433 }
435 pthread_mutex_unlock (&cache_lock);
437 if (status != 0)
438 {
439 sfree (queue_entry->filename);
440 sfree (queue_entry);
441 continue;
442 }
444 /* Update `tv_next_update' */
445 if (write_rate > 0.0)
446 {
447 gettimeofday (&tv_now, /* timezone = */ NULL);
448 tv_next_update.tv_sec = tv_now.tv_sec;
449 tv_next_update.tv_usec = tv_now.tv_usec
450 + ((suseconds_t) (1000000 * write_rate));
451 while (tv_next_update.tv_usec > 1000000)
452 {
453 tv_next_update.tv_sec++;
454 tv_next_update.tv_usec -= 1000000;
455 }
456 }
458 /* Write the values to the RRD-file */
459 srrd_update (queue_entry->filename, NULL,
460 values_num, (const char **)values);
461 DEBUG ("rrdtool plugin: queue thread: Wrote %i value%s to %s",
462 values_num, (values_num == 1) ? "" : "s",
463 queue_entry->filename);
465 for (i = 0; i < values_num; i++)
466 {
467 sfree (values[i]);
468 }
469 sfree (values);
470 sfree (queue_entry->filename);
471 sfree (queue_entry);
472 } /* while (42) */
474 pthread_exit ((void *) 0);
475 return ((void *) 0);
476 } /* void *rrd_queue_thread */
478 static int rrd_queue_enqueue (const char *filename,
479 rrd_queue_t **head, rrd_queue_t **tail)
480 {
481 rrd_queue_t *queue_entry;
483 queue_entry = (rrd_queue_t *) malloc (sizeof (rrd_queue_t));
484 if (queue_entry == NULL)
485 return (-1);
487 queue_entry->filename = strdup (filename);
488 if (queue_entry->filename == NULL)
489 {
490 free (queue_entry);
491 return (-1);
492 }
494 queue_entry->next = NULL;
496 pthread_mutex_lock (&queue_lock);
498 if (*tail == NULL)
499 *head = queue_entry;
500 else
501 (*tail)->next = queue_entry;
502 *tail = queue_entry;
504 pthread_cond_signal (&queue_cond);
505 pthread_mutex_unlock (&queue_lock);
507 return (0);
508 } /* int rrd_queue_enqueue */
510 static int rrd_queue_dequeue (const char *filename,
511 rrd_queue_t **head, rrd_queue_t **tail)
512 {
513 rrd_queue_t *this;
514 rrd_queue_t *prev;
516 pthread_mutex_lock (&queue_lock);
518 prev = NULL;
519 this = *head;
521 while (this != NULL)
522 {
523 if (strcmp (this->filename, filename) == 0)
524 break;
526 prev = this;
527 this = this->next;
528 }
530 if (this == NULL)
531 {
532 pthread_mutex_unlock (&queue_lock);
533 return (-1);
534 }
536 if (prev == NULL)
537 *head = this->next;
538 else
539 prev->next = this->next;
541 if (this->next == NULL)
542 *tail = prev;
544 pthread_mutex_unlock (&queue_lock);
546 sfree (this->filename);
547 sfree (this);
549 return (0);
550 } /* int rrd_queue_dequeue */
552 /* XXX: You must hold "cache_lock" when calling this function! */
553 static void rrd_cache_flush (cdtime_t timeout)
554 {
555 rrd_cache_t *rc;
556 cdtime_t now;
558 char **keys = NULL;
559 int keys_num = 0;
561 char *key;
562 c_avl_iterator_t *iter;
563 int i;
565 DEBUG ("rrdtool plugin: Flushing cache, timeout = %.3f",
566 CDTIME_T_TO_DOUBLE (timeout));
568 now = cdtime ();
569 timeout = TIME_T_TO_CDTIME_T (timeout);
571 /* Build a list of entries to be flushed */
572 iter = c_avl_get_iterator (cache);
573 while (c_avl_iterator_next (iter, (void *) &key, (void *) &rc) == 0)
574 {
575 if (rc->flags != FLAG_NONE)
576 continue;
577 /* timeout == 0 => flush everything */
578 else if ((timeout != 0)
579 && ((now - rc->first_value) < timeout))
580 continue;
581 else if (rc->values_num > 0)
582 {
583 int status;
585 status = rrd_queue_enqueue (key, &queue_head, &queue_tail);
586 if (status == 0)
587 rc->flags = FLAG_QUEUED;
588 }
589 else /* ancient and no values -> waste of memory */
590 {
591 char **tmp = (char **) realloc ((void *) keys,
592 (keys_num + 1) * sizeof (char *));
593 if (tmp == NULL)
594 {
595 char errbuf[1024];
596 ERROR ("rrdtool plugin: "
597 "realloc failed: %s",
598 sstrerror (errno, errbuf,
599 sizeof (errbuf)));
600 c_avl_iterator_destroy (iter);
601 sfree (keys);
602 return;
603 }
604 keys = tmp;
605 keys[keys_num] = key;
606 keys_num++;
607 }
608 } /* while (c_avl_iterator_next) */
609 c_avl_iterator_destroy (iter);
611 for (i = 0; i < keys_num; i++)
612 {
613 if (c_avl_remove (cache, keys[i], (void *) &key, (void *) &rc) != 0)
614 {
615 DEBUG ("rrdtool plugin: c_avl_remove (%s) failed.", keys[i]);
616 continue;
617 }
619 assert (rc->values == NULL);
620 assert (rc->values_num == 0);
622 sfree (rc);
623 sfree (key);
624 keys[i] = NULL;
625 } /* for (i = 0..keys_num) */
627 sfree (keys);
629 cache_flush_last = now;
630 } /* void rrd_cache_flush */
632 static int rrd_cache_flush_identifier (cdtime_t timeout,
633 const char *identifier)
634 {
635 rrd_cache_t *rc;
636 cdtime_t now;
637 int status;
638 char key[2048];
640 if (identifier == NULL)
641 {
642 rrd_cache_flush (timeout);
643 return (0);
644 }
646 now = cdtime ();
648 if (datadir == NULL)
649 snprintf (key, sizeof (key), "%s.rrd",
650 identifier);
651 else
652 snprintf (key, sizeof (key), "%s/%s.rrd",
653 datadir, identifier);
654 key[sizeof (key) - 1] = 0;
656 status = c_avl_get (cache, key, (void *) &rc);
657 if (status != 0)
658 {
659 INFO ("rrdtool plugin: rrd_cache_flush_identifier: "
660 "c_avl_get (%s) failed. Does that file really exist?",
661 key);
662 return (status);
663 }
665 if (rc->flags == FLAG_FLUSHQ)
666 {
667 status = 0;
668 }
669 else if (rc->flags == FLAG_QUEUED)
670 {
671 rrd_queue_dequeue (key, &queue_head, &queue_tail);
672 status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
673 if (status == 0)
674 rc->flags = FLAG_FLUSHQ;
675 }
676 else if ((now - rc->first_value) < timeout)
677 {
678 status = 0;
679 }
680 else if (rc->values_num > 0)
681 {
682 status = rrd_queue_enqueue (key, &flushq_head, &flushq_tail);
683 if (status == 0)
684 rc->flags = FLAG_FLUSHQ;
685 }
687 return (status);
688 } /* int rrd_cache_flush_identifier */
690 static int64_t rrd_get_random_variation (void)
691 {
692 long min;
693 long max;
695 if (random_timeout <= 0)
696 return (0);
698 /* Assure that "cache_timeout + random_variation" is never negative. */
699 if (random_timeout > cache_timeout)
700 {
701 INFO ("rrdtool plugin: Adjusting \"RandomTimeout\" to %.3f seconds.",
702 CDTIME_T_TO_DOUBLE (cache_timeout));
703 random_timeout = cache_timeout;
704 }
706 max = (long) (random_timeout / 2);
707 min = max - ((long) random_timeout);
709 return ((int64_t) cdrand_range (min, max));
710 } /* int64_t rrd_get_random_variation */
712 static int rrd_cache_insert (const char *filename,
713 const char *value, cdtime_t value_time)
714 {
715 rrd_cache_t *rc = NULL;
716 int new_rc = 0;
717 char **values_new;
719 pthread_mutex_lock (&cache_lock);
721 /* This shouldn't happen, but it did happen at least once, so we'll be
722 * careful. */
723 if (cache == NULL)
724 {
725 pthread_mutex_unlock (&cache_lock);
726 WARNING ("rrdtool plugin: cache == NULL.");
727 return (-1);
728 }
730 c_avl_get (cache, filename, (void *) &rc);
732 if (rc == NULL)
733 {
734 rc = malloc (sizeof (*rc));
735 if (rc == NULL)
736 {
737 pthread_mutex_unlock (&cache_lock);
738 return (-1);
739 }
740 rc->values_num = 0;
741 rc->values = NULL;
742 rc->first_value = 0;
743 rc->last_value = 0;
744 rc->random_variation = rrd_get_random_variation ();
745 rc->flags = FLAG_NONE;
746 new_rc = 1;
747 }
749 assert (value_time > 0); /* plugin_dispatch() ensures this. */
750 if (rc->last_value >= value_time)
751 {
752 pthread_mutex_unlock (&cache_lock);
753 DEBUG ("rrdtool plugin: (rc->last_value = %"PRIu64") "
754 ">= (value_time = %"PRIu64")",
755 rc->last_value, value_time);
756 return (-1);
757 }
759 values_new = (char **) realloc ((void *) rc->values,
760 (rc->values_num + 1) * sizeof (char *));
761 if (values_new == NULL)
762 {
763 char errbuf[1024];
764 void *cache_key = NULL;
766 sstrerror (errno, errbuf, sizeof (errbuf));
768 c_avl_remove (cache, filename, &cache_key, NULL);
769 pthread_mutex_unlock (&cache_lock);
771 ERROR ("rrdtool plugin: realloc failed: %s", errbuf);
773 sfree (cache_key);
774 sfree (rc->values);
775 sfree (rc);
776 return (-1);
777 }
778 rc->values = values_new;
780 rc->values[rc->values_num] = strdup (value);
781 if (rc->values[rc->values_num] != NULL)
782 rc->values_num++;
784 if (rc->values_num == 1)
785 rc->first_value = value_time;
786 rc->last_value = value_time;
788 /* Insert if this is the first value */
789 if (new_rc == 1)
790 {
791 void *cache_key = strdup (filename);
793 if (cache_key == NULL)
794 {
795 char errbuf[1024];
796 sstrerror (errno, errbuf, sizeof (errbuf));
798 pthread_mutex_unlock (&cache_lock);
800 ERROR ("rrdtool plugin: strdup failed: %s", errbuf);
802 sfree (rc->values[0]);
803 sfree (rc->values);
804 sfree (rc);
805 return (-1);
806 }
808 c_avl_insert (cache, cache_key, rc);
809 }
811 DEBUG ("rrdtool plugin: rrd_cache_insert: file = %s; "
812 "values_num = %i; age = %.3f;",
813 filename, rc->values_num,
814 CDTIME_T_TO_DOUBLE (rc->last_value - rc->first_value));
816 if ((rc->last_value - rc->first_value) >= (cache_timeout + rc->random_variation))
817 {
818 /* XXX: If you need to lock both, cache_lock and queue_lock, at
819 * the same time, ALWAYS lock `cache_lock' first! */
820 if (rc->flags == FLAG_NONE)
821 {
822 int status;
824 status = rrd_queue_enqueue (filename, &queue_head, &queue_tail);
825 if (status == 0)
826 rc->flags = FLAG_QUEUED;
828 rc->random_variation = rrd_get_random_variation ();
829 }
830 else
831 {
832 DEBUG ("rrdtool plugin: `%s' is already queued.", filename);
833 }
834 }
836 if ((cache_timeout > 0) &&
837 ((cdtime () - cache_flush_last) > cache_flush_timeout))
838 rrd_cache_flush (cache_flush_timeout);
840 pthread_mutex_unlock (&cache_lock);
842 return (0);
843 } /* int rrd_cache_insert */
845 static int rrd_cache_destroy (void) /* {{{ */
846 {
847 void *key = NULL;
848 void *value = NULL;
850 int non_empty = 0;
852 pthread_mutex_lock (&cache_lock);
854 if (cache == NULL)
855 {
856 pthread_mutex_unlock (&cache_lock);
857 return (0);
858 }
860 while (c_avl_pick (cache, &key, &value) == 0)
861 {
862 rrd_cache_t *rc;
863 int i;
865 sfree (key);
866 key = NULL;
868 rc = value;
869 value = NULL;
871 if (rc->values_num > 0)
872 non_empty++;
874 for (i = 0; i < rc->values_num; i++)
875 sfree (rc->values[i]);
876 sfree (rc->values);
877 sfree (rc);
878 }
880 c_avl_destroy (cache);
881 cache = NULL;
883 if (non_empty > 0)
884 {
885 INFO ("rrdtool plugin: %i cache %s had values when destroying the cache.",
886 non_empty, (non_empty == 1) ? "entry" : "entries");
887 }
888 else
889 {
890 DEBUG ("rrdtool plugin: No values have been lost "
891 "when destroying the cache.");
892 }
894 pthread_mutex_unlock (&cache_lock);
895 return (0);
896 } /* }}} int rrd_cache_destroy */
898 static int rrd_compare_numeric (const void *a_ptr, const void *b_ptr)
899 {
900 int a = *((int *) a_ptr);
901 int b = *((int *) b_ptr);
903 if (a < b)
904 return (-1);
905 else if (a > b)
906 return (1);
907 else
908 return (0);
909 } /* int rrd_compare_numeric */
911 static int rrd_write (const data_set_t *ds, const value_list_t *vl,
912 user_data_t __attribute__((unused)) *user_data)
913 {
914 struct stat statbuf;
915 char filename[512];
916 char values[512];
917 int status;
919 if (do_shutdown)
920 return (0);
922 if (0 != strcmp (ds->type, vl->type)) {
923 ERROR ("rrdtool plugin: DS type does not match value list type");
924 return -1;
925 }
927 if (value_list_to_filename (filename, sizeof (filename), vl) != 0)
928 return (-1);
930 if (value_list_to_string (values, sizeof (values), ds, vl) != 0)
931 return (-1);
933 if (stat (filename, &statbuf) == -1)
934 {
935 if (errno == ENOENT)
936 {
937 status = cu_rrd_create_file (filename,
938 ds, vl, &rrdcreate_config);
939 if (status != 0)
940 return (-1);
941 else if (rrdcreate_config.async)
942 return (0);
943 }
944 else
945 {
946 char errbuf[1024];
947 ERROR ("stat(%s) failed: %s", filename,
948 sstrerror (errno, errbuf,
949 sizeof (errbuf)));
950 return (-1);
951 }
952 }
953 else if (!S_ISREG (statbuf.st_mode))
954 {
955 ERROR ("stat(%s): Not a regular file!",
956 filename);
957 return (-1);
958 }
960 status = rrd_cache_insert (filename, values, vl->time);
962 return (status);
963 } /* int rrd_write */
965 static int rrd_flush (cdtime_t timeout, const char *identifier,
966 __attribute__((unused)) user_data_t *user_data)
967 {
968 pthread_mutex_lock (&cache_lock);
970 if (cache == NULL) {
971 pthread_mutex_unlock (&cache_lock);
972 return (0);
973 }
975 rrd_cache_flush_identifier (timeout, identifier);
977 pthread_mutex_unlock (&cache_lock);
978 return (0);
979 } /* int rrd_flush */
981 static int rrd_config (const char *key, const char *value)
982 {
983 if (strcasecmp ("CacheTimeout", key) == 0)
984 {
985 double tmp = atof (value);
986 if (tmp < 0)
987 {
988 fprintf (stderr, "rrdtool: `CacheTimeout' must "
989 "be greater than 0.\n");
990 ERROR ("rrdtool: `CacheTimeout' must "
991 "be greater than 0.\n");
992 return (1);
993 }
994 cache_timeout = DOUBLE_TO_CDTIME_T (tmp);
995 }
996 else if (strcasecmp ("CacheFlush", key) == 0)
997 {
998 int tmp = atoi (value);
999 if (tmp < 0)
1000 {
1001 fprintf (stderr, "rrdtool: `CacheFlush' must "
1002 "be greater than 0.\n");
1003 ERROR ("rrdtool: `CacheFlush' must "
1004 "be greater than 0.\n");
1005 return (1);
1006 }
1007 cache_flush_timeout = tmp;
1008 }
1009 else if (strcasecmp ("DataDir", key) == 0)
1010 {
1011 if (datadir != NULL)
1012 free (datadir);
1013 datadir = strdup (value);
1014 if (datadir != NULL)
1015 {
1016 int len = strlen (datadir);
1017 while ((len > 0) && (datadir[len - 1] == '/'))
1018 {
1019 len--;
1020 datadir[len] = '\0';
1021 }
1022 if (len <= 0)
1023 {
1024 free (datadir);
1025 datadir = NULL;
1026 }
1027 }
1028 }
1029 else if (strcasecmp ("StepSize", key) == 0)
1030 {
1031 unsigned long temp = strtoul (value, NULL, 0);
1032 if (temp > 0)
1033 rrdcreate_config.stepsize = temp;
1034 }
1035 else if (strcasecmp ("HeartBeat", key) == 0)
1036 {
1037 int temp = atoi (value);
1038 if (temp > 0)
1039 rrdcreate_config.heartbeat = temp;
1040 }
1041 else if (strcasecmp ("CreateFilesAsync", key) == 0)
1042 {
1043 if (IS_TRUE (value))
1044 rrdcreate_config.async = 1;
1045 else
1046 rrdcreate_config.async = 0;
1047 }
1048 else if (strcasecmp ("RRARows", key) == 0)
1049 {
1050 int tmp = atoi (value);
1051 if (tmp <= 0)
1052 {
1053 fprintf (stderr, "rrdtool: `RRARows' must "
1054 "be greater than 0.\n");
1055 ERROR ("rrdtool: `RRARows' must "
1056 "be greater than 0.\n");
1057 return (1);
1058 }
1059 rrdcreate_config.rrarows = tmp;
1060 }
1061 else if (strcasecmp ("RRATimespan", key) == 0)
1062 {
1063 char *saveptr = NULL;
1064 char *dummy;
1065 char *ptr;
1066 char *value_copy;
1067 int *tmp_alloc;
1069 value_copy = strdup (value);
1070 if (value_copy == NULL)
1071 return (1);
1073 dummy = value_copy;
1074 while ((ptr = strtok_r (dummy, ", \t", &saveptr)) != NULL)
1075 {
1076 dummy = NULL;
1078 tmp_alloc = realloc (rrdcreate_config.timespans,
1079 sizeof (int) * (rrdcreate_config.timespans_num + 1));
1080 if (tmp_alloc == NULL)
1081 {
1082 fprintf (stderr, "rrdtool: realloc failed.\n");
1083 ERROR ("rrdtool: realloc failed.\n");
1084 free (value_copy);
1085 return (1);
1086 }
1087 rrdcreate_config.timespans = tmp_alloc;
1088 rrdcreate_config.timespans[rrdcreate_config.timespans_num] = atoi (ptr);
1089 if (rrdcreate_config.timespans[rrdcreate_config.timespans_num] != 0)
1090 rrdcreate_config.timespans_num++;
1091 } /* while (strtok_r) */
1093 qsort (/* base = */ rrdcreate_config.timespans,
1094 /* nmemb = */ rrdcreate_config.timespans_num,
1095 /* size = */ sizeof (rrdcreate_config.timespans[0]),
1096 /* compar = */ rrd_compare_numeric);
1098 free (value_copy);
1099 }
1100 else if (strcasecmp ("XFF", key) == 0)
1101 {
1102 double tmp = atof (value);
1103 if ((tmp < 0.0) || (tmp >= 1.0))
1104 {
1105 fprintf (stderr, "rrdtool: `XFF' must "
1106 "be in the range 0 to 1 (exclusive).");
1107 ERROR ("rrdtool: `XFF' must "
1108 "be in the range 0 to 1 (exclusive).");
1109 return (1);
1110 }
1111 rrdcreate_config.xff = tmp;
1112 }
1113 else if (strcasecmp ("WritesPerSecond", key) == 0)
1114 {
1115 double wps = atof (value);
1117 if (wps < 0.0)
1118 {
1119 fprintf (stderr, "rrdtool: `WritesPerSecond' must be "
1120 "greater than or equal to zero.");
1121 return (1);
1122 }
1123 else if (wps == 0.0)
1124 {
1125 write_rate = 0.0;
1126 }
1127 else
1128 {
1129 write_rate = 1.0 / wps;
1130 }
1131 }
1132 else if (strcasecmp ("RandomTimeout", key) == 0)
1133 {
1134 double tmp;
1136 tmp = atof (value);
1137 if (tmp < 0.0)
1138 {
1139 fprintf (stderr, "rrdtool: `RandomTimeout' must "
1140 "be greater than or equal to zero.\n");
1141 ERROR ("rrdtool: `RandomTimeout' must "
1142 "be greater then or equal to zero.");
1143 }
1144 else
1145 {
1146 random_timeout = DOUBLE_TO_CDTIME_T (tmp);
1147 }
1148 }
1149 else
1150 {
1151 return (-1);
1152 }
1153 return (0);
1154 } /* int rrd_config */
1156 static int rrd_shutdown (void)
1157 {
1158 pthread_mutex_lock (&cache_lock);
1159 rrd_cache_flush (0);
1160 pthread_mutex_unlock (&cache_lock);
1162 pthread_mutex_lock (&queue_lock);
1163 do_shutdown = 1;
1164 pthread_cond_signal (&queue_cond);
1165 pthread_mutex_unlock (&queue_lock);
1167 if ((queue_thread_running != 0)
1168 && ((queue_head != NULL) || (flushq_head != NULL)))
1169 {
1170 INFO ("rrdtool plugin: Shutting down the queue thread. "
1171 "This may take a while.");
1172 }
1173 else if (queue_thread_running != 0)
1174 {
1175 INFO ("rrdtool plugin: Shutting down the queue thread.");
1176 }
1178 /* Wait for all the values to be written to disk before returning. */
1179 if (queue_thread_running != 0)
1180 {
1181 pthread_join (queue_thread, NULL);
1182 memset (&queue_thread, 0, sizeof (queue_thread));
1183 queue_thread_running = 0;
1184 DEBUG ("rrdtool plugin: queue_thread exited.");
1185 }
1187 rrd_cache_destroy ();
1189 return (0);
1190 } /* int rrd_shutdown */
1192 static int rrd_init (void)
1193 {
1194 static int init_once = 0;
1195 int status;
1197 if (init_once != 0)
1198 return (0);
1199 init_once = 1;
1201 if (rrdcreate_config.heartbeat <= 0)
1202 rrdcreate_config.heartbeat = 2 * rrdcreate_config.stepsize;
1204 /* Set the cache up */
1205 pthread_mutex_lock (&cache_lock);
1207 cache = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1208 if (cache == NULL)
1209 {
1210 pthread_mutex_unlock (&cache_lock);
1211 ERROR ("rrdtool plugin: c_avl_create failed.");
1212 return (-1);
1213 }
1215 cache_flush_last = cdtime ();
1216 if (cache_timeout == 0)
1217 {
1218 cache_flush_timeout = 0;
1219 }
1220 else if (cache_flush_timeout < cache_timeout)
1221 cache_flush_timeout = 10 * cache_timeout;
1223 pthread_mutex_unlock (&cache_lock);
1225 status = plugin_thread_create (&queue_thread, /* attr = */ NULL,
1226 rrd_queue_thread, /* args = */ NULL);
1227 if (status != 0)
1228 {
1229 ERROR ("rrdtool plugin: Cannot create queue-thread.");
1230 return (-1);
1231 }
1232 queue_thread_running = 1;
1234 DEBUG ("rrdtool plugin: rrd_init: datadir = %s; stepsize = %lu;"
1235 " heartbeat = %i; rrarows = %i; xff = %lf;",
1236 (datadir == NULL) ? "(null)" : datadir,
1237 rrdcreate_config.stepsize,
1238 rrdcreate_config.heartbeat,
1239 rrdcreate_config.rrarows,
1240 rrdcreate_config.xff);
1242 return (0);
1243 } /* int rrd_init */
1245 void module_register (void)
1246 {
1247 plugin_register_config ("rrdtool", rrd_config,
1248 config_keys, config_keys_num);
1249 plugin_register_init ("rrdtool", rrd_init);
1250 plugin_register_write ("rrdtool", rrd_write, /* user_data = */ NULL);
1251 plugin_register_flush ("rrdtool", rrd_flush, /* user_data = */ NULL);
1252 plugin_register_shutdown ("rrdtool", rrd_shutdown);
1253 }