Merge branch 'collectd-5.7' into collectd-5.8
[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 (%zu) 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[%zu] = %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 %zu values, "
473           "but uc_get_rate_by_name returned %zu.",
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   }
508   else {
509     DEBUG("utils_cache: uc_get_value_by_name: No such value: %s", name);
510     status = -1;
511   }
512
513   pthread_mutex_unlock(&cache_lock);
514
515   if (status == 0) {
516     *ret_values = ret;
517     *ret_values_num = ret_num;
518   }
519
520   return (status);
521 } /* int uc_get_value_by_name */
522
523 value_t *uc_get_value(const data_set_t *ds, const value_list_t *vl) {
524   char name[6 * DATA_MAX_NAME_LEN];
525   value_t *ret = NULL;
526   size_t ret_num = 0;
527   int status;
528
529   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
530     ERROR("utils_cache: uc_get_value: FORMAT_VL failed.");
531     return (NULL);
532   }
533
534   status = uc_get_value_by_name(name, &ret, &ret_num);
535   if (status != 0)
536     return (NULL);
537
538   /* This is important - the caller has no other way of knowing how many
539    * values are returned. */
540   if (ret_num != (size_t) ds->ds_num) {
541     ERROR("utils_cache: uc_get_value: ds[%s] has %zu values, "
542           "but uc_get_value_by_name returned %zu.", ds->type, ds->ds_num,
543           ret_num);
544     sfree(ret);
545     return (NULL);
546   }
547
548   return (ret);
549 } /* value_t *uc_get_value */
550
551 size_t uc_get_size(void) {
552   size_t size_arrays = 0;
553
554   pthread_mutex_lock(&cache_lock);
555   size_arrays = (size_t)c_avl_size(cache_tree);
556   pthread_mutex_unlock(&cache_lock);
557
558   return size_arrays;
559 }
560
561 int uc_get_names(char ***ret_names, cdtime_t **ret_times, size_t *ret_number) {
562   c_avl_iterator_t *iter;
563   char *key;
564   cache_entry_t *value;
565
566   char **names = NULL;
567   cdtime_t *times = NULL;
568   size_t number = 0;
569   size_t size_arrays = 0;
570
571   int status = 0;
572
573   if ((ret_names == NULL) || (ret_number == NULL))
574     return -1;
575
576   pthread_mutex_lock(&cache_lock);
577
578   size_arrays = (size_t)c_avl_size(cache_tree);
579   if (size_arrays < 1) {
580     /* Handle the "no values" case here, to avoid the error message when
581      * calloc() returns NULL. */
582     pthread_mutex_unlock(&cache_lock);
583     return 0;
584   }
585
586   names = calloc(size_arrays, sizeof(*names));
587   times = calloc(size_arrays, sizeof(*times));
588   if ((names == NULL) || (times == NULL)) {
589     ERROR("uc_get_names: calloc failed.");
590     sfree(names);
591     sfree(times);
592     pthread_mutex_unlock(&cache_lock);
593     return ENOMEM;
594   }
595
596   iter = c_avl_get_iterator(cache_tree);
597   while (c_avl_iterator_next(iter, (void *)&key, (void *)&value) == 0) {
598     /* remove missing values when list values */
599     if (value->state == STATE_MISSING)
600       continue;
601
602     /* c_avl_size does not return a number smaller than the number of elements
603      * returned by c_avl_iterator_next. */
604     assert(number < size_arrays);
605
606     if (ret_times != NULL)
607       times[number] = value->last_time;
608
609     names[number] = strdup(key);
610     if (names[number] == NULL) {
611       status = -1;
612       break;
613     }
614
615     number++;
616   } /* while (c_avl_iterator_next) */
617
618   c_avl_iterator_destroy(iter);
619   pthread_mutex_unlock(&cache_lock);
620
621   if (status != 0) {
622     for (size_t i = 0; i < number; i++) {
623       sfree(names[i]);
624     }
625     sfree(names);
626     sfree(times);
627
628     return -1;
629   }
630
631   *ret_names = names;
632   if (ret_times != NULL)
633     *ret_times = times;
634   else
635     sfree(times);
636   *ret_number = number;
637
638   return 0;
639 } /* int uc_get_names */
640
641 int uc_get_state(const data_set_t *ds, const value_list_t *vl) {
642   char name[6 * DATA_MAX_NAME_LEN];
643   cache_entry_t *ce = NULL;
644   int ret = STATE_ERROR;
645
646   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
647     ERROR("uc_get_state: FORMAT_VL failed.");
648     return STATE_ERROR;
649   }
650
651   pthread_mutex_lock(&cache_lock);
652
653   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
654     assert(ce != NULL);
655     ret = ce->state;
656   }
657
658   pthread_mutex_unlock(&cache_lock);
659
660   return ret;
661 } /* int uc_get_state */
662
663 int uc_set_state(const data_set_t *ds, const value_list_t *vl, int state) {
664   char name[6 * DATA_MAX_NAME_LEN];
665   cache_entry_t *ce = NULL;
666   int ret = -1;
667
668   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
669     ERROR("uc_set_state: FORMAT_VL failed.");
670     return STATE_ERROR;
671   }
672
673   pthread_mutex_lock(&cache_lock);
674
675   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
676     assert(ce != NULL);
677     ret = ce->state;
678     ce->state = state;
679   }
680
681   pthread_mutex_unlock(&cache_lock);
682
683   return ret;
684 } /* int uc_set_state */
685
686 int uc_get_history_by_name(const char *name, gauge_t *ret_history,
687                            size_t num_steps, size_t num_ds) {
688   cache_entry_t *ce = NULL;
689   int status = 0;
690
691   pthread_mutex_lock(&cache_lock);
692
693   status = c_avl_get(cache_tree, name, (void *)&ce);
694   if (status != 0) {
695     pthread_mutex_unlock(&cache_lock);
696     return -ENOENT;
697   }
698
699   if (((size_t)ce->values_num) != num_ds) {
700     pthread_mutex_unlock(&cache_lock);
701     return -EINVAL;
702   }
703
704   /* Check if there are enough values available. If not, increase the buffer
705    * size. */
706   if (ce->history_length < num_steps) {
707     gauge_t *tmp;
708
709     tmp =
710         realloc(ce->history, sizeof(*ce->history) * num_steps * ce->values_num);
711     if (tmp == NULL) {
712       pthread_mutex_unlock(&cache_lock);
713       return -ENOMEM;
714     }
715
716     for (size_t i = ce->history_length * ce->values_num;
717          i < (num_steps * ce->values_num); i++)
718       tmp[i] = NAN;
719
720     ce->history = tmp;
721     ce->history_length = num_steps;
722   } /* if (ce->history_length < num_steps) */
723
724   /* Copy the values to the output buffer. */
725   for (size_t i = 0; i < num_steps; i++) {
726     size_t src_index;
727     size_t dst_index;
728
729     if (i < ce->history_index)
730       src_index = ce->history_index - (i + 1);
731     else
732       src_index = ce->history_length + ce->history_index - (i + 1);
733     src_index = src_index * num_ds;
734
735     dst_index = i * num_ds;
736
737     memcpy(ret_history + dst_index, ce->history + src_index,
738            sizeof(*ret_history) * num_ds);
739   }
740
741   pthread_mutex_unlock(&cache_lock);
742
743   return 0;
744 } /* int uc_get_history_by_name */
745
746 int uc_get_history(const data_set_t *ds, const value_list_t *vl,
747                    gauge_t *ret_history, size_t num_steps, size_t num_ds) {
748   char name[6 * DATA_MAX_NAME_LEN];
749
750   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
751     ERROR("utils_cache: uc_get_history: FORMAT_VL failed.");
752     return -1;
753   }
754
755   return uc_get_history_by_name(name, ret_history, num_steps, num_ds);
756 } /* int uc_get_history */
757
758 int uc_get_hits(const data_set_t *ds, const value_list_t *vl) {
759   char name[6 * DATA_MAX_NAME_LEN];
760   cache_entry_t *ce = NULL;
761   int ret = STATE_ERROR;
762
763   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
764     ERROR("uc_get_hits: FORMAT_VL failed.");
765     return STATE_ERROR;
766   }
767
768   pthread_mutex_lock(&cache_lock);
769
770   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
771     assert(ce != NULL);
772     ret = ce->hits;
773   }
774
775   pthread_mutex_unlock(&cache_lock);
776
777   return ret;
778 } /* int uc_get_hits */
779
780 int uc_set_hits(const data_set_t *ds, const value_list_t *vl, int hits) {
781   char name[6 * DATA_MAX_NAME_LEN];
782   cache_entry_t *ce = NULL;
783   int ret = -1;
784
785   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
786     ERROR("uc_set_hits: FORMAT_VL failed.");
787     return STATE_ERROR;
788   }
789
790   pthread_mutex_lock(&cache_lock);
791
792   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
793     assert(ce != NULL);
794     ret = ce->hits;
795     ce->hits = hits;
796   }
797
798   pthread_mutex_unlock(&cache_lock);
799
800   return ret;
801 } /* int uc_set_hits */
802
803 int uc_inc_hits(const data_set_t *ds, const value_list_t *vl, int step) {
804   char name[6 * DATA_MAX_NAME_LEN];
805   cache_entry_t *ce = NULL;
806   int ret = -1;
807
808   if (FORMAT_VL(name, sizeof(name), vl) != 0) {
809     ERROR("uc_inc_hits: FORMAT_VL failed.");
810     return STATE_ERROR;
811   }
812
813   pthread_mutex_lock(&cache_lock);
814
815   if (c_avl_get(cache_tree, name, (void *)&ce) == 0) {
816     assert(ce != NULL);
817     ret = ce->hits;
818     ce->hits = ret + step;
819   }
820
821   pthread_mutex_unlock(&cache_lock);
822
823   return ret;
824 } /* int uc_inc_hits */
825
826 /*
827  * Iterator interface
828  */
829 uc_iter_t *uc_get_iterator(void) {
830   uc_iter_t *iter;
831
832   iter = (uc_iter_t *)calloc(1, sizeof(*iter));
833   if (iter == NULL)
834     return NULL;
835
836   pthread_mutex_lock(&cache_lock);
837
838   iter->iter = c_avl_get_iterator(cache_tree);
839   if (iter->iter == NULL) {
840     free(iter);
841     return NULL;
842   }
843
844   return iter;
845 } /* uc_iter_t *uc_get_iterator */
846
847 int uc_iterator_next(uc_iter_t *iter, char **ret_name) {
848   int status;
849
850   if (iter == NULL)
851     return -1;
852
853   while ((status = c_avl_iterator_next(iter->iter, (void *)&iter->name,
854                                        (void *)&iter->entry)) == 0) {
855     if (iter->entry->state == STATE_MISSING)
856       continue;
857
858     break;
859   }
860   if (status != 0) {
861     iter->name = NULL;
862     iter->entry = NULL;
863     return -1;
864   }
865
866   if (ret_name != NULL)
867     *ret_name = iter->name;
868
869   return 0;
870 } /* int uc_iterator_next */
871
872 void uc_iterator_destroy(uc_iter_t *iter) {
873   if (iter == NULL)
874     return;
875
876   c_avl_iterator_destroy(iter->iter);
877   pthread_mutex_unlock(&cache_lock);
878
879   free(iter);
880 } /* void uc_iterator_destroy */
881
882 int uc_iterator_get_time(uc_iter_t *iter, cdtime_t *ret_time) {
883   if ((iter == NULL) || (iter->entry == NULL) || (ret_time == NULL))
884     return -1;
885
886   *ret_time = iter->entry->last_time;
887   return 0;
888 } /* int uc_iterator_get_name */
889
890 int uc_iterator_get_values(uc_iter_t *iter, value_t **ret_values,
891                            size_t *ret_num) {
892   if ((iter == NULL) || (iter->entry == NULL) || (ret_values == NULL) ||
893       (ret_num == NULL))
894     return -1;
895
896   *ret_values =
897       calloc(iter->entry->values_num, sizeof(*iter->entry->values_raw));
898   if (*ret_values == NULL)
899     return -1;
900   for (size_t i = 0; i < iter->entry->values_num; ++i)
901     *ret_values[i] = iter->entry->values_raw[i];
902
903   *ret_num = iter->entry->values_num;
904
905   return 0;
906 } /* int uc_iterator_get_values */
907
908 int uc_iterator_get_interval(uc_iter_t *iter, cdtime_t *ret_interval) {
909   if ((iter == NULL) || (iter->entry == NULL) || (ret_interval == NULL))
910     return -1;
911
912   *ret_interval = iter->entry->interval;
913   return 0;
914 } /* int uc_iterator_get_name */
915
916 int uc_iterator_get_meta(uc_iter_t *iter, meta_data_t **ret_meta) {
917   if ((iter == NULL) || (iter->entry == NULL) || (ret_meta == NULL))
918     return -1;
919
920   *ret_meta = meta_data_clone(iter->entry->meta);
921
922   return 0;
923 } /* int uc_iterator_get_meta */
924
925 /*
926  * Meta data interface
927  */
928 /* XXX: This function will acquire `cache_lock' but will not free it! */
929 static meta_data_t *uc_get_meta(const value_list_t *vl) /* {{{ */
930 {
931   char name[6 * DATA_MAX_NAME_LEN];
932   cache_entry_t *ce = NULL;
933   int status;
934
935   status = FORMAT_VL(name, sizeof(name), vl);
936   if (status != 0) {
937     ERROR("utils_cache: uc_get_meta: FORMAT_VL failed.");
938     return NULL;
939   }
940
941   pthread_mutex_lock(&cache_lock);
942
943   status = c_avl_get(cache_tree, name, (void *)&ce);
944   if (status != 0) {
945     pthread_mutex_unlock(&cache_lock);
946     return NULL;
947   }
948   assert(ce != NULL);
949
950   if (ce->meta == NULL)
951     ce->meta = meta_data_create();
952
953   if (ce->meta == NULL)
954     pthread_mutex_unlock(&cache_lock);
955
956   return ce->meta;
957 } /* }}} meta_data_t *uc_get_meta */
958
959 /* Sorry about this preprocessor magic, but it really makes this file much
960  * shorter.. */
961 #define UC_WRAP(wrap_function)                                                 \
962   {                                                                            \
963     meta_data_t *meta;                                                         \
964     int status;                                                                \
965     meta = uc_get_meta(vl);                                                    \
966     if (meta == NULL)                                                          \
967       return -1;                                                               \
968     status = wrap_function(meta, key);                                         \
969     pthread_mutex_unlock(&cache_lock);                                         \
970     return status;                                                             \
971   }
972 int uc_meta_data_exists(const value_list_t *vl,
973                         const char *key) UC_WRAP(meta_data_exists)
974
975     int uc_meta_data_delete(const value_list_t *vl,
976                             const char *key) UC_WRAP(meta_data_delete)
977 #undef UC_WRAP
978
979 /* We need a new version of this macro because the following functions take
980  * two argumetns. */
981 #define UC_WRAP(wrap_function)                                                 \
982   {                                                                            \
983     meta_data_t *meta;                                                         \
984     int status;                                                                \
985     meta = uc_get_meta(vl);                                                    \
986     if (meta == NULL)                                                          \
987       return -1;                                                               \
988     status = wrap_function(meta, key, value);                                  \
989     pthread_mutex_unlock(&cache_lock);                                         \
990     return status;                                                             \
991   }
992         int uc_meta_data_add_string(const value_list_t *vl, const char *key,
993                                     const char *value)
994             UC_WRAP(meta_data_add_string) int uc_meta_data_add_signed_int(
995                 const value_list_t *vl, const char *key, int64_t value)
996                 UC_WRAP(meta_data_add_signed_int) int uc_meta_data_add_unsigned_int(
997                     const value_list_t *vl, const char *key, uint64_t value)
998                     UC_WRAP(meta_data_add_unsigned_int) int uc_meta_data_add_double(
999                         const value_list_t *vl, const char *key, double value)
1000                         UC_WRAP(meta_data_add_double) int uc_meta_data_add_boolean(
1001                             const value_list_t *vl, const char *key,
1002                             _Bool value) UC_WRAP(meta_data_add_boolean)
1003
1004                             int uc_meta_data_get_string(const value_list_t *vl,
1005                                                         const char *key,
1006                                                         char **value)
1007                                 UC_WRAP(meta_data_get_string) int uc_meta_data_get_signed_int(
1008                                     const value_list_t *vl, const char *key,
1009                                     int64_t *value)
1010                                     UC_WRAP(meta_data_get_signed_int) int uc_meta_data_get_unsigned_int(
1011                                         const value_list_t *vl, const char *key,
1012                                         uint64_t *value)
1013                                         UC_WRAP(meta_data_get_unsigned_int) int uc_meta_data_get_double(
1014                                             const value_list_t *vl,
1015                                             const char *key, double *value)
1016                                             UC_WRAP(meta_data_get_double) int uc_meta_data_get_boolean(
1017                                                 const value_list_t *vl,
1018                                                 const char *key, _Bool *value)
1019                                                 UC_WRAP(meta_data_get_boolean)
1020 #undef UC_WRAP