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