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