Code

store: Do not canonicalize the hostname when fetching a timeseries.
[sysdb.git] / src / core / store.c
1 /*
2  * SysDB - src/core/store.c
3  * Copyright (C) 2012-2013 Sebastian 'tokkee' Harl <sh@tokkee.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
17  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
28 #if HAVE_CONFIG_H
29 #       include "config.h"
30 #endif /* HAVE_CONFIG_H */
32 #include "sysdb.h"
33 #include "core/store-private.h"
34 #include "core/plugin.h"
35 #include "utils/avltree.h"
36 #include "utils/error.h"
38 #include <assert.h>
40 #include <errno.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
46 #include <math.h>
47 #include <pthread.h>
49 /*
50  * private variables
51  */
53 struct sdb_store {
54         sdb_object_t super;
56         /* hosts are the top-level entries and
57          * reference everything else */
58         sdb_avltree_t *hosts;
59         pthread_rwlock_t host_lock;
60 };
62 /*
63  * private types
64  */
66 static sdb_type_t host_type;
67 static sdb_type_t service_type;
68 static sdb_type_t metric_type;
69 static sdb_type_t attribute_type;
71 static int
72 store_init(sdb_object_t *obj, va_list __attribute__((unused)) ap)
73 {
74         int err;
75         if (! (SDB_STORE(obj)->hosts = sdb_avltree_create()))
76                 return -1;
77         if ((err = pthread_rwlock_init(&SDB_STORE(obj)->host_lock,
78                                         /* attr = */ NULL))) {
79                 char errbuf[128];
80                 sdb_log(SDB_LOG_ERR, "store: Failed to initialize lock: %s",
81                                 sdb_strerror(err, errbuf, sizeof(errbuf)));
82                 return -1;
83         }
84         return 0;
85 } /* store_init */
87 static void
88 store_destroy(sdb_object_t *obj)
89 {
90         int err;
91         if ((err = pthread_rwlock_destroy(&SDB_STORE(obj)->host_lock))) {
92                 char errbuf[128];
93                 sdb_log(SDB_LOG_ERR, "store: Failed to destroy lock: %s",
94                                 sdb_strerror(err, errbuf, sizeof(errbuf)));
95                 return;
96         }
97         sdb_avltree_destroy(SDB_STORE(obj)->hosts);
98         SDB_STORE(obj)->hosts = NULL;
99 } /* store_destroy */
101 static int
102 store_obj_init(sdb_object_t *obj, va_list ap)
104         sdb_store_obj_t *sobj = STORE_OBJ(obj);
106         sobj->type = va_arg(ap, int);
108         sobj->last_update = va_arg(ap, sdb_time_t);
109         sobj->interval = 0;
110         sobj->backends = NULL;
111         sobj->backends_num = 0;
112         sobj->parent = NULL;
113         return 0;
114 } /* store_obj_init */
116 static void
117 store_obj_destroy(sdb_object_t *obj)
119         sdb_store_obj_t *sobj = STORE_OBJ(obj);
120         size_t i;
122         for (i = 0; i < sobj->backends_num; ++i)
123                 free(sobj->backends[i]);
124         free(sobj->backends);
125         sobj->backends = NULL;
126         sobj->backends_num = 0;
128         // We don't currently keep an extra reference for parent objects to
129         // avoid circular self-references which are not handled correctly by
130         // the ref-count base management layer.
131         //sdb_object_deref(SDB_OBJ(sobj->parent));
132 } /* store_obj_destroy */
134 static int
135 host_init(sdb_object_t *obj, va_list ap)
137         sdb_host_t *sobj = HOST(obj);
138         int ret;
140         /* this will consume the first argument (type) of ap */
141         ret = store_obj_init(obj, ap);
142         if (ret)
143                 return ret;
145         sobj->services = sdb_avltree_create();
146         if (! sobj->services)
147                 return -1;
148         sobj->metrics = sdb_avltree_create();
149         if (! sobj->metrics)
150                 return -1;
151         sobj->attributes = sdb_avltree_create();
152         if (! sobj->attributes)
153                 return -1;
154         return 0;
155 } /* host_init */
157 static void
158 host_destroy(sdb_object_t *obj)
160         sdb_host_t *sobj = HOST(obj);
161         assert(obj);
163         store_obj_destroy(obj);
165         if (sobj->services)
166                 sdb_avltree_destroy(sobj->services);
167         if (sobj->metrics)
168                 sdb_avltree_destroy(sobj->metrics);
169         if (sobj->attributes)
170                 sdb_avltree_destroy(sobj->attributes);
171 } /* host_destroy */
173 static int
174 service_init(sdb_object_t *obj, va_list ap)
176         sdb_service_t *sobj = SVC(obj);
177         int ret;
179         /* this will consume the first argument (type) of ap */
180         ret = store_obj_init(obj, ap);
181         if (ret)
182                 return ret;
184         sobj->attributes = sdb_avltree_create();
185         if (! sobj->attributes)
186                 return -1;
187         return 0;
188 } /* service_init */
190 static void
191 service_destroy(sdb_object_t *obj)
193         sdb_service_t *sobj = SVC(obj);
194         assert(obj);
196         store_obj_destroy(obj);
198         if (sobj->attributes)
199                 sdb_avltree_destroy(sobj->attributes);
200 } /* service_destroy */
202 static int
203 metric_init(sdb_object_t *obj, va_list ap)
205         sdb_metric_t *sobj = METRIC(obj);
206         int ret;
208         /* this will consume the first argument (type) of ap */
209         ret = store_obj_init(obj, ap);
210         if (ret)
211                 return ret;
213         sobj->attributes = sdb_avltree_create();
214         if (! sobj->attributes)
215                 return -1;
217         sobj->store.type = sobj->store.id = NULL;
218         return 0;
219 } /* metric_init */
221 static void
222 metric_destroy(sdb_object_t *obj)
224         sdb_metric_t *sobj = METRIC(obj);
225         assert(obj);
227         store_obj_destroy(obj);
229         if (sobj->attributes)
230                 sdb_avltree_destroy(sobj->attributes);
232         if (sobj->store.type)
233                 free(sobj->store.type);
234         if (sobj->store.id)
235                 free(sobj->store.id);
236 } /* metric_destroy */
238 static int
239 attr_init(sdb_object_t *obj, va_list ap)
241         const sdb_data_t *value;
242         int ret;
244         /* this will consume the first two arguments
245          * (type and last_update) of ap */
246         ret = store_obj_init(obj, ap);
247         if (ret)
248                 return ret;
249         value = va_arg(ap, const sdb_data_t *);
251         if (value)
252                 if (sdb_data_copy(&ATTR(obj)->value, value))
253                         return -1;
254         return 0;
255 } /* attr_init */
257 static void
258 attr_destroy(sdb_object_t *obj)
260         assert(obj);
262         store_obj_destroy(obj);
263         sdb_data_free_datum(&ATTR(obj)->value);
264 } /* attr_destroy */
266 static sdb_type_t store_type = {
267         /* size = */ sizeof(sdb_store_t),
268         /* init = */ store_init,
269         /* destroy = */ store_destroy,
270 };
272 static sdb_type_t host_type = {
273         /* size = */ sizeof(sdb_host_t),
274         /* init = */ host_init,
275         /* destroy = */ host_destroy
276 };
278 static sdb_type_t service_type = {
279         /* size = */ sizeof(sdb_service_t),
280         /* init = */ service_init,
281         /* destroy = */ service_destroy
282 };
284 static sdb_type_t metric_type = {
285         /* size = */ sizeof(sdb_metric_t),
286         /* init = */ metric_init,
287         /* destroy = */ metric_destroy
288 };
290 static sdb_type_t attribute_type = {
291         /* size = */ sizeof(sdb_attribute_t),
292         /* init = */ attr_init,
293         /* destroy = */ attr_destroy
294 };
296 /*
297  * private helper functions
298  */
300 static int
301 record_backend(sdb_store_obj_t *obj)
303         const sdb_plugin_info_t *info;
304         char **tmp;
305         size_t i;
307         info = sdb_plugin_current();
308         if (! info)
309                 return 0;
311         for (i = 0; i < obj->backends_num; ++i)
312                 if (!strcasecmp(obj->backends[i], info->plugin_name))
313                         return 0;
315         tmp = realloc(obj->backends,
316                         (obj->backends_num + 1) * sizeof(*obj->backends));
317         if (! tmp)
318                 return -1;
320         obj->backends = tmp;
321         obj->backends[obj->backends_num] = strdup(info->plugin_name);
322         if (! obj->backends[obj->backends_num])
323                 return -1;
325         ++obj->backends_num;
326         return 0;
327 } /* record_backend */
329 static int
330 store_obj(sdb_store_obj_t *parent, sdb_avltree_t *parent_tree,
331                 int type, const char *name, sdb_time_t last_update,
332                 sdb_store_obj_t **updated_obj)
334         sdb_store_obj_t *old, *new;
335         int status = 0;
337         assert(parent_tree);
339         if (last_update <= 0)
340                 last_update = sdb_gettime();
342         old = STORE_OBJ(sdb_avltree_lookup(parent_tree, name));
343         if (old) {
344                 if (old->last_update > last_update) {
345                         sdb_log(SDB_LOG_DEBUG, "store: Cannot update %s '%s' - "
346                                         "value too old (%"PRIsdbTIME" < %"PRIsdbTIME")",
347                                         SDB_STORE_TYPE_TO_NAME(type), name,
348                                         last_update, old->last_update);
349                         /* don't report an error; the object may be updated by multiple
350                          * backends */
351                         status = 1;
352                 }
353                 else if (old->last_update == last_update) {
354                         /* don't report an error and also don't even log this to avoid
355                          * excessive noise on high sampling frequencies */
356                         status = 1;
357                 }
358                 else {
359                         sdb_time_t interval = last_update - old->last_update;
360                         old->last_update = last_update;
361                         if (interval) {
362                                 if (old->interval)
363                                         old->interval = (sdb_time_t)((0.9 * (double)old->interval)
364                                                         + (0.1 * (double)interval));
365                                 else
366                                         old->interval = interval;
367                         }
368                 }
370                 new = old;
371                 sdb_object_deref(SDB_OBJ(old));
372         }
373         else {
374                 if (type == SDB_ATTRIBUTE) {
375                         /* the value will be updated by the caller */
376                         new = STORE_OBJ(sdb_object_create(name, attribute_type,
377                                                 type, last_update, NULL));
378                 }
379                 else {
380                         sdb_type_t t;
381                         t = type == SDB_HOST
382                                 ? host_type
383                                 : type == SDB_SERVICE
384                                         ? service_type
385                                         : metric_type;
386                         new = STORE_OBJ(sdb_object_create(name, t, type, last_update));
387                 }
389                 if (new) {
390                         status = sdb_avltree_insert(parent_tree, SDB_OBJ(new));
392                         /* pass control to the tree or destroy in case of an error */
393                         sdb_object_deref(SDB_OBJ(new));
394                 }
395                 else {
396                         char errbuf[1024];
397                         sdb_log(SDB_LOG_ERR, "store: Failed to create %s '%s': %s",
398                                         SDB_STORE_TYPE_TO_NAME(type), name,
399                                         sdb_strerror(errno, errbuf, sizeof(errbuf)));
400                         status = -1;
401                 }
402         }
404         if (status < 0)
405                 return status;
406         assert(new);
408         if (new->parent != parent) {
409                 // Avoid circular self-references which are not handled
410                 // correctly by the ref-count based management layer.
411                 //sdb_object_deref(SDB_OBJ(new->parent));
412                 //sdb_object_ref(SDB_OBJ(parent));
413                 new->parent = parent;
414         }
416         if (updated_obj)
417                 *updated_obj = new;
419         if (record_backend(new))
420                 return -1;
421         return status;
422 } /* store_obj */
424 static int
425 store_attr(sdb_store_obj_t *parent, sdb_avltree_t *attributes,
426                 const char *key, const sdb_data_t *value, sdb_time_t last_update)
428         sdb_store_obj_t *attr = NULL;
429         int status;
431         status = store_obj(parent, attributes, SDB_ATTRIBUTE,
432                         key, last_update, &attr);
433         if (status)
434                 return status;
436         /* don't update unchanged values */
437         if (! sdb_data_cmp(&ATTR(attr)->value, value))
438                 return status;
440         assert(attr);
441         if (sdb_data_copy(&ATTR(attr)->value, value))
442                 return -1;
443         return status;
444 } /* store_attr */
446 static int
447 store_metric_store(sdb_metric_t *metric, sdb_metric_store_t *store)
449         char *type = metric->store.type;
450         char *id = metric->store.id;
452         if ((! metric->store.type) || strcasecmp(metric->store.type, store->type)) {
453                 if (! (type = strdup(store->type)))
454                         return -1;
455         }
456         if ((! metric->store.id) || strcasecmp(metric->store.id, store->id)) {
457                 if (! (id = strdup(store->id))) {
458                         if (type != metric->store.type)
459                                 free(type);
460                         return -1;
461                 }
462         }
464         if (type != metric->store.type) {
465                 if (metric->store.type)
466                         free(metric->store.type);
467                 metric->store.type = type;
468         }
469         if (id != metric->store.id) {
470                 if (metric->store.id)
471                         free(metric->store.id);
472                 metric->store.id = id;
473         }
474         return 0;
475 } /* store_metric_store */
477 /* The store's host_lock has to be acquired before calling this function. */
478 static sdb_avltree_t *
479 get_host_children(sdb_host_t *host, int type)
481         if ((type != SDB_SERVICE) && (type != SDB_METRIC)
482                         && (type != SDB_ATTRIBUTE))
483                 return NULL;
485         if (! host)
486                 return NULL;
488         if (type == SDB_ATTRIBUTE)
489                 return host->attributes;
490         else if (type == SDB_METRIC)
491                 return host->metrics;
492         else
493                 return host->services;
494 } /* get_host_children */
496 /*
497  * ts_tojson serializes a time-series to JSON.
498  *
499  * The function never returns an error. Rather, an error message will be part
500  * of the serialized data.
501  */
502 static void
503 ts_tojson(sdb_timeseries_t *ts, sdb_strbuf_t *buf)
505         char start_str[64];
506         char end_str[64];
508         size_t i;
510         /* TODO: make time format configurable */
511         if (! sdb_strftime(start_str, sizeof(start_str), ts->start))
512                 snprintf(start_str, sizeof(start_str), "<error>");
513         start_str[sizeof(start_str) - 1] = '\0';
514         if (! sdb_strftime(end_str, sizeof(end_str), ts->end))
515                 snprintf(end_str, sizeof(end_str), "<error>");
516         end_str[sizeof(end_str) - 1] = '\0';
518         sdb_strbuf_append(buf, "{\"start\": \"%s\", \"end\": \"%s\", \"data\": {",
519                         start_str, end_str);
521         for (i = 0; i < ts->data_names_len; ++i) {
522                 size_t j;
523                 sdb_strbuf_append(buf, "\"%s\": [", ts->data_names[i]);
525                 for (j = 0; j < ts->data_len; ++j) {
526                         char time_str[64];
528                         if (! sdb_strftime(time_str, sizeof(time_str), ts->data[i][j].timestamp))
529                                 snprintf(time_str, sizeof(time_str), "<error>");
530                         time_str[sizeof(time_str) - 1] = '\0';
532                         /* Some GNU libc versions may print '-nan' which we dont' want */
533                         if (isnan(ts->data[i][j].value))
534                                 sdb_strbuf_append(buf, "{\"timestamp\": \"%s\", "
535                                                 "\"value\": \"nan\"}", time_str);
536                         else
537                                 sdb_strbuf_append(buf, "{\"timestamp\": \"%s\", "
538                                                 "\"value\": \"%f\"}", time_str, ts->data[i][j].value);
540                         if (j < ts->data_len - 1)
541                                 sdb_strbuf_append(buf, ",");
542                 }
544                 if (i < ts->data_names_len - 1)
545                         sdb_strbuf_append(buf, "],");
546                 else
547                         sdb_strbuf_append(buf, "]");
548         }
549         sdb_strbuf_append(buf, "}}");
550 } /* ts_tojson */
552 /*
553  * store writer API
554  */
556 static int
557 store_attribute(const char *hostname,
558                 const char *key, const sdb_data_t *value,
559                 sdb_time_t last_update, sdb_object_t *user_data)
561         sdb_store_t *st = SDB_STORE(user_data);
563         sdb_host_t *host;
564         sdb_avltree_t *attrs;
565         int status = 0;
567         if ((! hostname) || (! key))
568                 return -1;
570         pthread_rwlock_wrlock(&st->host_lock);
571         host = HOST(sdb_avltree_lookup(st->hosts, hostname));
572         attrs = get_host_children(host, SDB_ATTRIBUTE);
573         if (! attrs) {
574                 sdb_log(SDB_LOG_ERR, "store: Failed to store attribute '%s' - "
575                                 "host '%s' not found", key, hostname);
576                 status = -1;
577         }
579         if (! status)
580                 status = store_attr(STORE_OBJ(host), attrs, key, value, last_update);
582         sdb_object_deref(SDB_OBJ(host));
583         pthread_rwlock_unlock(&st->host_lock);
585         return status;
586 } /* store_attribute */
588 static int
589 store_host(const char *name, sdb_time_t last_update, sdb_object_t *user_data)
591         sdb_store_t *st = SDB_STORE(user_data);
592         int status = 0;
594         if (! name)
595                 return -1;
597         pthread_rwlock_wrlock(&st->host_lock);
598         status = store_obj(NULL, st->hosts,
599                         SDB_HOST, name, last_update, NULL);
600         pthread_rwlock_unlock(&st->host_lock);
602         return status;
603 } /* store_host */
605 static int
606 store_service_attr(const char *hostname, const char *service,
607                 const char *key, const sdb_data_t *value, sdb_time_t last_update,
608                 sdb_object_t *user_data)
610         sdb_store_t *st = SDB_STORE(user_data);
612         sdb_host_t *host;
613         sdb_service_t *svc;
614         sdb_avltree_t *services;
615         int status = 0;
617         if ((! hostname) || (! service) || (! key))
618                 return -1;
620         pthread_rwlock_wrlock(&st->host_lock);
621         host = HOST(sdb_avltree_lookup(st->hosts, hostname));
622         services = get_host_children(host, SDB_SERVICE);
623         sdb_object_deref(SDB_OBJ(host));
624         if (! services) {
625                 sdb_log(SDB_LOG_ERR, "store: Failed to store attribute '%s' "
626                                 "for service '%s' - host '%ss' not found",
627                                 key, service, hostname);
628                 pthread_rwlock_unlock(&st->host_lock);
629                 return -1;
630         }
632         svc = SVC(sdb_avltree_lookup(services, service));
633         if (! svc) {
634                 sdb_log(SDB_LOG_ERR, "store: Failed to store attribute '%s' - "
635                                 "service '%s/%s' not found", key, hostname, service);
636                 status = -1;
637         }
639         if (! status)
640                 status = store_attr(STORE_OBJ(svc), svc->attributes,
641                                 key, value, last_update);
643         sdb_object_deref(SDB_OBJ(svc));
644         pthread_rwlock_unlock(&st->host_lock);
646         return status;
647 } /* store_service_attr */
649 static int
650 store_service(const char *hostname, const char *name,
651                 sdb_time_t last_update, sdb_object_t *user_data)
653         sdb_store_t *st = SDB_STORE(user_data);
655         sdb_host_t *host;
656         sdb_avltree_t *services;
657         sdb_data_t d;
659         int status = 0;
661         if ((! hostname) || (! name))
662                 return -1;
664         pthread_rwlock_wrlock(&st->host_lock);
665         host = HOST(sdb_avltree_lookup(st->hosts, hostname));
666         services = get_host_children(host, SDB_SERVICE);
667         if (! services) {
668                 sdb_log(SDB_LOG_ERR, "store: Failed to store service '%s' - "
669                                 "host '%s' not found", name, hostname);
670                 status = -1;
671         }
673         if (! status)
674                 status = store_obj(STORE_OBJ(host), services, SDB_SERVICE,
675                                 name, last_update, NULL);
677         sdb_object_deref(SDB_OBJ(host));
678         pthread_rwlock_unlock(&st->host_lock);
680         if (status)
681                 return status;
683         /* record the hostname as an attribute */
684         d.type = SDB_TYPE_STRING;
685         d.data.string = SDB_OBJ(host)->name;
686         if (store_service_attr(hostname, name, "hostname", &d, last_update, user_data))
687                 status = -1;
688         return status;
689 } /* store_service */
691 static int
692 store_metric_attr(const char *hostname, const char *metric,
693                 const char *key, const sdb_data_t *value, sdb_time_t last_update,
694                 sdb_object_t *user_data)
696         sdb_store_t *st = SDB_STORE(user_data);
698         sdb_avltree_t *metrics;
699         sdb_host_t *host;
700         sdb_metric_t *m;
701         int status = 0;
703         if ((! hostname) || (! metric) || (! key))
704                 return -1;
706         pthread_rwlock_wrlock(&st->host_lock);
707         host = HOST(sdb_avltree_lookup(st->hosts, hostname));
708         metrics = get_host_children(host, SDB_METRIC);
709         sdb_object_deref(SDB_OBJ(host));
710         if (! metrics) {
711                 sdb_log(SDB_LOG_ERR, "store: Failed to store attribute '%s' "
712                                 "for metric '%s' - host '%s' not found",
713                                 key, metric, hostname);
714                 pthread_rwlock_unlock(&st->host_lock);
715                 return -1;
716         }
718         m = METRIC(sdb_avltree_lookup(metrics, metric));
719         if (! m) {
720                 sdb_log(SDB_LOG_ERR, "store: Failed to store attribute '%s' - "
721                                 "metric '%s/%s' not found", key, hostname, metric);
722                 status = -1;
723         }
725         if (! status)
726                 status = store_attr(STORE_OBJ(m), m->attributes,
727                                 key, value, last_update);
729         sdb_object_deref(SDB_OBJ(m));
730         pthread_rwlock_unlock(&st->host_lock);
732         return status;
733 } /* store_metric_attr */
735 static int
736 store_metric(const char *hostname, const char *name,
737                 sdb_metric_store_t *store, sdb_time_t last_update,
738                 sdb_object_t *user_data)
740         sdb_store_t *st = SDB_STORE(user_data);
742         sdb_store_obj_t *obj = NULL;
743         sdb_host_t *host;
744         sdb_metric_t *metric;
745         sdb_data_t d;
747         sdb_avltree_t *metrics;
749         int status = 0;
751         if ((! hostname) || (! name))
752                 return -1;
754         if (store) {
755                 if ((store->type != NULL) != (store->id != NULL))
756                         return -1;
757                 else if (! store->type)
758                         store = NULL;
759         }
761         pthread_rwlock_wrlock(&st->host_lock);
762         host = HOST(sdb_avltree_lookup(st->hosts, hostname));
763         metrics = get_host_children(host, SDB_METRIC);
764         if (! metrics) {
765                 sdb_log(SDB_LOG_ERR, "store: Failed to store metric '%s' - "
766                                 "host '%s' not found", name, hostname);
767                 status = -1;
768         }
770         if (! status)
771                 status = store_obj(STORE_OBJ(host), metrics, SDB_METRIC,
772                                 name, last_update, &obj);
773         sdb_object_deref(SDB_OBJ(host));
775         if (status) {
776                 pthread_rwlock_unlock(&st->host_lock);
777                 return status;
778         }
780         assert(obj);
781         metric = METRIC(obj);
783         if (store)
784                 if (store_metric_store(metric, store))
785                         status = -1;
786         pthread_rwlock_unlock(&st->host_lock);
788         /* record the hostname as an attribute */
789         d.type = SDB_TYPE_STRING;
790         d.data.string = SDB_OBJ(host)->name;
791         if (store_metric_attr(hostname, name, "hostname", &d, last_update, user_data))
792                 status = -1;
793         return status;
794 } /* store_metric */
796 sdb_store_writer_t sdb_store_writer = {
797         store_host, store_service, store_metric,
798         store_attribute, store_service_attr, store_metric_attr,
799 };
801 static sdb_object_t *
802 prepare_query(sdb_ast_node_t *ast,
803                 sdb_strbuf_t __attribute__((unused)) *errbuf,
804                 sdb_object_t __attribute__((unused)) *user_data)
806         return SDB_OBJ(sdb_store_query_prepare(ast));
807 } /* prepare_query */
809 static int
810 execute_query(sdb_object_t *q,
811                 sdb_strbuf_t *buf, sdb_strbuf_t *errbuf,
812                 sdb_object_t *user_data)
814         return sdb_store_query_execute(SDB_STORE(user_data),
815                         QUERY(q), buf, errbuf);
816 } /* execute_query */
818 sdb_store_reader_t sdb_store_reader = {
819         prepare_query, execute_query,
820 };
822 /*
823  * public API
824  */
826 sdb_store_t *
827 sdb_store_create(void)
829         return SDB_STORE(sdb_object_create("store", store_type));
830 } /* sdb_store_create */
832 int
833 sdb_store_host(sdb_store_t *store, const char *name, sdb_time_t last_update)
835         return store_host(name, last_update, SDB_OBJ(store));
836 } /* sdb_store_host */
838 int
839 sdb_store_service(sdb_store_t *store, const char *hostname, const char *name,
840                 sdb_time_t last_update)
842         return store_service(hostname, name, last_update, SDB_OBJ(store));
843 } /* sdb_store_service */
845 int
846 sdb_store_metric(sdb_store_t *store, const char *hostname, const char *name,
847                 sdb_metric_store_t *metric_store, sdb_time_t last_update)
849         return store_metric(hostname, name, metric_store, last_update, SDB_OBJ(store));
850 } /* sdb_store_metric */
852 int
853 sdb_store_attribute(sdb_store_t *store, const char *hostname,
854                 const char *key, const sdb_data_t *value, sdb_time_t last_update)
856         return store_attribute(hostname, key, value, last_update, SDB_OBJ(store));
857 } /* sdb_store_attribute */
859 int
860 sdb_store_service_attr(sdb_store_t *store, const char *hostname,
861                 const char *service, const char *key, const sdb_data_t *value,
862                 sdb_time_t last_update)
864         return store_service_attr(hostname, service, key, value,
865                         last_update, SDB_OBJ(store));
866 } /* sdb_store_service_attr */
868 int
869 sdb_store_metric_attr(sdb_store_t *store, const char *hostname,
870                 const char *metric, const char *key, const sdb_data_t *value,
871                 sdb_time_t last_update)
873         return store_metric_attr(hostname, metric, key, value,
874                         last_update, SDB_OBJ(store));
875 } /* sdb_store_metric_attr */
877 sdb_store_obj_t *
878 sdb_store_get_host(sdb_store_t *store, const char *name)
880         sdb_host_t *host;
882         if ((! store) || (! name))
883                 return NULL;
885         host = HOST(sdb_avltree_lookup(store->hosts, name));
886         if (! host)
887                 return NULL;
889         return STORE_OBJ(host);
890 } /* sdb_store_get_host */
892 sdb_store_obj_t *
893 sdb_store_get_child(sdb_store_obj_t *host, int type, const char *name)
895         sdb_avltree_t *children;
897         if ((! host) || (host->type != SDB_HOST) || (! name))
898                 return NULL;
900         children = get_host_children(HOST(host), type);
901         if (! children)
902                 return NULL;
903         return STORE_OBJ(sdb_avltree_lookup(children, name));
904 } /* sdb_store_get_child */
906 int
907 sdb_store_get_field(sdb_store_obj_t *obj, int field, sdb_data_t *res)
909         sdb_data_t tmp;
911         if (! obj)
912                 return -1;
914         switch (field) {
915                 case SDB_FIELD_NAME:
916                         tmp.type = SDB_TYPE_STRING;
917                         tmp.data.string = strdup(SDB_OBJ(obj)->name);
918                         if (! tmp.data.string)
919                                 return -1;
920                         break;
921                 case SDB_FIELD_LAST_UPDATE:
922                         tmp.type = SDB_TYPE_DATETIME;
923                         tmp.data.datetime = obj->last_update;
924                         break;
925                 case SDB_FIELD_AGE:
926                         tmp.type = SDB_TYPE_DATETIME;
927                         tmp.data.datetime = sdb_gettime() - obj->last_update;
928                         break;
929                 case SDB_FIELD_INTERVAL:
930                         tmp.type = SDB_TYPE_DATETIME;
931                         tmp.data.datetime = obj->interval;
932                         break;
933                 case SDB_FIELD_BACKEND:
934                         if (! res)
935                                 return 0;
936                         tmp.type = SDB_TYPE_ARRAY | SDB_TYPE_STRING;
937                         tmp.data.array.length = obj->backends_num;
938                         tmp.data.array.values = obj->backends;
939                         return sdb_data_copy(res, &tmp);
940                 case SDB_FIELD_VALUE:
941                         if (obj->type != SDB_ATTRIBUTE)
942                                 return -1;
943                         if (! res)
944                                 return 0;
945                         return sdb_data_copy(res, &ATTR(obj)->value);
946                 case SDB_FIELD_TIMESERIES:
947                         if (obj->type != SDB_METRIC)
948                                 return -1;
949                         tmp.type = SDB_TYPE_BOOLEAN;
950                         tmp.data.boolean = METRIC(obj)->store.type != NULL;
951                 default:
952                         return -1;
953         }
954         if (res)
955                 *res = tmp;
956         else
957                 sdb_data_free_datum(&tmp);
958         return 0;
959 } /* sdb_store_get_field */
961 int
962 sdb_store_get_attr(sdb_store_obj_t *obj, const char *name, sdb_data_t *res,
963                 sdb_store_matcher_t *filter)
965         sdb_avltree_t *tree = NULL;
966         sdb_store_obj_t *attr;
968         if ((! obj) || (! name))
969                 return -1;
971         if (obj->type == SDB_HOST)
972                 tree = HOST(obj)->attributes;
973         else if (obj->type == SDB_SERVICE)
974                 tree = SVC(obj)->attributes;
975         else if (obj->type == SDB_METRIC)
976                 tree = METRIC(obj)->attributes;
978         if (! tree)
979                 return -1;
981         attr = STORE_OBJ(sdb_avltree_lookup(tree, name));
982         if (! attr)
983                 return -1;
984         if (filter && (! sdb_store_matcher_matches(filter, attr, NULL))) {
985                 sdb_object_deref(SDB_OBJ(attr));
986                 return -1;
987         }
989         assert(STORE_OBJ(attr)->type == SDB_ATTRIBUTE);
990         if (res)
991                 sdb_data_copy(res, &ATTR(attr)->value);
992         sdb_object_deref(SDB_OBJ(attr));
993         return 0;
994 } /* sdb_store_get_attr */
996 /* TODO: sdb_store_fetch_timeseries should move into the plugin module */
998 int
999 sdb_store_fetch_timeseries(sdb_store_t *store,
1000                 const char *hostname, const char *metric,
1001                 sdb_timeseries_opts_t *opts, sdb_strbuf_t *buf)
1003         sdb_avltree_t *metrics;
1004         sdb_host_t *host;
1005         sdb_metric_t *m;
1007         sdb_timeseries_t *ts;
1009         int status = 0;
1011         if ((! store) || (! hostname) || (! metric) || (! opts) || (! buf))
1012                 return -1;
1014         pthread_rwlock_rdlock(&store->host_lock);
1015         host = HOST(sdb_avltree_lookup(store->hosts, hostname));
1016         metrics = get_host_children(host, SDB_METRIC);
1017         sdb_object_deref(SDB_OBJ(host));
1018         if (! metrics) {
1019                 sdb_log(SDB_LOG_ERR, "store: Failed to fetch time-series '%s/%s' "
1020                                 "- host '%s' not found", hostname, metric, hostname);
1021                 pthread_rwlock_unlock(&store->host_lock);
1022                 return -1;
1023         }
1025         m = METRIC(sdb_avltree_lookup(metrics, metric));
1026         if (! m) {
1027                 sdb_log(SDB_LOG_ERR, "store: Failed to fetch time-series '%s/%s' "
1028                                 "- metric '%s' not found", hostname, metric, metric);
1029                 pthread_rwlock_unlock(&store->host_lock);
1030                 return -1;
1031         }
1033         if ((! m->store.type) || (! m->store.id)) {
1034                 sdb_log(SDB_LOG_ERR, "store: Failed to fetch time-series '%s/%s' "
1035                                 "- no data-store configured for the stored metric",
1036                                 hostname, metric);
1037                 sdb_object_deref(SDB_OBJ(m));
1038                 pthread_rwlock_unlock(&store->host_lock);
1039                 return -1;
1040         }
1042         {
1043                 char type[strlen(m->store.type) + 1];
1044                 char id[strlen(m->store.id) + 1];
1046                 strncpy(type, m->store.type, sizeof(type));
1047                 strncpy(id, m->store.id, sizeof(id));
1048                 pthread_rwlock_unlock(&store->host_lock);
1050                 ts = sdb_plugin_fetch_timeseries(type, id, opts);
1051                 if (! ts) {
1052                         sdb_log(SDB_LOG_ERR, "store: Failed to fetch time-series '%s/%s' "
1053                                         "- %s fetcher callback returned no data for '%s'",
1054                                         hostname, metric, type, id);
1055                         status = -1;
1056                 }
1057         }
1059         ts_tojson(ts, buf);
1060         sdb_object_deref(SDB_OBJ(m));
1061         sdb_timeseries_destroy(ts);
1062         return status;
1063 } /* sdb_store_fetch_timeseries */
1065 int
1066 sdb_store_scan(sdb_store_t *store, int type,
1067                 sdb_store_matcher_t *m, sdb_store_matcher_t *filter,
1068                 sdb_store_lookup_cb cb, void *user_data)
1070         sdb_avltree_iter_t *host_iter = NULL;
1071         int status = 0;
1073         if ((! store) || (! cb))
1074                 return -1;
1076         if ((type != SDB_HOST) && (type != SDB_SERVICE) && (type != SDB_METRIC)) {
1077                 sdb_log(SDB_LOG_ERR, "store: Cannot scan objects of type %d", type);
1078                 return -1;
1079         }
1081         pthread_rwlock_rdlock(&store->host_lock);
1082         host_iter = sdb_avltree_get_iter(store->hosts);
1083         if (! host_iter)
1084                 status = -1;
1086         /* has_next returns false if the iterator is NULL */
1087         while (sdb_avltree_iter_has_next(host_iter)) {
1088                 sdb_store_obj_t *host;
1089                 sdb_avltree_iter_t *iter = NULL;
1091                 host = STORE_OBJ(sdb_avltree_iter_get_next(host_iter));
1092                 assert(host);
1094                 if (! sdb_store_matcher_matches(filter, host, NULL))
1095                         continue;
1097                 if (type == SDB_SERVICE)
1098                         iter = sdb_avltree_get_iter(HOST(host)->services);
1099                 else if (type == SDB_METRIC)
1100                         iter = sdb_avltree_get_iter(HOST(host)->metrics);
1102                 if (iter) {
1103                         while (sdb_avltree_iter_has_next(iter)) {
1104                                 sdb_store_obj_t *obj;
1105                                 obj = STORE_OBJ(sdb_avltree_iter_get_next(iter));
1106                                 assert(obj);
1108                                 if (sdb_store_matcher_matches(m, obj, filter)) {
1109                                         if (cb(obj, filter, user_data)) {
1110                                                 sdb_log(SDB_LOG_ERR, "store: Callback returned "
1111                                                                 "an error while scanning");
1112                                                 status = -1;
1113                                                 break;
1114                                         }
1115                                 }
1116                         }
1117                 }
1118                 else if (sdb_store_matcher_matches(m, host, filter)) {
1119                         if (cb(host, filter, user_data)) {
1120                                 sdb_log(SDB_LOG_ERR, "store: Callback returned "
1121                                                 "an error while scanning");
1122                                 status = -1;
1123                         }
1124                 }
1126                 sdb_avltree_iter_destroy(iter);
1127                 if (status)
1128                         break;
1129         }
1131         sdb_avltree_iter_destroy(host_iter);
1132         pthread_rwlock_unlock(&store->host_lock);
1133         return status;
1134 } /* sdb_store_scan */
1136 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */