Code

store: Removed obsolete TODO note.
[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 sdb_host_t *
301 lookup_host(sdb_store_t *st, const char *name, bool canonicalize)
303         sdb_host_t *host;
304         char *cname;
306         assert(name);
307         if (! canonicalize)
308                 return HOST(sdb_avltree_lookup(st->hosts, name));
310         cname = strdup(name);
311         cname = sdb_plugin_cname(cname);
312         if (! cname) {
313                 sdb_log(SDB_LOG_ERR, "store: strdup failed");
314                 return NULL;
315         }
317         host = HOST(sdb_avltree_lookup(st->hosts, cname));
318         free(cname);
319         return host;
320 } /* lookup_host */
322 static int
323 record_backend(sdb_store_obj_t *obj)
325         const sdb_plugin_info_t *info;
326         char **tmp;
327         size_t i;
329         info = sdb_plugin_current();
330         if (! info)
331                 return 0;
333         for (i = 0; i < obj->backends_num; ++i)
334                 if (!strcasecmp(obj->backends[i], info->plugin_name))
335                         return 0;
337         tmp = realloc(obj->backends,
338                         (obj->backends_num + 1) * sizeof(*obj->backends));
339         if (! tmp)
340                 return -1;
342         obj->backends = tmp;
343         obj->backends[obj->backends_num] = strdup(info->plugin_name);
344         if (! obj->backends[obj->backends_num])
345                 return -1;
347         ++obj->backends_num;
348         return 0;
349 } /* record_backend */
351 static int
352 store_obj(sdb_store_obj_t *parent, sdb_avltree_t *parent_tree,
353                 int type, const char *name, sdb_time_t last_update,
354                 sdb_store_obj_t **updated_obj)
356         sdb_store_obj_t *old, *new;
357         int status = 0;
359         assert(parent_tree);
361         if (last_update <= 0)
362                 last_update = sdb_gettime();
364         old = STORE_OBJ(sdb_avltree_lookup(parent_tree, name));
365         if (old) {
366                 if (old->last_update > last_update) {
367                         sdb_log(SDB_LOG_DEBUG, "store: Cannot update %s '%s' - "
368                                         "value too old (%"PRIsdbTIME" < %"PRIsdbTIME")",
369                                         SDB_STORE_TYPE_TO_NAME(type), name,
370                                         last_update, old->last_update);
371                         /* don't report an error; the object may be updated by multiple
372                          * backends */
373                         status = 1;
374                 }
375                 else if (old->last_update == last_update) {
376                         /* don't report an error and also don't even log this to avoid
377                          * excessive noise on high sampling frequencies */
378                         status = 1;
379                 }
380                 else {
381                         sdb_time_t interval = last_update - old->last_update;
382                         old->last_update = last_update;
383                         if (interval) {
384                                 if (old->interval)
385                                         old->interval = (sdb_time_t)((0.9 * (double)old->interval)
386                                                         + (0.1 * (double)interval));
387                                 else
388                                         old->interval = interval;
389                         }
390                 }
392                 new = old;
393                 sdb_object_deref(SDB_OBJ(old));
394         }
395         else {
396                 if (type == SDB_ATTRIBUTE) {
397                         /* the value will be updated by the caller */
398                         new = STORE_OBJ(sdb_object_create(name, attribute_type,
399                                                 type, last_update, NULL));
400                 }
401                 else {
402                         sdb_type_t t;
403                         t = type == SDB_HOST
404                                 ? host_type
405                                 : type == SDB_SERVICE
406                                         ? service_type
407                                         : metric_type;
408                         new = STORE_OBJ(sdb_object_create(name, t, type, last_update));
409                 }
411                 if (new) {
412                         status = sdb_avltree_insert(parent_tree, SDB_OBJ(new));
414                         /* pass control to the tree or destroy in case of an error */
415                         sdb_object_deref(SDB_OBJ(new));
416                 }
417                 else {
418                         char errbuf[1024];
419                         sdb_log(SDB_LOG_ERR, "store: Failed to create %s '%s': %s",
420                                         SDB_STORE_TYPE_TO_NAME(type), name,
421                                         sdb_strerror(errno, errbuf, sizeof(errbuf)));
422                         status = -1;
423                 }
424         }
426         if (status < 0)
427                 return status;
428         assert(new);
430         if (new->parent != parent) {
431                 // Avoid circular self-references which are not handled
432                 // correctly by the ref-count based management layer.
433                 //sdb_object_deref(SDB_OBJ(new->parent));
434                 //sdb_object_ref(SDB_OBJ(parent));
435                 new->parent = parent;
436         }
438         if (updated_obj)
439                 *updated_obj = new;
441         if (record_backend(new))
442                 return -1;
443         return status;
444 } /* store_obj */
446 static int
447 store_attr(sdb_store_obj_t *parent, sdb_avltree_t *attributes,
448                 const char *key, const sdb_data_t *value, sdb_time_t last_update)
450         sdb_store_obj_t *attr = NULL;
451         int status;
453         status = store_obj(parent, attributes, SDB_ATTRIBUTE,
454                         key, last_update, &attr);
455         if (status)
456                 return status;
458         /* don't update unchanged values */
459         if (! sdb_data_cmp(&ATTR(attr)->value, value))
460                 return status;
462         assert(attr);
463         if (sdb_data_copy(&ATTR(attr)->value, value))
464                 return -1;
465         return status;
466 } /* store_attr */
468 static int
469 store_metric_store(sdb_metric_t *metric, sdb_metric_store_t *store)
471         char *type = metric->store.type;
472         char *id = metric->store.id;
474         if ((! metric->store.type) || strcasecmp(metric->store.type, store->type)) {
475                 if (! (type = strdup(store->type)))
476                         return -1;
477         }
478         if ((! metric->store.id) || strcasecmp(metric->store.id, store->id)) {
479                 if (! (id = strdup(store->id))) {
480                         if (type != metric->store.type)
481                                 free(type);
482                         return -1;
483                 }
484         }
486         if (type != metric->store.type) {
487                 if (metric->store.type)
488                         free(metric->store.type);
489                 metric->store.type = type;
490         }
491         if (id != metric->store.id) {
492                 if (metric->store.id)
493                         free(metric->store.id);
494                 metric->store.id = id;
495         }
496         return 0;
497 } /* store_metric_store */
499 /* The store's host_lock has to be acquired before calling this function. */
500 static sdb_avltree_t *
501 get_host_children(sdb_host_t *host, int type)
503         if ((type != SDB_SERVICE) && (type != SDB_METRIC)
504                         && (type != SDB_ATTRIBUTE))
505                 return NULL;
507         if (! host)
508                 return NULL;
510         if (type == SDB_ATTRIBUTE)
511                 return host->attributes;
512         else if (type == SDB_METRIC)
513                 return host->metrics;
514         else
515                 return host->services;
516 } /* get_host_children */
518 /*
519  * ts_tojson serializes a time-series to JSON.
520  *
521  * The function never returns an error. Rather, an error message will be part
522  * of the serialized data.
523  */
524 static void
525 ts_tojson(sdb_timeseries_t *ts, sdb_strbuf_t *buf)
527         char start_str[64];
528         char end_str[64];
530         size_t i;
532         /* TODO: make time format configurable */
533         if (! sdb_strftime(start_str, sizeof(start_str), ts->start))
534                 snprintf(start_str, sizeof(start_str), "<error>");
535         start_str[sizeof(start_str) - 1] = '\0';
536         if (! sdb_strftime(end_str, sizeof(end_str), ts->end))
537                 snprintf(end_str, sizeof(end_str), "<error>");
538         end_str[sizeof(end_str) - 1] = '\0';
540         sdb_strbuf_append(buf, "{\"start\": \"%s\", \"end\": \"%s\", \"data\": {",
541                         start_str, end_str);
543         for (i = 0; i < ts->data_names_len; ++i) {
544                 size_t j;
545                 sdb_strbuf_append(buf, "\"%s\": [", ts->data_names[i]);
547                 for (j = 0; j < ts->data_len; ++j) {
548                         char time_str[64];
550                         if (! sdb_strftime(time_str, sizeof(time_str), ts->data[i][j].timestamp))
551                                 snprintf(time_str, sizeof(time_str), "<error>");
552                         time_str[sizeof(time_str) - 1] = '\0';
554                         /* Some GNU libc versions may print '-nan' which we dont' want */
555                         if (isnan(ts->data[i][j].value))
556                                 sdb_strbuf_append(buf, "{\"timestamp\": \"%s\", "
557                                                 "\"value\": \"nan\"}", time_str);
558                         else
559                                 sdb_strbuf_append(buf, "{\"timestamp\": \"%s\", "
560                                                 "\"value\": \"%f\"}", time_str, ts->data[i][j].value);
562                         if (j < ts->data_len - 1)
563                                 sdb_strbuf_append(buf, ",");
564                 }
566                 if (i < ts->data_names_len - 1)
567                         sdb_strbuf_append(buf, "],");
568                 else
569                         sdb_strbuf_append(buf, "]");
570         }
571         sdb_strbuf_append(buf, "}}");
572 } /* ts_tojson */
574 /*
575  * store writer API
576  */
578 static int
579 store_attribute(const char *hostname,
580                 const char *key, const sdb_data_t *value,
581                 sdb_time_t last_update, sdb_object_t *user_data)
583         sdb_store_t *st = SDB_STORE(user_data);
585         sdb_host_t *host;
586         sdb_avltree_t *attrs;
587         int status = 0;
589         if ((! hostname) || (! key))
590                 return -1;
592         pthread_rwlock_wrlock(&st->host_lock);
593         host = lookup_host(st, hostname, /* canonicalize = */ 0);
594         attrs = get_host_children(host, SDB_ATTRIBUTE);
595         if (! attrs) {
596                 sdb_log(SDB_LOG_ERR, "store: Failed to store attribute '%s' - "
597                                 "host '%s' not found", key, hostname);
598                 status = -1;
599         }
601         if (! status)
602                 status = store_attr(STORE_OBJ(host), attrs, key, value, last_update);
604         sdb_object_deref(SDB_OBJ(host));
605         pthread_rwlock_unlock(&st->host_lock);
607         return status;
608 } /* store_attribute */
610 static int
611 store_host(const char *name, sdb_time_t last_update, sdb_object_t *user_data)
613         sdb_store_t *st = SDB_STORE(user_data);
614         int status = 0;
616         if (! name)
617                 return -1;
619         pthread_rwlock_wrlock(&st->host_lock);
620         status = store_obj(NULL, st->hosts,
621                         SDB_HOST, name, last_update, NULL);
622         pthread_rwlock_unlock(&st->host_lock);
624         return status;
625 } /* store_host */
627 static int
628 store_service_attr(const char *hostname, const char *service,
629                 const char *key, const sdb_data_t *value, sdb_time_t last_update,
630                 sdb_object_t *user_data)
632         sdb_store_t *st = SDB_STORE(user_data);
634         sdb_host_t *host;
635         sdb_service_t *svc;
636         sdb_avltree_t *services;
637         int status = 0;
639         if ((! hostname) || (! service) || (! key))
640                 return -1;
642         pthread_rwlock_wrlock(&st->host_lock);
643         host = lookup_host(st, hostname, /* canonicalize = */ 0);
644         services = get_host_children(host, SDB_SERVICE);
645         sdb_object_deref(SDB_OBJ(host));
646         if (! services) {
647                 sdb_log(SDB_LOG_ERR, "store: Failed to store attribute '%s' "
648                                 "for service '%s' - host '%ss' not found",
649                                 key, service, hostname);
650                 pthread_rwlock_unlock(&st->host_lock);
651                 return -1;
652         }
654         svc = SVC(sdb_avltree_lookup(services, service));
655         if (! svc) {
656                 sdb_log(SDB_LOG_ERR, "store: Failed to store attribute '%s' - "
657                                 "service '%s/%s' not found", key, hostname, service);
658                 status = -1;
659         }
661         if (! status)
662                 status = store_attr(STORE_OBJ(svc), svc->attributes,
663                                 key, value, last_update);
665         sdb_object_deref(SDB_OBJ(svc));
666         pthread_rwlock_unlock(&st->host_lock);
668         return status;
669 } /* store_service_attr */
671 static int
672 store_service(const char *hostname, const char *name,
673                 sdb_time_t last_update, sdb_object_t *user_data)
675         sdb_store_t *st = SDB_STORE(user_data);
677         sdb_host_t *host;
678         sdb_avltree_t *services;
679         sdb_data_t d;
681         int status = 0;
683         if ((! hostname) || (! name))
684                 return -1;
686         pthread_rwlock_wrlock(&st->host_lock);
687         host = lookup_host(st, hostname, /* canonicalize = */ 0);
688         services = get_host_children(host, SDB_SERVICE);
689         if (! services) {
690                 sdb_log(SDB_LOG_ERR, "store: Failed to store service '%s' - "
691                                 "host '%s' not found", name, hostname);
692                 status = -1;
693         }
695         if (! status)
696                 status = store_obj(STORE_OBJ(host), services, SDB_SERVICE,
697                                 name, last_update, NULL);
699         sdb_object_deref(SDB_OBJ(host));
700         pthread_rwlock_unlock(&st->host_lock);
702         if (status)
703                 return status;
705         /* record the hostname as an attribute */
706         d.type = SDB_TYPE_STRING;
707         d.data.string = SDB_OBJ(host)->name;
708         if (store_service_attr(hostname, name, "hostname", &d, last_update, user_data))
709                 status = -1;
710         return status;
711 } /* store_service */
713 static int
714 store_metric_attr(const char *hostname, const char *metric,
715                 const char *key, const sdb_data_t *value, sdb_time_t last_update,
716                 sdb_object_t *user_data)
718         sdb_store_t *st = SDB_STORE(user_data);
720         sdb_avltree_t *metrics;
721         sdb_host_t *host;
722         sdb_metric_t *m;
723         int status = 0;
725         if ((! hostname) || (! metric) || (! key))
726                 return -1;
728         pthread_rwlock_wrlock(&st->host_lock);
729         host = lookup_host(st, hostname, /* canonicalize = */ 0);
730         metrics = get_host_children(host, SDB_METRIC);
731         sdb_object_deref(SDB_OBJ(host));
732         if (! metrics) {
733                 sdb_log(SDB_LOG_ERR, "store: Failed to store attribute '%s' "
734                                 "for metric '%s' - host '%s' not found",
735                                 key, metric, hostname);
736                 pthread_rwlock_unlock(&st->host_lock);
737                 return -1;
738         }
740         m = METRIC(sdb_avltree_lookup(metrics, metric));
741         if (! m) {
742                 sdb_log(SDB_LOG_ERR, "store: Failed to store attribute '%s' - "
743                                 "metric '%s/%s' not found", key, hostname, metric);
744                 status = -1;
745         }
747         if (! status)
748                 status = store_attr(STORE_OBJ(m), m->attributes,
749                                 key, value, last_update);
751         sdb_object_deref(SDB_OBJ(m));
752         pthread_rwlock_unlock(&st->host_lock);
754         return status;
755 } /* store_metric_attr */
757 static int
758 store_metric(const char *hostname, const char *name,
759                 sdb_metric_store_t *store, sdb_time_t last_update,
760                 sdb_object_t *user_data)
762         sdb_store_t *st = SDB_STORE(user_data);
764         sdb_store_obj_t *obj = NULL;
765         sdb_host_t *host;
766         sdb_metric_t *metric;
767         sdb_data_t d;
769         sdb_avltree_t *metrics;
771         int status = 0;
773         if ((! hostname) || (! name))
774                 return -1;
776         if (store) {
777                 if ((store->type != NULL) != (store->id != NULL))
778                         return -1;
779                 else if (! store->type)
780                         store = NULL;
781         }
783         pthread_rwlock_wrlock(&st->host_lock);
784         host = lookup_host(st, hostname, /* canonicalize = */ 0);
785         metrics = get_host_children(host, SDB_METRIC);
786         if (! metrics) {
787                 sdb_log(SDB_LOG_ERR, "store: Failed to store metric '%s' - "
788                                 "host '%s' not found", name, hostname);
789                 status = -1;
790         }
792         if (! status)
793                 status = store_obj(STORE_OBJ(host), metrics, SDB_METRIC,
794                                 name, last_update, &obj);
795         sdb_object_deref(SDB_OBJ(host));
797         if (status) {
798                 pthread_rwlock_unlock(&st->host_lock);
799                 return status;
800         }
802         assert(obj);
803         metric = METRIC(obj);
805         if (store)
806                 if (store_metric_store(metric, store))
807                         status = -1;
808         pthread_rwlock_unlock(&st->host_lock);
810         /* record the hostname as an attribute */
811         d.type = SDB_TYPE_STRING;
812         d.data.string = SDB_OBJ(host)->name;
813         if (store_metric_attr(hostname, name, "hostname", &d, last_update, user_data))
814                 status = -1;
815         return status;
816 } /* store_metric */
818 sdb_store_writer_t sdb_store_writer = {
819         store_host, store_service, store_metric,
820         store_attribute, store_service_attr, store_metric_attr,
821 };
823 static sdb_object_t *
824 prepare_query(sdb_ast_node_t *ast,
825                 sdb_strbuf_t __attribute__((unused)) *errbuf,
826                 sdb_object_t __attribute__((unused)) *user_data)
828         return SDB_OBJ(sdb_store_query_prepare(ast));
829 } /* prepare_query */
831 static int
832 execute_query(sdb_object_t *q,
833                 sdb_strbuf_t *buf, sdb_strbuf_t *errbuf,
834                 sdb_object_t *user_data)
836         return sdb_store_query_execute(SDB_STORE(user_data),
837                         QUERY(q), buf, errbuf);
838 } /* execute_query */
840 sdb_store_reader_t sdb_store_reader = {
841         prepare_query, execute_query,
842 };
844 /*
845  * public API
846  */
848 sdb_store_t *
849 sdb_store_create(void)
851         return SDB_STORE(sdb_object_create("store", store_type));
852 } /* sdb_store_create */
854 int
855 sdb_store_host(sdb_store_t *store, const char *name, sdb_time_t last_update)
857         return store_host(name, last_update, SDB_OBJ(store));
858 } /* sdb_store_host */
860 int
861 sdb_store_service(sdb_store_t *store, const char *hostname, const char *name,
862                 sdb_time_t last_update)
864         return store_service(hostname, name, last_update, SDB_OBJ(store));
865 } /* sdb_store_service */
867 int
868 sdb_store_metric(sdb_store_t *store, const char *hostname, const char *name,
869                 sdb_metric_store_t *metric_store, sdb_time_t last_update)
871         return store_metric(hostname, name, metric_store, last_update, SDB_OBJ(store));
872 } /* sdb_store_metric */
874 int
875 sdb_store_attribute(sdb_store_t *store, const char *hostname,
876                 const char *key, const sdb_data_t *value, sdb_time_t last_update)
878         return store_attribute(hostname, key, value, last_update, SDB_OBJ(store));
879 } /* sdb_store_attribute */
881 int
882 sdb_store_service_attr(sdb_store_t *store, const char *hostname,
883                 const char *service, const char *key, const sdb_data_t *value,
884                 sdb_time_t last_update)
886         return store_service_attr(hostname, service, key, value,
887                         last_update, SDB_OBJ(store));
888 } /* sdb_store_service_attr */
890 int
891 sdb_store_metric_attr(sdb_store_t *store, const char *hostname,
892                 const char *metric, const char *key, const sdb_data_t *value,
893                 sdb_time_t last_update)
895         return store_metric_attr(hostname, metric, key, value,
896                         last_update, SDB_OBJ(store));
897 } /* sdb_store_metric_attr */
899 sdb_store_obj_t *
900 sdb_store_get_host(sdb_store_t *store, const char *name)
902         sdb_host_t *host;
904         if ((! store) || (! name))
905                 return NULL;
907         host = lookup_host(store, name, /* canonicalize = */ 0);
908         if (! host)
909                 return NULL;
911         return STORE_OBJ(host);
912 } /* sdb_store_get_host */
914 sdb_store_obj_t *
915 sdb_store_get_child(sdb_store_obj_t *host, int type, const char *name)
917         sdb_avltree_t *children;
919         if ((! host) || (host->type != SDB_HOST) || (! name))
920                 return NULL;
922         children = get_host_children(HOST(host), type);
923         if (! children)
924                 return NULL;
925         return STORE_OBJ(sdb_avltree_lookup(children, name));
926 } /* sdb_store_get_child */
928 int
929 sdb_store_get_field(sdb_store_obj_t *obj, int field, sdb_data_t *res)
931         sdb_data_t tmp;
933         if (! obj)
934                 return -1;
936         switch (field) {
937                 case SDB_FIELD_NAME:
938                         tmp.type = SDB_TYPE_STRING;
939                         tmp.data.string = strdup(SDB_OBJ(obj)->name);
940                         if (! tmp.data.string)
941                                 return -1;
942                         break;
943                 case SDB_FIELD_LAST_UPDATE:
944                         tmp.type = SDB_TYPE_DATETIME;
945                         tmp.data.datetime = obj->last_update;
946                         break;
947                 case SDB_FIELD_AGE:
948                         tmp.type = SDB_TYPE_DATETIME;
949                         tmp.data.datetime = sdb_gettime() - obj->last_update;
950                         break;
951                 case SDB_FIELD_INTERVAL:
952                         tmp.type = SDB_TYPE_DATETIME;
953                         tmp.data.datetime = obj->interval;
954                         break;
955                 case SDB_FIELD_BACKEND:
956                         if (! res)
957                                 return 0;
958                         tmp.type = SDB_TYPE_ARRAY | SDB_TYPE_STRING;
959                         tmp.data.array.length = obj->backends_num;
960                         tmp.data.array.values = obj->backends;
961                         return sdb_data_copy(res, &tmp);
962                 case SDB_FIELD_VALUE:
963                         if (obj->type != SDB_ATTRIBUTE)
964                                 return -1;
965                         if (! res)
966                                 return 0;
967                         return sdb_data_copy(res, &ATTR(obj)->value);
968                 case SDB_FIELD_TIMESERIES:
969                         if (obj->type != SDB_METRIC)
970                                 return -1;
971                         tmp.type = SDB_TYPE_BOOLEAN;
972                         tmp.data.boolean = METRIC(obj)->store.type != NULL;
973                 default:
974                         return -1;
975         }
976         if (res)
977                 *res = tmp;
978         else
979                 sdb_data_free_datum(&tmp);
980         return 0;
981 } /* sdb_store_get_field */
983 int
984 sdb_store_get_attr(sdb_store_obj_t *obj, const char *name, sdb_data_t *res,
985                 sdb_store_matcher_t *filter)
987         sdb_avltree_t *tree = NULL;
988         sdb_store_obj_t *attr;
990         if ((! obj) || (! name))
991                 return -1;
993         if (obj->type == SDB_HOST)
994                 tree = HOST(obj)->attributes;
995         else if (obj->type == SDB_SERVICE)
996                 tree = SVC(obj)->attributes;
997         else if (obj->type == SDB_METRIC)
998                 tree = METRIC(obj)->attributes;
1000         if (! tree)
1001                 return -1;
1003         attr = STORE_OBJ(sdb_avltree_lookup(tree, name));
1004         if (! attr)
1005                 return -1;
1006         if (filter && (! sdb_store_matcher_matches(filter, attr, NULL))) {
1007                 sdb_object_deref(SDB_OBJ(attr));
1008                 return -1;
1009         }
1011         assert(STORE_OBJ(attr)->type == SDB_ATTRIBUTE);
1012         if (res)
1013                 sdb_data_copy(res, &ATTR(attr)->value);
1014         sdb_object_deref(SDB_OBJ(attr));
1015         return 0;
1016 } /* sdb_store_get_attr */
1018 /* TODO: sdb_store_fetch_timeseries should move into the plugin module */
1020 int
1021 sdb_store_fetch_timeseries(sdb_store_t *store,
1022                 const char *hostname, const char *metric,
1023                 sdb_timeseries_opts_t *opts, sdb_strbuf_t *buf)
1025         sdb_avltree_t *metrics;
1026         sdb_host_t *host;
1027         sdb_metric_t *m;
1029         sdb_timeseries_t *ts;
1031         int status = 0;
1033         if ((! store) || (! hostname) || (! metric) || (! opts) || (! buf))
1034                 return -1;
1036         pthread_rwlock_rdlock(&store->host_lock);
1037         host = lookup_host(store, hostname, /* canonicalize = */ 1);
1038         metrics = get_host_children(host, SDB_METRIC);
1039         sdb_object_deref(SDB_OBJ(host));
1040         if (! metrics) {
1041                 sdb_log(SDB_LOG_ERR, "store: Failed to fetch time-series '%s/%s' "
1042                                 "- host '%s' not found", hostname, metric, hostname);
1043                 pthread_rwlock_unlock(&store->host_lock);
1044                 return -1;
1045         }
1047         m = METRIC(sdb_avltree_lookup(metrics, metric));
1048         if (! m) {
1049                 sdb_log(SDB_LOG_ERR, "store: Failed to fetch time-series '%s/%s' "
1050                                 "- metric '%s' not found", hostname, metric, metric);
1051                 pthread_rwlock_unlock(&store->host_lock);
1052                 return -1;
1053         }
1055         if ((! m->store.type) || (! m->store.id)) {
1056                 sdb_log(SDB_LOG_ERR, "store: Failed to fetch time-series '%s/%s' "
1057                                 "- no data-store configured for the stored metric",
1058                                 hostname, metric);
1059                 sdb_object_deref(SDB_OBJ(m));
1060                 pthread_rwlock_unlock(&store->host_lock);
1061                 return -1;
1062         }
1064         {
1065                 char type[strlen(m->store.type) + 1];
1066                 char id[strlen(m->store.id) + 1];
1068                 strncpy(type, m->store.type, sizeof(type));
1069                 strncpy(id, m->store.id, sizeof(id));
1070                 pthread_rwlock_unlock(&store->host_lock);
1072                 ts = sdb_plugin_fetch_timeseries(type, id, opts);
1073                 if (! ts) {
1074                         sdb_log(SDB_LOG_ERR, "store: Failed to fetch time-series '%s/%s' "
1075                                         "- %s fetcher callback returned no data for '%s'",
1076                                         hostname, metric, type, id);
1077                         status = -1;
1078                 }
1079         }
1081         ts_tojson(ts, buf);
1082         sdb_object_deref(SDB_OBJ(m));
1083         sdb_timeseries_destroy(ts);
1084         return status;
1085 } /* sdb_store_fetch_timeseries */
1087 int
1088 sdb_store_scan(sdb_store_t *store, int type,
1089                 sdb_store_matcher_t *m, sdb_store_matcher_t *filter,
1090                 sdb_store_lookup_cb cb, void *user_data)
1092         sdb_avltree_iter_t *host_iter = NULL;
1093         int status = 0;
1095         if ((! store) || (! cb))
1096                 return -1;
1098         if ((type != SDB_HOST) && (type != SDB_SERVICE) && (type != SDB_METRIC)) {
1099                 sdb_log(SDB_LOG_ERR, "store: Cannot scan objects of type %d", type);
1100                 return -1;
1101         }
1103         pthread_rwlock_rdlock(&store->host_lock);
1104         host_iter = sdb_avltree_get_iter(store->hosts);
1105         if (! host_iter)
1106                 status = -1;
1108         /* has_next returns false if the iterator is NULL */
1109         while (sdb_avltree_iter_has_next(host_iter)) {
1110                 sdb_store_obj_t *host;
1111                 sdb_avltree_iter_t *iter = NULL;
1113                 host = STORE_OBJ(sdb_avltree_iter_get_next(host_iter));
1114                 assert(host);
1116                 if (! sdb_store_matcher_matches(filter, host, NULL))
1117                         continue;
1119                 if (type == SDB_SERVICE)
1120                         iter = sdb_avltree_get_iter(HOST(host)->services);
1121                 else if (type == SDB_METRIC)
1122                         iter = sdb_avltree_get_iter(HOST(host)->metrics);
1124                 if (iter) {
1125                         while (sdb_avltree_iter_has_next(iter)) {
1126                                 sdb_store_obj_t *obj;
1127                                 obj = STORE_OBJ(sdb_avltree_iter_get_next(iter));
1128                                 assert(obj);
1130                                 if (sdb_store_matcher_matches(m, obj, filter)) {
1131                                         if (cb(obj, filter, user_data)) {
1132                                                 sdb_log(SDB_LOG_ERR, "store: Callback returned "
1133                                                                 "an error while scanning");
1134                                                 status = -1;
1135                                                 break;
1136                                         }
1137                                 }
1138                         }
1139                 }
1140                 else if (sdb_store_matcher_matches(m, host, filter)) {
1141                         if (cb(host, filter, user_data)) {
1142                                 sdb_log(SDB_LOG_ERR, "store: Callback returned "
1143                                                 "an error while scanning");
1144                                 status = -1;
1145                         }
1146                 }
1148                 sdb_avltree_iter_destroy(iter);
1149                 if (status)
1150                         break;
1151         }
1153         sdb_avltree_iter_destroy(host_iter);
1154         pthread_rwlock_unlock(&store->host_lock);
1155         return status;
1156 } /* sdb_store_scan */
1158 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */