utils_cache: fix pointer reference and meta_data ingestion
[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 = NULL;
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 (vl->meta != NULL) {
207     ce->meta = meta_data_clone(vl->meta);
208   }
209
210   if (c_avl_insert(cache_tree, key_copy, ce) != 0) {
211     sfree(key_copy);
212     ERROR("uc_insert: c_avl_insert failed.");
213     return -1;
214   }
215
216   DEBUG("uc_insert: Added %s to the cache.", key);
217   return 0;
218 } /* int uc_insert */
219
220 int uc_init(void) {
221   if (cache_tree == NULL)
222     cache_tree =
223         c_avl_create((int (*)(const void *, const void *))cache_compare);
224
225   return 0;
226 } /* int uc_init */
227
228 int uc_check_timeout(void) {
229   struct {
230     char *key;
231     cdtime_t time;
232     cdtime_t interval;
233   } *expired = NULL;
234   size_t expired_num = 0;
235
236   pthread_mutex_lock(&cache_lock);
237   cdtime_t now = cdtime();
238
239   /* Build a list of entries to be flushed */
240   c_avl_iterator_t *iter = c_avl_get_iterator(cache_tree);
241   char *key = NULL;
242   cache_entry_t *ce = NULL;
243   while (c_avl_iterator_next(iter, (void *)&key, (void *)&ce) == 0) {
244     /* If the entry is fresh enough, continue. */
245     if ((now - ce->last_update) < (ce->interval * timeout_g))
246       continue;
247
248     void *tmp = realloc(expired, (expired_num + 1) * sizeof(*expired));
249     if (tmp == NULL) {
250       ERROR("uc_check_timeout: realloc failed.");
251       continue;
252     }
253     expired = tmp;
254
255     expired[expired_num].key = strdup(key);
256     expired[expired_num].time = ce->last_time;
257     expired[expired_num].interval = ce->interval;
258
259     if (expired[expired_num].key == NULL) {
260       ERROR("uc_check_timeout: strdup failed.");
261       continue;
262     }
263
264     expired_num++;
265   } /* while (c_avl_iterator_next) */
266
267   c_avl_iterator_destroy(iter);
268   pthread_mutex_unlock(&cache_lock);
269
270   if (expired_num == 0) {
271     sfree(expired);
272     return 0;
273   }
274
275   /* Call the "missing" callback for each value. Do this before removing the
276    * value from the cache, so that callbacks can still access the data stored,
277    * including plugin specific meta data, rates, history, â€¦. This must be done
278    * without holding the lock, otherwise we will run into a deadlock if a
279    * plugin calls the cache interface. */
280   for (size_t i = 0; i < expired_num; i++) {
281     value_list_t vl = {
282         .time = expired[i].time, .interval = expired[i].interval,
283     };
284
285     if (parse_identifier_vl(expired[i].key, &vl) != 0) {
286       ERROR("uc_check_timeout: parse_identifier_vl (\"%s\") failed.",
287             expired[i].key);
288       continue;
289     }
290
291     plugin_dispatch_missing(&vl);
292   } /* for (i = 0; i < expired_num; i++) */
293
294   /* Now actually remove all the values from the cache. We don't re-evaluate
295    * the timestamp again, so in theory it is possible we remove a value after
296    * it is updated here. */
297   pthread_mutex_lock(&cache_lock);
298   for (size_t i = 0; i < expired_num; i++) {
299     char *key = NULL;
300     cache_entry_t *value = NULL;
301
302     if (c_avl_remove(cache_tree, expired[i].key, (void *)&key,
303                      (void *)&value) != 0) {
304       ERROR("uc_check_timeout: c_avl_remove (\"%s\") failed.", expired[i].key);
305       sfree(expired[i].key);
306       continue;
307     }
308     sfree(key);
309     cache_free(value);
310
311     sfree(expired[i].key);
312   } /* for (i = 0; i < expired_num; i++) */
313   pthread_mutex_unlock(&cache_lock);
314
315   sfree(expired);
316   return 0;
317 } /* int uc_check_timeout */
318
319 int uc_update(const data_set_t *ds, const value_list_t *vl) {
320   char name[6 * DATA_MAX_NAME_LEN];
321   cache_entry_t *ce = NULL;
322   int status;
323
324   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
325     ERROR("uc_update: FORMAT_VL failed.");
326     return -1;
327   }
328
329   pthread_mutex_lock(&cache_lock);
330
331   status = c_avl_get(cache_tree, name, (void *)&ce);
332   if (status != 0) /* entry does not yet exist */
333   {
334     status = uc_insert(ds, vl, name);
335     pthread_mutex_unlock(&cache_lock);
336     return status;
337   }
338
339   assert(ce != NULL);
340   assert(ce->values_num == ds->ds_num);
341
342   if (ce->last_time >= vl->time) {
343     pthread_mutex_unlock(&cache_lock);
344     NOTICE("uc_update: Value too old: name = %s; value time = %.3f; "
345            "last cache update = %.3f;",
346            name, CDTIME_T_TO_DOUBLE(vl->time),
347            CDTIME_T_TO_DOUBLE(ce->last_time));
348     return -1;
349   }
350
351   for (size_t i = 0; i < ds->ds_num; i++) {
352     switch (ds->ds[i].type) {
353     case DS_TYPE_COUNTER: {
354       counter_t diff =
355           counter_diff(ce->values_raw[i].counter, vl->values[i].counter);
356       ce->values_gauge[i] =
357           ((double)diff) / (CDTIME_T_TO_DOUBLE(vl->time - ce->last_time));
358       ce->values_raw[i].counter = vl->values[i].counter;
359     } break;
360
361     case DS_TYPE_GAUGE:
362       ce->values_raw[i].gauge = vl->values[i].gauge;
363       ce->values_gauge[i] = vl->values[i].gauge;
364       break;
365
366     case DS_TYPE_DERIVE: {
367       derive_t diff = vl->values[i].derive - ce->values_raw[i].derive;
368
369       ce->values_gauge[i] =
370           ((double)diff) / (CDTIME_T_TO_DOUBLE(vl->time - ce->last_time));
371       ce->values_raw[i].derive = vl->values[i].derive;
372     } break;
373
374     case DS_TYPE_ABSOLUTE:
375       ce->values_gauge[i] = ((double)vl->values[i].absolute) /
376                             (CDTIME_T_TO_DOUBLE(vl->time - ce->last_time));
377       ce->values_raw[i].absolute = vl->values[i].absolute;
378       break;
379
380     default:
381       /* This shouldn't happen. */
382       pthread_mutex_unlock(&cache_lock);
383       ERROR("uc_update: Don't know how to handle data source type %i.",
384             ds->ds[i].type);
385       return -1;
386     } /* switch (ds->ds[i].type) */
387
388     DEBUG("uc_update: %s: ds[%" PRIsz "] = %lf", name, i, ce->values_gauge[i]);
389   } /* for (i) */
390
391   /* Update the history if it exists. */
392   if (ce->history != NULL) {
393     assert(ce->history_index < ce->history_length);
394     for (size_t i = 0; i < ce->values_num; i++) {
395       size_t hist_idx = (ce->values_num * ce->history_index) + i;
396       ce->history[hist_idx] = ce->values_gauge[i];
397     }
398
399     assert(ce->history_length > 0);
400     ce->history_index = (ce->history_index + 1) % ce->history_length;
401   }
402
403   /* Prune invalid gauge data */
404   uc_check_range(ds, ce);
405
406   ce->last_time = vl->time;
407   ce->last_update = cdtime();
408   ce->interval = vl->interval;
409
410   pthread_mutex_unlock(&cache_lock);
411
412   return 0;
413 } /* int uc_update */
414
415 int uc_get_rate_by_name(const char *name, gauge_t **ret_values,
416                         size_t *ret_values_num) {
417   gauge_t *ret = NULL;
418   size_t ret_num = 0;
419   cache_entry_t *ce = NULL;
420   int status = 0;
421
422   pthread_mutex_lock(&cache_lock);
423
424   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
425     assert(ce != NULL);
426
427     /* remove missing values from getval */
428     if (ce->state == STATE_MISSING) {
429       DEBUG("utils_cache: uc_get_rate_by_name: requested metric \"%s\" is in "
430             "state \"missing\".",
431             name);
432       status = -1;
433     } else {
434       ret_num = ce->values_num;
435       ret = malloc(ret_num * sizeof(*ret));
436       if (ret == NULL) {
437         ERROR("utils_cache: uc_get_rate_by_name: malloc failed.");
438         status = -1;
439       } else {
440         memcpy(ret, ce->values_gauge, ret_num * sizeof(gauge_t));
441       }
442     }
443   } else {
444     DEBUG("utils_cache: uc_get_rate_by_name: No such value: %s", name);
445     status = -1;
446   }
447
448   pthread_mutex_unlock(&cache_lock);
449
450   if (status == 0) {
451     *ret_values = ret;
452     *ret_values_num = ret_num;
453   }
454
455   return status;
456 } /* gauge_t *uc_get_rate_by_name */
457
458 gauge_t *uc_get_rate(const data_set_t *ds, const value_list_t *vl) {
459   char name[6 * DATA_MAX_NAME_LEN];
460   gauge_t *ret = NULL;
461   size_t ret_num = 0;
462   int status;
463
464   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
465     ERROR("utils_cache: uc_get_rate: FORMAT_VL failed.");
466     return NULL;
467   }
468
469   status = uc_get_rate_by_name(name, &ret, &ret_num);
470   if (status != 0)
471     return NULL;
472
473   /* This is important - the caller has no other way of knowing how many
474    * values are returned. */
475   if (ret_num != ds->ds_num) {
476     ERROR("utils_cache: uc_get_rate: ds[%s] has %" PRIsz " values, "
477           "but uc_get_rate_by_name returned %" PRIsz ".",
478           ds->type, ds->ds_num, ret_num);
479     sfree(ret);
480     return NULL;
481   }
482
483   return ret;
484 } /* gauge_t *uc_get_rate */
485
486 int uc_get_value_by_name(const char *name, value_t **ret_values,
487                          size_t *ret_values_num) {
488   value_t *ret = NULL;
489   size_t ret_num = 0;
490   cache_entry_t *ce = NULL;
491   int status = 0;
492
493   pthread_mutex_lock(&cache_lock);
494
495   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
496     assert(ce != NULL);
497
498     /* remove missing values from getval */
499     if (ce->state == STATE_MISSING) {
500       status = -1;
501     } else {
502       ret_num = ce->values_num;
503       ret = malloc(ret_num * sizeof(*ret));
504       if (ret == NULL) {
505         ERROR("utils_cache: uc_get_value_by_name: malloc failed.");
506         status = -1;
507       } else {
508         memcpy(ret, ce->values_raw, ret_num * sizeof(value_t));
509       }
510     }
511   } else {
512     DEBUG("utils_cache: uc_get_value_by_name: No such value: %s", name);
513     status = -1;
514   }
515
516   pthread_mutex_unlock(&cache_lock);
517
518   if (status == 0) {
519     *ret_values = ret;
520     *ret_values_num = ret_num;
521   }
522
523   return (status);
524 } /* int uc_get_value_by_name */
525
526 value_t *uc_get_value(const data_set_t *ds, const value_list_t *vl) {
527   char name[6 * DATA_MAX_NAME_LEN];
528   value_t *ret = NULL;
529   size_t ret_num = 0;
530   int status;
531
532   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
533     ERROR("utils_cache: uc_get_value: FORMAT_VL failed.");
534     return (NULL);
535   }
536
537   status = uc_get_value_by_name(name, &ret, &ret_num);
538   if (status != 0)
539     return (NULL);
540
541   /* This is important - the caller has no other way of knowing how many
542    * values are returned. */
543   if (ret_num != (size_t)ds->ds_num) {
544     ERROR("utils_cache: uc_get_value: ds[%s] has %" PRIsz " values, "
545           "but uc_get_value_by_name returned %" PRIsz ".",
546           ds->type, ds->ds_num, ret_num);
547     sfree(ret);
548     return (NULL);
549   }
550
551   return (ret);
552 } /* value_t *uc_get_value */
553
554 size_t uc_get_size(void) {
555   size_t size_arrays = 0;
556
557   pthread_mutex_lock(&cache_lock);
558   size_arrays = (size_t)c_avl_size(cache_tree);
559   pthread_mutex_unlock(&cache_lock);
560
561   return size_arrays;
562 }
563
564 int uc_get_names(char ***ret_names, cdtime_t **ret_times, size_t *ret_number) {
565   c_avl_iterator_t *iter;
566   char *key;
567   cache_entry_t *value;
568
569   char **names = NULL;
570   cdtime_t *times = NULL;
571   size_t number = 0;
572   size_t size_arrays = 0;
573
574   int status = 0;
575
576   if ((ret_names == NULL) || (ret_number == NULL))
577     return -1;
578
579   pthread_mutex_lock(&cache_lock);
580
581   size_arrays = (size_t)c_avl_size(cache_tree);
582   if (size_arrays < 1) {
583     /* Handle the "no values" case here, to avoid the error message when
584      * calloc() returns NULL. */
585     pthread_mutex_unlock(&cache_lock);
586     return 0;
587   }
588
589   names = calloc(size_arrays, sizeof(*names));
590   times = calloc(size_arrays, sizeof(*times));
591   if ((names == NULL) || (times == NULL)) {
592     ERROR("uc_get_names: calloc failed.");
593     sfree(names);
594     sfree(times);
595     pthread_mutex_unlock(&cache_lock);
596     return ENOMEM;
597   }
598
599   iter = c_avl_get_iterator(cache_tree);
600   while (c_avl_iterator_next(iter, (void *)&key, (void *)&value) == 0) {
601     /* remove missing values when list values */
602     if (value->state == STATE_MISSING)
603       continue;
604
605     /* c_avl_size does not return a number smaller than the number of elements
606      * returned by c_avl_iterator_next. */
607     assert(number < size_arrays);
608
609     if (ret_times != NULL)
610       times[number] = value->last_time;
611
612     names[number] = strdup(key);
613     if (names[number] == NULL) {
614       status = -1;
615       break;
616     }
617
618     number++;
619   } /* while (c_avl_iterator_next) */
620
621   c_avl_iterator_destroy(iter);
622   pthread_mutex_unlock(&cache_lock);
623
624   if (status != 0) {
625     for (size_t i = 0; i < number; i++) {
626       sfree(names[i]);
627     }
628     sfree(names);
629     sfree(times);
630
631     return -1;
632   }
633
634   *ret_names = names;
635   if (ret_times != NULL)
636     *ret_times = times;
637   else
638     sfree(times);
639   *ret_number = number;
640
641   return 0;
642 } /* int uc_get_names */
643
644 int uc_get_state(const data_set_t *ds, const value_list_t *vl) {
645   char name[6 * DATA_MAX_NAME_LEN];
646   cache_entry_t *ce = NULL;
647   int ret = STATE_ERROR;
648
649   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
650     ERROR("uc_get_state: FORMAT_VL failed.");
651     return STATE_ERROR;
652   }
653
654   pthread_mutex_lock(&cache_lock);
655
656   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
657     assert(ce != NULL);
658     ret = ce->state;
659   }
660
661   pthread_mutex_unlock(&cache_lock);
662
663   return ret;
664 } /* int uc_get_state */
665
666 int uc_set_state(const data_set_t *ds, const value_list_t *vl, int state) {
667   char name[6 * DATA_MAX_NAME_LEN];
668   cache_entry_t *ce = NULL;
669   int ret = -1;
670
671   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
672     ERROR("uc_set_state: FORMAT_VL failed.");
673     return STATE_ERROR;
674   }
675
676   pthread_mutex_lock(&cache_lock);
677
678   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
679     assert(ce != NULL);
680     ret = ce->state;
681     ce->state = state;
682   }
683
684   pthread_mutex_unlock(&cache_lock);
685
686   return ret;
687 } /* int uc_set_state */
688
689 int uc_get_history_by_name(const char *name, gauge_t *ret_history,
690                            size_t num_steps, size_t num_ds) {
691   cache_entry_t *ce = NULL;
692   int status = 0;
693
694   pthread_mutex_lock(&cache_lock);
695
696   status = c_avl_get(cache_tree, name, (void *)&ce);
697   if (status != 0) {
698     pthread_mutex_unlock(&cache_lock);
699     return -ENOENT;
700   }
701
702   if (((size_t)ce->values_num) != num_ds) {
703     pthread_mutex_unlock(&cache_lock);
704     return -EINVAL;
705   }
706
707   /* Check if there are enough values available. If not, increase the buffer
708    * size. */
709   if (ce->history_length < num_steps) {
710     gauge_t *tmp;
711
712     tmp =
713         realloc(ce->history, sizeof(*ce->history) * num_steps * ce->values_num);
714     if (tmp == NULL) {
715       pthread_mutex_unlock(&cache_lock);
716       return -ENOMEM;
717     }
718
719     for (size_t i = ce->history_length * ce->values_num;
720          i < (num_steps * ce->values_num); i++)
721       tmp[i] = NAN;
722
723     ce->history = tmp;
724     ce->history_length = num_steps;
725   } /* if (ce->history_length < num_steps) */
726
727   /* Copy the values to the output buffer. */
728   for (size_t i = 0; i < num_steps; i++) {
729     size_t src_index;
730     size_t dst_index;
731
732     if (i < ce->history_index)
733       src_index = ce->history_index - (i + 1);
734     else
735       src_index = ce->history_length + ce->history_index - (i + 1);
736     src_index = src_index * num_ds;
737
738     dst_index = i * num_ds;
739
740     memcpy(ret_history + dst_index, ce->history + src_index,
741            sizeof(*ret_history) * num_ds);
742   }
743
744   pthread_mutex_unlock(&cache_lock);
745
746   return 0;
747 } /* int uc_get_history_by_name */
748
749 int uc_get_history(const data_set_t *ds, const value_list_t *vl,
750                    gauge_t *ret_history, size_t num_steps, size_t num_ds) {
751   char name[6 * DATA_MAX_NAME_LEN];
752
753   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
754     ERROR("utils_cache: uc_get_history: FORMAT_VL failed.");
755     return -1;
756   }
757
758   return uc_get_history_by_name(name, ret_history, num_steps, num_ds);
759 } /* int uc_get_history */
760
761 int uc_get_hits(const data_set_t *ds, const value_list_t *vl) {
762   char name[6 * DATA_MAX_NAME_LEN];
763   cache_entry_t *ce = NULL;
764   int ret = STATE_ERROR;
765
766   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
767     ERROR("uc_get_hits: FORMAT_VL failed.");
768     return STATE_ERROR;
769   }
770
771   pthread_mutex_lock(&cache_lock);
772
773   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
774     assert(ce != NULL);
775     ret = ce->hits;
776   }
777
778   pthread_mutex_unlock(&cache_lock);
779
780   return ret;
781 } /* int uc_get_hits */
782
783 int uc_set_hits(const data_set_t *ds, const value_list_t *vl, int hits) {
784   char name[6 * DATA_MAX_NAME_LEN];
785   cache_entry_t *ce = NULL;
786   int ret = -1;
787
788   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
789     ERROR("uc_set_hits: FORMAT_VL failed.");
790     return STATE_ERROR;
791   }
792
793   pthread_mutex_lock(&cache_lock);
794
795   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
796     assert(ce != NULL);
797     ret = ce->hits;
798     ce->hits = hits;
799   }
800
801   pthread_mutex_unlock(&cache_lock);
802
803   return ret;
804 } /* int uc_set_hits */
805
806 int uc_inc_hits(const data_set_t *ds, const value_list_t *vl, int step) {
807   char name[6 * DATA_MAX_NAME_LEN];
808   cache_entry_t *ce = NULL;
809   int ret = -1;
810
811   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
812     ERROR("uc_inc_hits: FORMAT_VL failed.");
813     return STATE_ERROR;
814   }
815
816   pthread_mutex_lock(&cache_lock);
817
818   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
819     assert(ce != NULL);
820     ret = ce->hits;
821     ce->hits = ret + step;
822   }
823
824   pthread_mutex_unlock(&cache_lock);
825
826   return ret;
827 } /* int uc_inc_hits */
828
829 /*
830  * Iterator interface
831  */
832 uc_iter_t *uc_get_iterator(void) {
833   uc_iter_t *iter;
834
835   iter = (uc_iter_t *)calloc(1, sizeof(*iter));
836   if (iter == NULL)
837     return NULL;
838
839   pthread_mutex_lock(&cache_lock);
840
841   iter->iter = c_avl_get_iterator(cache_tree);
842   if (iter->iter == NULL) {
843     free(iter);
844     return NULL;
845   }
846
847   return iter;
848 } /* uc_iter_t *uc_get_iterator */
849
850 int uc_iterator_next(uc_iter_t *iter, char **ret_name) {
851   int status;
852
853   if (iter == NULL)
854     return -1;
855
856   while ((status = c_avl_iterator_next(iter->iter, (void *)&iter->name,
857                                        (void *)&iter->entry)) == 0) {
858     if (iter->entry->state == STATE_MISSING)
859       continue;
860
861     break;
862   }
863   if (status != 0) {
864     iter->name = NULL;
865     iter->entry = NULL;
866     return -1;
867   }
868
869   if (ret_name != NULL)
870     *ret_name = iter->name;
871
872   return 0;
873 } /* int uc_iterator_next */
874
875 void uc_iterator_destroy(uc_iter_t *iter) {
876   if (iter == NULL)
877     return;
878
879   c_avl_iterator_destroy(iter->iter);
880   pthread_mutex_unlock(&cache_lock);
881
882   free(iter);
883 } /* void uc_iterator_destroy */
884
885 int uc_iterator_get_time(uc_iter_t *iter, cdtime_t *ret_time) {
886   if ((iter == NULL) || (iter->entry == NULL) || (ret_time == NULL))
887     return -1;
888
889   *ret_time = iter->entry->last_time;
890   return 0;
891 } /* int uc_iterator_get_name */
892
893 int uc_iterator_get_values(uc_iter_t *iter, value_t **ret_values,
894                            size_t *ret_num) {
895   if ((iter == NULL) || (iter->entry == NULL) || (ret_values == NULL) ||
896       (ret_num == NULL))
897     return -1;
898   *ret_values =
899       calloc(iter->entry->values_num, sizeof(*iter->entry->values_raw));
900   if (*ret_values == NULL)
901     return -1;
902   for (size_t i = 0; i < iter->entry->values_num; ++i)
903     (*ret_values)[i] = iter->entry->values_raw[i];
904
905   *ret_num = iter->entry->values_num;
906
907   return 0;
908 } /* int uc_iterator_get_values */
909
910 int uc_iterator_get_interval(uc_iter_t *iter, cdtime_t *ret_interval) {
911   if ((iter == NULL) || (iter->entry == NULL) || (ret_interval == NULL))
912     return -1;
913
914   *ret_interval = iter->entry->interval;
915   return 0;
916 } /* int uc_iterator_get_name */
917
918 int uc_iterator_get_meta(uc_iter_t *iter, meta_data_t **ret_meta) {
919   if ((iter == NULL) || (iter->entry == NULL) || (ret_meta == NULL))
920     return -1;
921
922   *ret_meta = meta_data_clone(iter->entry->meta);
923
924   return 0;
925 } /* int uc_iterator_get_meta */
926
927 /*
928  * Meta data interface
929  */
930 /* XXX: This function will acquire `cache_lock' but will not free it! */
931 static meta_data_t *uc_get_meta(const value_list_t *vl) /* {{{ */
932 {
933   char name[6 * DATA_MAX_NAME_LEN];
934   cache_entry_t *ce = NULL;
935   int status;
936
937   status = FORMAT_VL(name, sizeof(name), vl);
938   if (status != 0) {
939     ERROR("utils_cache: uc_get_meta: FORMAT_VL failed.");
940     return NULL;
941   }
942
943   pthread_mutex_lock(&cache_lock);
944
945   status = c_avl_get(cache_tree, name, (void *)&ce);
946   if (status != 0) {
947     pthread_mutex_unlock(&cache_lock);
948     return NULL;
949   }
950   assert(ce != NULL);
951
952   if (ce->meta == NULL)
953     ce->meta = meta_data_create();
954
955   if (ce->meta == NULL)
956     pthread_mutex_unlock(&cache_lock);
957
958   return ce->meta;
959 } /* }}} meta_data_t *uc_get_meta */
960
961 /* Sorry about this preprocessor magic, but it really makes this file much
962  * shorter.. */
963 #define UC_WRAP(wrap_function)                                                 \
964   {                                                                            \
965     meta_data_t *meta;                                                         \
966     int status;                                                                \
967     meta = uc_get_meta(vl);                                                    \
968     if (meta == NULL)                                                          \
969       return -1;                                                               \
970     status = wrap_function(meta, key);                                         \
971     pthread_mutex_unlock(&cache_lock);                                         \
972     return status;                                                             \
973   }
974 int uc_meta_data_exists(const value_list_t *vl,
975                         const char *key) UC_WRAP(meta_data_exists)
976
977     int uc_meta_data_delete(const value_list_t *vl,
978                             const char *key) UC_WRAP(meta_data_delete)
979 #undef UC_WRAP
980
981 /* We need a new version of this macro because the following functions take
982  * two argumetns. */
983 #define UC_WRAP(wrap_function)                                                 \
984   {                                                                            \
985     meta_data_t *meta;                                                         \
986     int status;                                                                \
987     meta = uc_get_meta(vl);                                                    \
988     if (meta == NULL)                                                          \
989       return -1;                                                               \
990     status = wrap_function(meta, key, value);                                  \
991     pthread_mutex_unlock(&cache_lock);                                         \
992     return status;                                                             \
993   }
994         int uc_meta_data_add_string(const value_list_t *vl, const char *key,
995                                     const char *value)
996             UC_WRAP(meta_data_add_string) int uc_meta_data_add_signed_int(
997                 const value_list_t *vl, const char *key, int64_t value)
998                 UC_WRAP(meta_data_add_signed_int) int uc_meta_data_add_unsigned_int(
999                     const value_list_t *vl, const char *key, uint64_t value)
1000                     UC_WRAP(meta_data_add_unsigned_int) int uc_meta_data_add_double(
1001                         const value_list_t *vl, const char *key, double value)
1002                         UC_WRAP(meta_data_add_double) int uc_meta_data_add_boolean(
1003                             const value_list_t *vl, const char *key,
1004                             _Bool value) UC_WRAP(meta_data_add_boolean)
1005
1006                             int uc_meta_data_get_string(const value_list_t *vl,
1007                                                         const char *key,
1008                                                         char **value)
1009                                 UC_WRAP(meta_data_get_string) int uc_meta_data_get_signed_int(
1010                                     const value_list_t *vl, const char *key,
1011                                     int64_t *value)
1012                                     UC_WRAP(meta_data_get_signed_int) int uc_meta_data_get_unsigned_int(
1013                                         const value_list_t *vl, const char *key,
1014                                         uint64_t *value)
1015                                         UC_WRAP(meta_data_get_unsigned_int) int uc_meta_data_get_double(
1016                                             const value_list_t *vl,
1017                                             const char *key, double *value)
1018                                             UC_WRAP(meta_data_get_double) int uc_meta_data_get_boolean(
1019                                                 const value_list_t *vl,
1020                                                 const char *key, _Bool *value)
1021                                                 UC_WRAP(meta_data_get_boolean)
1022 #undef UC_WRAP