Merge pull request #2618 from ajssmith/amqp1_dev1_branch
[collectd.git] / src / daemon / utils_cache.c
1 /**
2  * collectd - src/utils_cache.c
3  * Copyright (C) 2007-2010  Florian octo Forster
4  * Copyright (C) 2016       Sebastian tokkee Harl
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  *
24  * Authors:
25  *   Florian octo Forster <octo at collectd.org>
26  *   Sebastian tokkee Harl <sh at tokkee.org>
27  **/
28
29 #include "collectd.h"
30
31 #include "common.h"
32 #include "meta_data.h"
33 #include "plugin.h"
34 #include "utils_avltree.h"
35 #include "utils_cache.h"
36
37 #include <assert.h>
38
39 typedef struct cache_entry_s {
40   char name[6 * DATA_MAX_NAME_LEN];
41   size_t values_num;
42   gauge_t *values_gauge;
43   value_t *values_raw;
44   /* Time contained in the package
45    * (for calculating rates) */
46   cdtime_t last_time;
47   /* Time according to the local clock
48    * (for purging old entries) */
49   cdtime_t last_update;
50   /* Interval in which the data is collected
51    * (for purging old entries) */
52   cdtime_t interval;
53   int state;
54   int hits;
55
56   /*
57    * +-----+-----+-----+-----+-----+-----+-----+-----+-----+----
58    * !  0  !  1  !  2  !  3  !  4  !  5  !  6  !  7  !  8  ! ...
59    * +-----+-----+-----+-----+-----+-----+-----+-----+-----+----
60    * ! ds0 ! ds1 ! ds2 ! ds0 ! ds1 ! ds2 ! ds0 ! ds1 ! ds2 ! ...
61    * +-----+-----+-----+-----+-----+-----+-----+-----+-----+----
62    * !      t = 0      !      t = 1      !      t = 2      ! ...
63    * +-----------------+-----------------+-----------------+----
64    */
65   gauge_t *history;
66   size_t history_index; /* points to the next position to write to. */
67   size_t history_length;
68
69   meta_data_t *meta;
70 } cache_entry_t;
71
72 struct uc_iter_s {
73   c_avl_iterator_t *iter;
74
75   char *name;
76   cache_entry_t *entry;
77 };
78
79 static c_avl_tree_t *cache_tree;
80 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
81
82 static int cache_compare(const cache_entry_t *a, const cache_entry_t *b) {
83 #if COLLECT_DEBUG
84   assert((a != NULL) && (b != NULL));
85 #endif
86   return strcmp(a->name, b->name);
87 } /* int cache_compare */
88
89 static cache_entry_t *cache_alloc(size_t values_num) {
90   cache_entry_t *ce;
91
92   ce = calloc(1, sizeof(*ce));
93   if (ce == NULL) {
94     ERROR("utils_cache: cache_alloc: calloc failed.");
95     return NULL;
96   }
97   ce->values_num = values_num;
98
99   ce->values_gauge = calloc(values_num, sizeof(*ce->values_gauge));
100   ce->values_raw = calloc(values_num, sizeof(*ce->values_raw));
101   if ((ce->values_gauge == NULL) || (ce->values_raw == NULL)) {
102     sfree(ce->values_gauge);
103     sfree(ce->values_raw);
104     sfree(ce);
105     ERROR("utils_cache: cache_alloc: calloc failed.");
106     return NULL;
107   }
108
109   ce->history = NULL;
110   ce->history_length = 0;
111   ce->meta = NULL;
112
113   return ce;
114 } /* cache_entry_t *cache_alloc */
115
116 static void cache_free(cache_entry_t *ce) {
117   if (ce == NULL)
118     return;
119
120   sfree(ce->values_gauge);
121   sfree(ce->values_raw);
122   sfree(ce->history);
123   if (ce->meta != NULL) {
124     meta_data_destroy(ce->meta);
125     ce->meta = NULL;
126   }
127   sfree(ce);
128 } /* void cache_free */
129
130 static void uc_check_range(const data_set_t *ds, cache_entry_t *ce) {
131   for (size_t i = 0; i < ds->ds_num; i++) {
132     if (isnan(ce->values_gauge[i]))
133       continue;
134     else if (ce->values_gauge[i] < ds->ds[i].min)
135       ce->values_gauge[i] = NAN;
136     else if (ce->values_gauge[i] > ds->ds[i].max)
137       ce->values_gauge[i] = NAN;
138   }
139 } /* void uc_check_range */
140
141 static int uc_insert(const data_set_t *ds, const value_list_t *vl,
142                      const char *key) {
143   char *key_copy;
144   cache_entry_t *ce;
145
146   /* `cache_lock' has been locked by `uc_update' */
147
148   key_copy = strdup(key);
149   if (key_copy == NULL) {
150     ERROR("uc_insert: strdup failed.");
151     return -1;
152   }
153
154   ce = cache_alloc(ds->ds_num);
155   if (ce == NULL) {
156     sfree(key_copy);
157     ERROR("uc_insert: cache_alloc (%" PRIsz ") failed.", ds->ds_num);
158     return -1;
159   }
160
161   sstrncpy(ce->name, key, sizeof(ce->name));
162
163   for (size_t i = 0; i < ds->ds_num; i++) {
164     switch (ds->ds[i].type) {
165     case DS_TYPE_COUNTER:
166       ce->values_gauge[i] = NAN;
167       ce->values_raw[i].counter = vl->values[i].counter;
168       break;
169
170     case DS_TYPE_GAUGE:
171       ce->values_gauge[i] = vl->values[i].gauge;
172       ce->values_raw[i].gauge = vl->values[i].gauge;
173       break;
174
175     case DS_TYPE_DERIVE:
176       ce->values_gauge[i] = NAN;
177       ce->values_raw[i].derive = vl->values[i].derive;
178       break;
179
180     case DS_TYPE_ABSOLUTE:
181       ce->values_gauge[i] = NAN;
182       if (vl->interval > 0)
183         ce->values_gauge[i] =
184             ((double)vl->values[i].absolute) / CDTIME_T_TO_DOUBLE(vl->interval);
185       ce->values_raw[i].absolute = vl->values[i].absolute;
186       break;
187
188     default:
189       /* This shouldn't happen. */
190       ERROR("uc_insert: Don't know how to handle data source type %i.",
191             ds->ds[i].type);
192       sfree(key_copy);
193       cache_free(ce);
194       return -1;
195     } /* switch (ds->ds[i].type) */
196   }   /* for (i) */
197
198   /* Prune invalid gauge data */
199   uc_check_range(ds, ce);
200
201   ce->last_time = vl->time;
202   ce->last_update = cdtime();
203   ce->interval = vl->interval;
204   ce->state = STATE_OKAY;
205
206   if (c_avl_insert(cache_tree, key_copy, ce) != 0) {
207     sfree(key_copy);
208     ERROR("uc_insert: c_avl_insert failed.");
209     return -1;
210   }
211
212   DEBUG("uc_insert: Added %s to the cache.", key);
213   return 0;
214 } /* int uc_insert */
215
216 int uc_init(void) {
217   if (cache_tree == NULL)
218     cache_tree =
219         c_avl_create((int (*)(const void *, const void *))cache_compare);
220
221   return 0;
222 } /* int uc_init */
223
224 int uc_check_timeout(void) {
225   struct {
226     char *key;
227     cdtime_t time;
228     cdtime_t interval;
229   } *expired = NULL;
230   size_t expired_num = 0;
231
232   pthread_mutex_lock(&cache_lock);
233   cdtime_t now = cdtime();
234
235   /* Build a list of entries to be flushed */
236   c_avl_iterator_t *iter = c_avl_get_iterator(cache_tree);
237   char *key = NULL;
238   cache_entry_t *ce = NULL;
239   while (c_avl_iterator_next(iter, (void *)&key, (void *)&ce) == 0) {
240     /* If the entry is fresh enough, continue. */
241     if ((now - ce->last_update) < (ce->interval * timeout_g))
242       continue;
243
244     void *tmp = realloc(expired, (expired_num + 1) * sizeof(*expired));
245     if (tmp == NULL) {
246       ERROR("uc_check_timeout: realloc failed.");
247       continue;
248     }
249     expired = tmp;
250
251     expired[expired_num].key = strdup(key);
252     expired[expired_num].time = ce->last_time;
253     expired[expired_num].interval = ce->interval;
254
255     if (expired[expired_num].key == NULL) {
256       ERROR("uc_check_timeout: strdup failed.");
257       continue;
258     }
259
260     expired_num++;
261   } /* while (c_avl_iterator_next) */
262
263   c_avl_iterator_destroy(iter);
264   pthread_mutex_unlock(&cache_lock);
265
266   if (expired_num == 0) {
267     sfree(expired);
268     return 0;
269   }
270
271   /* Call the "missing" callback for each value. Do this before removing the
272    * value from the cache, so that callbacks can still access the data stored,
273    * including plugin specific meta data, rates, history, â€¦. This must be done
274    * without holding the lock, otherwise we will run into a deadlock if a
275    * plugin calls the cache interface. */
276   for (size_t i = 0; i < expired_num; i++) {
277     value_list_t vl = {
278         .time = expired[i].time, .interval = expired[i].interval,
279     };
280
281     if (parse_identifier_vl(expired[i].key, &vl) != 0) {
282       ERROR("uc_check_timeout: parse_identifier_vl (\"%s\") failed.",
283             expired[i].key);
284       continue;
285     }
286
287     plugin_dispatch_missing(&vl);
288   } /* for (i = 0; i < expired_num; i++) */
289
290   /* Now actually remove all the values from the cache. We don't re-evaluate
291    * the timestamp again, so in theory it is possible we remove a value after
292    * it is updated here. */
293   pthread_mutex_lock(&cache_lock);
294   for (size_t i = 0; i < expired_num; i++) {
295     char *key = NULL;
296     cache_entry_t *value = NULL;
297
298     if (c_avl_remove(cache_tree, expired[i].key, (void *)&key,
299                      (void *)&value) != 0) {
300       ERROR("uc_check_timeout: c_avl_remove (\"%s\") failed.", expired[i].key);
301       sfree(expired[i].key);
302       continue;
303     }
304     sfree(key);
305     cache_free(value);
306
307     sfree(expired[i].key);
308   } /* for (i = 0; i < expired_num; i++) */
309   pthread_mutex_unlock(&cache_lock);
310
311   sfree(expired);
312   return 0;
313 } /* int uc_check_timeout */
314
315 int uc_update(const data_set_t *ds, const value_list_t *vl) {
316   char name[6 * DATA_MAX_NAME_LEN];
317   cache_entry_t *ce = NULL;
318   int status;
319
320   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
321     ERROR("uc_update: FORMAT_VL failed.");
322     return -1;
323   }
324
325   pthread_mutex_lock(&cache_lock);
326
327   status = c_avl_get(cache_tree, name, (void *)&ce);
328   if (status != 0) /* entry does not yet exist */
329   {
330     status = uc_insert(ds, vl, name);
331     pthread_mutex_unlock(&cache_lock);
332     return status;
333   }
334
335   assert(ce != NULL);
336   assert(ce->values_num == ds->ds_num);
337
338   if (ce->last_time >= vl->time) {
339     pthread_mutex_unlock(&cache_lock);
340     NOTICE("uc_update: Value too old: name = %s; value time = %.3f; "
341            "last cache update = %.3f;",
342            name, CDTIME_T_TO_DOUBLE(vl->time),
343            CDTIME_T_TO_DOUBLE(ce->last_time));
344     return -1;
345   }
346
347   for (size_t i = 0; i < ds->ds_num; i++) {
348     switch (ds->ds[i].type) {
349     case DS_TYPE_COUNTER: {
350       counter_t diff =
351           counter_diff(ce->values_raw[i].counter, vl->values[i].counter);
352       ce->values_gauge[i] =
353           ((double)diff) / (CDTIME_T_TO_DOUBLE(vl->time - ce->last_time));
354       ce->values_raw[i].counter = vl->values[i].counter;
355     } break;
356
357     case DS_TYPE_GAUGE:
358       ce->values_raw[i].gauge = vl->values[i].gauge;
359       ce->values_gauge[i] = vl->values[i].gauge;
360       break;
361
362     case DS_TYPE_DERIVE: {
363       derive_t diff = vl->values[i].derive - ce->values_raw[i].derive;
364
365       ce->values_gauge[i] =
366           ((double)diff) / (CDTIME_T_TO_DOUBLE(vl->time - ce->last_time));
367       ce->values_raw[i].derive = vl->values[i].derive;
368     } break;
369
370     case DS_TYPE_ABSOLUTE:
371       ce->values_gauge[i] = ((double)vl->values[i].absolute) /
372                             (CDTIME_T_TO_DOUBLE(vl->time - ce->last_time));
373       ce->values_raw[i].absolute = vl->values[i].absolute;
374       break;
375
376     default:
377       /* This shouldn't happen. */
378       pthread_mutex_unlock(&cache_lock);
379       ERROR("uc_update: Don't know how to handle data source type %i.",
380             ds->ds[i].type);
381       return -1;
382     } /* switch (ds->ds[i].type) */
383
384     DEBUG("uc_update: %s: ds[%" PRIsz "] = %lf", name, i, ce->values_gauge[i]);
385   } /* for (i) */
386
387   /* Update the history if it exists. */
388   if (ce->history != NULL) {
389     assert(ce->history_index < ce->history_length);
390     for (size_t i = 0; i < ce->values_num; i++) {
391       size_t hist_idx = (ce->values_num * ce->history_index) + i;
392       ce->history[hist_idx] = ce->values_gauge[i];
393     }
394
395     assert(ce->history_length > 0);
396     ce->history_index = (ce->history_index + 1) % ce->history_length;
397   }
398
399   /* Prune invalid gauge data */
400   uc_check_range(ds, ce);
401
402   ce->last_time = vl->time;
403   ce->last_update = cdtime();
404   ce->interval = vl->interval;
405
406   pthread_mutex_unlock(&cache_lock);
407
408   return 0;
409 } /* int uc_update */
410
411 int uc_get_rate_by_name(const char *name, gauge_t **ret_values,
412                         size_t *ret_values_num) {
413   gauge_t *ret = NULL;
414   size_t ret_num = 0;
415   cache_entry_t *ce = NULL;
416   int status = 0;
417
418   pthread_mutex_lock(&cache_lock);
419
420   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
421     assert(ce != NULL);
422
423     /* remove missing values from getval */
424     if (ce->state == STATE_MISSING) {
425       DEBUG("utils_cache: uc_get_rate_by_name: requested metric \"%s\" is in "
426             "state \"missing\".",
427             name);
428       status = -1;
429     } else {
430       ret_num = ce->values_num;
431       ret = malloc(ret_num * sizeof(*ret));
432       if (ret == NULL) {
433         ERROR("utils_cache: uc_get_rate_by_name: malloc failed.");
434         status = -1;
435       } else {
436         memcpy(ret, ce->values_gauge, ret_num * sizeof(gauge_t));
437       }
438     }
439   } else {
440     DEBUG("utils_cache: uc_get_rate_by_name: No such value: %s", name);
441     status = -1;
442   }
443
444   pthread_mutex_unlock(&cache_lock);
445
446   if (status == 0) {
447     *ret_values = ret;
448     *ret_values_num = ret_num;
449   }
450
451   return status;
452 } /* gauge_t *uc_get_rate_by_name */
453
454 gauge_t *uc_get_rate(const data_set_t *ds, const value_list_t *vl) {
455   char name[6 * DATA_MAX_NAME_LEN];
456   gauge_t *ret = NULL;
457   size_t ret_num = 0;
458   int status;
459
460   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
461     ERROR("utils_cache: uc_get_rate: FORMAT_VL failed.");
462     return NULL;
463   }
464
465   status = uc_get_rate_by_name(name, &ret, &ret_num);
466   if (status != 0)
467     return NULL;
468
469   /* This is important - the caller has no other way of knowing how many
470    * values are returned. */
471   if (ret_num != ds->ds_num) {
472     ERROR("utils_cache: uc_get_rate: ds[%s] has %" PRIsz " values, "
473           "but uc_get_rate_by_name returned %" PRIsz ".",
474           ds->type, ds->ds_num, ret_num);
475     sfree(ret);
476     return NULL;
477   }
478
479   return ret;
480 } /* gauge_t *uc_get_rate */
481
482 int uc_get_value_by_name(const char *name, value_t **ret_values,
483                          size_t *ret_values_num) {
484   value_t *ret = NULL;
485   size_t ret_num = 0;
486   cache_entry_t *ce = NULL;
487   int status = 0;
488
489   pthread_mutex_lock(&cache_lock);
490
491   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
492     assert(ce != NULL);
493
494     /* remove missing values from getval */
495     if (ce->state == STATE_MISSING) {
496       status = -1;
497     } else {
498       ret_num = ce->values_num;
499       ret = malloc(ret_num * sizeof(*ret));
500       if (ret == NULL) {
501         ERROR("utils_cache: uc_get_value_by_name: malloc failed.");
502         status = -1;
503       } else {
504         memcpy(ret, ce->values_raw, ret_num * sizeof(value_t));
505       }
506     }
507   } else {
508     DEBUG("utils_cache: uc_get_value_by_name: No such value: %s", name);
509     status = -1;
510   }
511
512   pthread_mutex_unlock(&cache_lock);
513
514   if (status == 0) {
515     *ret_values = ret;
516     *ret_values_num = ret_num;
517   }
518
519   return (status);
520 } /* int uc_get_value_by_name */
521
522 value_t *uc_get_value(const data_set_t *ds, const value_list_t *vl) {
523   char name[6 * DATA_MAX_NAME_LEN];
524   value_t *ret = NULL;
525   size_t ret_num = 0;
526   int status;
527
528   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
529     ERROR("utils_cache: uc_get_value: FORMAT_VL failed.");
530     return (NULL);
531   }
532
533   status = uc_get_value_by_name(name, &ret, &ret_num);
534   if (status != 0)
535     return (NULL);
536
537   /* This is important - the caller has no other way of knowing how many
538    * values are returned. */
539   if (ret_num != (size_t)ds->ds_num) {
540     ERROR("utils_cache: uc_get_value: ds[%s] has %" PRIsz " values, "
541           "but uc_get_value_by_name returned %" PRIsz ".",
542           ds->type, ds->ds_num, ret_num);
543     sfree(ret);
544     return (NULL);
545   }
546
547   return (ret);
548 } /* value_t *uc_get_value */
549
550 size_t uc_get_size(void) {
551   size_t size_arrays = 0;
552
553   pthread_mutex_lock(&cache_lock);
554   size_arrays = (size_t)c_avl_size(cache_tree);
555   pthread_mutex_unlock(&cache_lock);
556
557   return size_arrays;
558 }
559
560 int uc_get_names(char ***ret_names, cdtime_t **ret_times, size_t *ret_number) {
561   c_avl_iterator_t *iter;
562   char *key;
563   cache_entry_t *value;
564
565   char **names = NULL;
566   cdtime_t *times = NULL;
567   size_t number = 0;
568   size_t size_arrays = 0;
569
570   int status = 0;
571
572   if ((ret_names == NULL) || (ret_number == NULL))
573     return -1;
574
575   pthread_mutex_lock(&cache_lock);
576
577   size_arrays = (size_t)c_avl_size(cache_tree);
578   if (size_arrays < 1) {
579     /* Handle the "no values" case here, to avoid the error message when
580      * calloc() returns NULL. */
581     pthread_mutex_unlock(&cache_lock);
582     return 0;
583   }
584
585   names = calloc(size_arrays, sizeof(*names));
586   times = calloc(size_arrays, sizeof(*times));
587   if ((names == NULL) || (times == NULL)) {
588     ERROR("uc_get_names: calloc failed.");
589     sfree(names);
590     sfree(times);
591     pthread_mutex_unlock(&cache_lock);
592     return ENOMEM;
593   }
594
595   iter = c_avl_get_iterator(cache_tree);
596   while (c_avl_iterator_next(iter, (void *)&key, (void *)&value) == 0) {
597     /* remove missing values when list values */
598     if (value->state == STATE_MISSING)
599       continue;
600
601     /* c_avl_size does not return a number smaller than the number of elements
602      * returned by c_avl_iterator_next. */
603     assert(number < size_arrays);
604
605     if (ret_times != NULL)
606       times[number] = value->last_time;
607
608     names[number] = strdup(key);
609     if (names[number] == NULL) {
610       status = -1;
611       break;
612     }
613
614     number++;
615   } /* while (c_avl_iterator_next) */
616
617   c_avl_iterator_destroy(iter);
618   pthread_mutex_unlock(&cache_lock);
619
620   if (status != 0) {
621     for (size_t i = 0; i < number; i++) {
622       sfree(names[i]);
623     }
624     sfree(names);
625     sfree(times);
626
627     return -1;
628   }
629
630   *ret_names = names;
631   if (ret_times != NULL)
632     *ret_times = times;
633   else
634     sfree(times);
635   *ret_number = number;
636
637   return 0;
638 } /* int uc_get_names */
639
640 int uc_get_state(const data_set_t *ds, const value_list_t *vl) {
641   char name[6 * DATA_MAX_NAME_LEN];
642   cache_entry_t *ce = NULL;
643   int ret = STATE_ERROR;
644
645   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
646     ERROR("uc_get_state: FORMAT_VL failed.");
647     return STATE_ERROR;
648   }
649
650   pthread_mutex_lock(&cache_lock);
651
652   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
653     assert(ce != NULL);
654     ret = ce->state;
655   }
656
657   pthread_mutex_unlock(&cache_lock);
658
659   return ret;
660 } /* int uc_get_state */
661
662 int uc_set_state(const data_set_t *ds, const value_list_t *vl, int state) {
663   char name[6 * DATA_MAX_NAME_LEN];
664   cache_entry_t *ce = NULL;
665   int ret = -1;
666
667   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
668     ERROR("uc_set_state: FORMAT_VL failed.");
669     return STATE_ERROR;
670   }
671
672   pthread_mutex_lock(&cache_lock);
673
674   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
675     assert(ce != NULL);
676     ret = ce->state;
677     ce->state = state;
678   }
679
680   pthread_mutex_unlock(&cache_lock);
681
682   return ret;
683 } /* int uc_set_state */
684
685 int uc_get_history_by_name(const char *name, gauge_t *ret_history,
686                            size_t num_steps, size_t num_ds) {
687   cache_entry_t *ce = NULL;
688   int status = 0;
689
690   pthread_mutex_lock(&cache_lock);
691
692   status = c_avl_get(cache_tree, name, (void *)&ce);
693   if (status != 0) {
694     pthread_mutex_unlock(&cache_lock);
695     return -ENOENT;
696   }
697
698   if (((size_t)ce->values_num) != num_ds) {
699     pthread_mutex_unlock(&cache_lock);
700     return -EINVAL;
701   }
702
703   /* Check if there are enough values available. If not, increase the buffer
704    * size. */
705   if (ce->history_length < num_steps) {
706     gauge_t *tmp;
707
708     tmp =
709         realloc(ce->history, sizeof(*ce->history) * num_steps * ce->values_num);
710     if (tmp == NULL) {
711       pthread_mutex_unlock(&cache_lock);
712       return -ENOMEM;
713     }
714
715     for (size_t i = ce->history_length * ce->values_num;
716          i < (num_steps * ce->values_num); i++)
717       tmp[i] = NAN;
718
719     ce->history = tmp;
720     ce->history_length = num_steps;
721   } /* if (ce->history_length < num_steps) */
722
723   /* Copy the values to the output buffer. */
724   for (size_t i = 0; i < num_steps; i++) {
725     size_t src_index;
726     size_t dst_index;
727
728     if (i < ce->history_index)
729       src_index = ce->history_index - (i + 1);
730     else
731       src_index = ce->history_length + ce->history_index - (i + 1);
732     src_index = src_index * num_ds;
733
734     dst_index = i * num_ds;
735
736     memcpy(ret_history + dst_index, ce->history + src_index,
737            sizeof(*ret_history) * num_ds);
738   }
739
740   pthread_mutex_unlock(&cache_lock);
741
742   return 0;
743 } /* int uc_get_history_by_name */
744
745 int uc_get_history(const data_set_t *ds, const value_list_t *vl,
746                    gauge_t *ret_history, size_t num_steps, size_t num_ds) {
747   char name[6 * DATA_MAX_NAME_LEN];
748
749   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
750     ERROR("utils_cache: uc_get_history: FORMAT_VL failed.");
751     return -1;
752   }
753
754   return uc_get_history_by_name(name, ret_history, num_steps, num_ds);
755 } /* int uc_get_history */
756
757 int uc_get_hits(const data_set_t *ds, const value_list_t *vl) {
758   char name[6 * DATA_MAX_NAME_LEN];
759   cache_entry_t *ce = NULL;
760   int ret = STATE_ERROR;
761
762   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
763     ERROR("uc_get_hits: FORMAT_VL failed.");
764     return STATE_ERROR;
765   }
766
767   pthread_mutex_lock(&cache_lock);
768
769   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
770     assert(ce != NULL);
771     ret = ce->hits;
772   }
773
774   pthread_mutex_unlock(&cache_lock);
775
776   return ret;
777 } /* int uc_get_hits */
778
779 int uc_set_hits(const data_set_t *ds, const value_list_t *vl, int hits) {
780   char name[6 * DATA_MAX_NAME_LEN];
781   cache_entry_t *ce = NULL;
782   int ret = -1;
783
784   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
785     ERROR("uc_set_hits: FORMAT_VL failed.");
786     return STATE_ERROR;
787   }
788
789   pthread_mutex_lock(&cache_lock);
790
791   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
792     assert(ce != NULL);
793     ret = ce->hits;
794     ce->hits = hits;
795   }
796
797   pthread_mutex_unlock(&cache_lock);
798
799   return ret;
800 } /* int uc_set_hits */
801
802 int uc_inc_hits(const data_set_t *ds, const value_list_t *vl, int step) {
803   char name[6 * DATA_MAX_NAME_LEN];
804   cache_entry_t *ce = NULL;
805   int ret = -1;
806
807   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
808     ERROR("uc_inc_hits: FORMAT_VL failed.");
809     return STATE_ERROR;
810   }
811
812   pthread_mutex_lock(&cache_lock);
813
814   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
815     assert(ce != NULL);
816     ret = ce->hits;
817     ce->hits = ret + step;
818   }
819
820   pthread_mutex_unlock(&cache_lock);
821
822   return ret;
823 } /* int uc_inc_hits */
824
825 /*
826  * Iterator interface
827  */
828 uc_iter_t *uc_get_iterator(void) {
829   uc_iter_t *iter;
830
831   iter = (uc_iter_t *)calloc(1, sizeof(*iter));
832   if (iter == NULL)
833     return NULL;
834
835   pthread_mutex_lock(&cache_lock);
836
837   iter->iter = c_avl_get_iterator(cache_tree);
838   if (iter->iter == NULL) {
839     free(iter);
840     return NULL;
841   }
842
843   return iter;
844 } /* uc_iter_t *uc_get_iterator */
845
846 int uc_iterator_next(uc_iter_t *iter, char **ret_name) {
847   int status;
848
849   if (iter == NULL)
850     return -1;
851
852   while ((status = c_avl_iterator_next(iter->iter, (void *)&iter->name,
853                                        (void *)&iter->entry)) == 0) {
854     if (iter->entry->state == STATE_MISSING)
855       continue;
856
857     break;
858   }
859   if (status != 0) {
860     iter->name = NULL;
861     iter->entry = NULL;
862     return -1;
863   }
864
865   if (ret_name != NULL)
866     *ret_name = iter->name;
867
868   return 0;
869 } /* int uc_iterator_next */
870
871 void uc_iterator_destroy(uc_iter_t *iter) {
872   if (iter == NULL)
873     return;
874
875   c_avl_iterator_destroy(iter->iter);
876   pthread_mutex_unlock(&cache_lock);
877
878   free(iter);
879 } /* void uc_iterator_destroy */
880
881 int uc_iterator_get_time(uc_iter_t *iter, cdtime_t *ret_time) {
882   if ((iter == NULL) || (iter->entry == NULL) || (ret_time == NULL))
883     return -1;
884
885   *ret_time = iter->entry->last_time;
886   return 0;
887 } /* int uc_iterator_get_name */
888
889 int uc_iterator_get_values(uc_iter_t *iter, value_t **ret_values,
890                            size_t *ret_num) {
891   if ((iter == NULL) || (iter->entry == NULL) || (ret_values == NULL) ||
892       (ret_num == NULL))
893     return -1;
894
895   *ret_values =
896       calloc(iter->entry->values_num, sizeof(*iter->entry->values_raw));
897   if (*ret_values == NULL)
898     return -1;
899   for (size_t i = 0; i < iter->entry->values_num; ++i)
900     *ret_values[i] = iter->entry->values_raw[i];
901
902   *ret_num = iter->entry->values_num;
903
904   return 0;
905 } /* int uc_iterator_get_values */
906
907 int uc_iterator_get_interval(uc_iter_t *iter, cdtime_t *ret_interval) {
908   if ((iter == NULL) || (iter->entry == NULL) || (ret_interval == NULL))
909     return -1;
910
911   *ret_interval = iter->entry->interval;
912   return 0;
913 } /* int uc_iterator_get_name */
914
915 int uc_iterator_get_meta(uc_iter_t *iter, meta_data_t **ret_meta) {
916   if ((iter == NULL) || (iter->entry == NULL) || (ret_meta == NULL))
917     return -1;
918
919   *ret_meta = meta_data_clone(iter->entry->meta);
920
921   return 0;
922 } /* int uc_iterator_get_meta */
923
924 /*
925  * Meta data interface
926  */
927 /* XXX: This function will acquire `cache_lock' but will not free it! */
928 static meta_data_t *uc_get_meta(const value_list_t *vl) /* {{{ */
929 {
930   char name[6 * DATA_MAX_NAME_LEN];
931   cache_entry_t *ce = NULL;
932   int status;
933
934   status = FORMAT_VL(name, sizeof(name), vl);
935   if (status != 0) {
936     ERROR("utils_cache: uc_get_meta: FORMAT_VL failed.");
937     return NULL;
938   }
939
940   pthread_mutex_lock(&cache_lock);
941
942   status = c_avl_get(cache_tree, name, (void *)&ce);
943   if (status != 0) {
944     pthread_mutex_unlock(&cache_lock);
945     return NULL;
946   }
947   assert(ce != NULL);
948
949   if (ce->meta == NULL)
950     ce->meta = meta_data_create();
951
952   if (ce->meta == NULL)
953     pthread_mutex_unlock(&cache_lock);
954
955   return ce->meta;
956 } /* }}} meta_data_t *uc_get_meta */
957
958 /* Sorry about this preprocessor magic, but it really makes this file much
959  * shorter.. */
960 #define UC_WRAP(wrap_function)                                                 \
961   {                                                                            \
962     meta_data_t *meta;                                                         \
963     int status;                                                                \
964     meta = uc_get_meta(vl);                                                    \
965     if (meta == NULL)                                                          \
966       return -1;                                                               \
967     status = wrap_function(meta, key);                                         \
968     pthread_mutex_unlock(&cache_lock);                                         \
969     return status;                                                             \
970   }
971 int uc_meta_data_exists(const value_list_t *vl,
972                         const char *key) UC_WRAP(meta_data_exists)
973
974     int uc_meta_data_delete(const value_list_t *vl,
975                             const char *key) UC_WRAP(meta_data_delete)
976 #undef UC_WRAP
977
978 /* We need a new version of this macro because the following functions take
979  * two argumetns. */
980 #define UC_WRAP(wrap_function)                                                 \
981   {                                                                            \
982     meta_data_t *meta;                                                         \
983     int status;                                                                \
984     meta = uc_get_meta(vl);                                                    \
985     if (meta == NULL)                                                          \
986       return -1;                                                               \
987     status = wrap_function(meta, key, value);                                  \
988     pthread_mutex_unlock(&cache_lock);                                         \
989     return status;                                                             \
990   }
991         int uc_meta_data_add_string(const value_list_t *vl, const char *key,
992                                     const char *value)
993             UC_WRAP(meta_data_add_string) int uc_meta_data_add_signed_int(
994                 const value_list_t *vl, const char *key, int64_t value)
995                 UC_WRAP(meta_data_add_signed_int) int uc_meta_data_add_unsigned_int(
996                     const value_list_t *vl, const char *key, uint64_t value)
997                     UC_WRAP(meta_data_add_unsigned_int) int uc_meta_data_add_double(
998                         const value_list_t *vl, const char *key, double value)
999                         UC_WRAP(meta_data_add_double) int uc_meta_data_add_boolean(
1000                             const value_list_t *vl, const char *key,
1001                             bool value) UC_WRAP(meta_data_add_boolean)
1002
1003                             int uc_meta_data_get_string(const value_list_t *vl,
1004                                                         const char *key,
1005                                                         char **value)
1006                                 UC_WRAP(meta_data_get_string) int uc_meta_data_get_signed_int(
1007                                     const value_list_t *vl, const char *key,
1008                                     int64_t *value)
1009                                     UC_WRAP(meta_data_get_signed_int) int uc_meta_data_get_unsigned_int(
1010                                         const value_list_t *vl, const char *key,
1011                                         uint64_t *value)
1012                                         UC_WRAP(meta_data_get_unsigned_int) int uc_meta_data_get_double(
1013                                             const value_list_t *vl,
1014                                             const char *key, double *value)
1015                                             UC_WRAP(meta_data_get_double) int uc_meta_data_get_boolean(
1016                                                 const value_list_t *vl,
1017                                                 const char *key, bool *value)
1018                                                 UC_WRAP(meta_data_get_boolean)
1019 #undef UC_WRAP