Code

store_json: Fix parent/child detection.
[sysdb.git] / src / core / store_json.c
1 /*
2  * SysDB - src/core/store_json.c
3  * Copyright (C) 2013-2015 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 /*
29  * This module implements JSON support.
30  */
32 #if HAVE_CONFIG_H
33 #       include "config.h"
34 #endif /* HAVE_CONFIG_H */
36 #include "sysdb.h"
37 #include "core/store-private.h"
38 #include "utils/error.h"
40 #include <assert.h>
42 #include <ctype.h>
43 #include <stdlib.h>
44 #include <string.h>
46 /*
47  * private data types
48  */
50 struct sdb_store_json_formatter {
51         sdb_object_t super;
53         /* The string buffer to write to */
54         sdb_strbuf_t *buf;
56         /* The context describes the state of the formatter through
57          * the path pointing to the current object */
58         int context[8];
59         size_t current;
61         int type;
62         int flags;
63 };
64 #define F(obj) ((sdb_store_json_formatter_t *)(obj))
66 static int
67 formatter_init(sdb_object_t *obj, va_list ap)
68 {
69         sdb_store_json_formatter_t *f = F(obj);
71         f->buf = va_arg(ap, sdb_strbuf_t *);
72         if (! f->buf)
73                 return -1;
75         f->type = va_arg(ap, int);
76         if ((f->type != SDB_HOST) && (f->type != SDB_SERVICE) && (f->type != SDB_METRIC))
77                 return -1;
79         f->flags = va_arg(ap, int);
81         f->context[0] = 0;
82         f->current = 0;
83         return 0;
84 } /* formatter_init */
86 static sdb_type_t formatter_type = {
87         /* size = */ sizeof(sdb_store_json_formatter_t),
88         /* init = */ formatter_init,
89         /* destroy = */ NULL,
90 };
92 /*
93  * private helper functions
94  */
96 static void
97 escape_string(const char *src, char *dest)
98 {
99         size_t i = 1;
100         dest[0] = '"';
101         for ( ; *src; ++src) {
102                 char c = *src;
103                 if ((c == '"') || (c == '\\') || iscntrl((int)c)) {
104                         dest[i] = '\\';
105                         ++i;
106                 }
107                 switch (c) {
108                         case '\a': dest[i] = 'a'; break;
109                         case '\b': dest[i] = 'b'; break;
110                         case '\t': dest[i] = 't'; break;
111                         case '\n': dest[i] = 'n'; break;
112                         case '\v': dest[i] = 'v'; break;
113                         case '\f': dest[i] = 'f'; break;
114                         case '\r': dest[i] = 'r'; break;
115                         default: dest[i] = c; break;
116                 }
117                 ++i;
118         }
119         dest[i] = '"';
120         dest[i + 1] = '\0';
121 } /* escape_string */
123 /* handle_new_object takes care of all maintenance logic related to adding a
124  * new object. That is, it manages context information and emit the prefix and
125  * suffix of an object. */
126 static int
127 handle_new_object(sdb_store_json_formatter_t *f, sdb_store_obj_t *obj)
129         /* first top-level object */
130         if (! f->context[0]) {
131                 if ((obj->type != f->type) && (obj->type != SDB_HOST)) {
132                         sdb_log(SDB_LOG_ERR, "store: Unexpected object of type %s "
133                                         "as the first element during %s JSON serialization",
134                                         SDB_STORE_TYPE_TO_NAME(obj->type),
135                                         SDB_STORE_TYPE_TO_NAME(f->type));
136                         return -1;
137                 }
138                 if (f->flags & SDB_WANT_ARRAY)
139                         sdb_strbuf_append(f->buf, "[");
140                 assert(f->current == 0);
141                 f->context[f->current] = obj->type;
142                 return 0;
143         }
145         if ((f->context[f->current] != SDB_HOST)
146                         && (obj->type != SDB_ATTRIBUTE)) {
147                 /* new entry of the same type or a parent object;
148                  * rewind to the right state */
149                 while ((f->current > 0)
150                                 && (f->context[f->current] != obj->type)) {
151                         sdb_strbuf_append(f->buf, "}]");
152                         --f->current;
153                 }
154         }
156         if (obj->type == f->context[f->current]) {
157                 /* new entry of the same type */
158                 sdb_strbuf_append(f->buf, "},");
159         }
160         else if ((f->context[f->current] == SDB_HOST)
161                         || (obj->type == SDB_ATTRIBUTE)) {
162                 assert(obj->type != SDB_HOST);
163                 /* all object types may be children of a host;
164                  * attributes may be children of any type */
165                 sdb_strbuf_append(f->buf, ", \"%ss\": [",
166                                 SDB_STORE_TYPE_TO_NAME(obj->type));
167                 ++f->current;
168         }
169         else {
170                 sdb_log(SDB_LOG_ERR, "store: Unexpected object of type %s "
171                                 "on level %zu during JSON serialization",
172                                 SDB_STORE_TYPE_TO_NAME(obj->type), f->current);
173                 return -1;
174         }
176         assert(f->current < SDB_STATIC_ARRAY_LEN(f->context));
177         f->context[f->current] = obj->type;
178         return 0;
179 } /* handle_new_object */
181 static int
182 json_emit(sdb_store_json_formatter_t *f, sdb_store_obj_t *obj)
184         char time_str[64];
185         char interval_str[64];
186         char name[2 * strlen(SDB_OBJ(obj)->name) + 3];
187         size_t i;
189         assert(f && obj);
191         handle_new_object(f, obj);
193         escape_string(SDB_OBJ(obj)->name, name);
194         sdb_strbuf_append(f->buf, "{\"name\": %s, ", name);
195         if (obj->type == SDB_ATTRIBUTE) {
196                 char tmp[sdb_data_strlen(&ATTR(obj)->value) + 1];
197                 char val[2 * sizeof(tmp) + 3];
198                 if (! sdb_data_format(&ATTR(obj)->value, tmp, sizeof(tmp),
199                                         SDB_DOUBLE_QUOTED))
200                         snprintf(tmp, sizeof(tmp), "<error>");
202                 if (tmp[0] == '"') {
203                         /* a string; escape_string handles quoting */
204                         tmp[strlen(tmp) - 1] = '\0';
205                         escape_string(tmp + 1, val);
206                         sdb_strbuf_append(f->buf, "\"value\": %s, ", val);
207                 }
208                 else
209                         sdb_strbuf_append(f->buf, "\"value\": %s, ", tmp);
210         }
211         else if (obj->type == SDB_METRIC) {
212                 if (METRIC(obj)->store.type != NULL)
213                         sdb_strbuf_append(f->buf, "\"timeseries\": true, ");
214                 else
215                         sdb_strbuf_append(f->buf, "\"timeseries\": false, ");
216         }
218         /* TODO: make time and interval formats configurable */
219         if (! sdb_strftime(time_str, sizeof(time_str), obj->last_update))
220                 snprintf(time_str, sizeof(time_str), "<error>");
221         time_str[sizeof(time_str) - 1] = '\0';
223         if (! sdb_strfinterval(interval_str, sizeof(interval_str),
224                                 obj->interval))
225                 snprintf(interval_str, sizeof(interval_str), "<error>");
226         interval_str[sizeof(interval_str) - 1] = '\0';
228         sdb_strbuf_append(f->buf, "\"last_update\": \"%s\", "
229                         "\"update_interval\": \"%s\", \"backends\": [",
230                         time_str, interval_str);
232         for (i = 0; i < obj->backends_num; ++i) {
233                 sdb_strbuf_append(f->buf, "\"%s\"", obj->backends[i]);
234                 if (i < obj->backends_num - 1)
235                         sdb_strbuf_append(f->buf, ",");
236         }
237         sdb_strbuf_append(f->buf, "]");
238         return 0;
239 } /* json_emit */
241 /*
242  * public API
243  */
245 sdb_store_json_formatter_t *
246 sdb_store_json_formatter(sdb_strbuf_t *buf, int type, int flags)
248         return F(sdb_object_create("json-formatter", formatter_type,
249                                 buf, type, flags));
250 } /* sdb_store_json_formatter */
252 int
253 sdb_store_json_emit(sdb_store_json_formatter_t *f, sdb_store_obj_t *obj)
255         if ((! f) || (! obj))
256                 return -1;
257         return json_emit(f, obj);
258 } /* sdb_store_json_emit */
260 int
261 sdb_store_json_emit_full(sdb_store_json_formatter_t *f, sdb_store_obj_t *obj,
262                 sdb_store_matcher_t *filter)
264         sdb_avltree_t *trees[] = { NULL, NULL, NULL };
265         size_t i;
267         if (sdb_store_json_emit(f, obj))
268                 return -1;
270         if (obj->type == SDB_HOST) {
271                 trees[0] = HOST(obj)->attributes;
272                 trees[1] = HOST(obj)->metrics;
273                 trees[2] = HOST(obj)->services;
274         }
275         else if (obj->type == SDB_SERVICE)
276                 trees[0] = SVC(obj)->attributes;
277         else if (obj->type == SDB_METRIC)
278                 trees[0] = METRIC(obj)->attributes;
279         else if (obj->type == SDB_ATTRIBUTE)
280                 return 0;
281         else
282                 return -1;
284         for (i = 0; i < SDB_STATIC_ARRAY_LEN(trees); ++i) {
285                 sdb_avltree_iter_t *iter;
287                 if (! trees[i])
288                         continue;
290                 iter = sdb_avltree_get_iter(trees[i]);
291                 while (sdb_avltree_iter_has_next(iter)) {
292                         sdb_store_obj_t *child;
293                         child = STORE_OBJ(sdb_avltree_iter_get_next(iter));
295                         if (filter && (! sdb_store_matcher_matches(filter, child, NULL)))
296                                 continue;
298                         if (sdb_store_json_emit_full(f, child, filter)) {
299                                 sdb_avltree_iter_destroy(iter);
300                                 return -1;
301                         }
302                 }
303                 sdb_avltree_iter_destroy(iter);
304         }
305         return 0;
306 } /* sdb_store_json_emit_full */
308 int
309 sdb_store_json_finish(sdb_store_json_formatter_t *f)
311         if (! f)
312                 return -1;
314         if (! f->context[0]) {
315                 /* no content */
316                 if (f->flags & SDB_WANT_ARRAY)
317                         sdb_strbuf_append(f->buf, "[]");
318                 return 0;
319         }
321         while (f->current > 0) {
322                 sdb_strbuf_append(f->buf, "}]");
323                 --f->current;
324         }
325         sdb_strbuf_append(f->buf, "}");
327         if (f->flags & SDB_WANT_ARRAY)
328                 sdb_strbuf_append(f->buf, "]");
329         return 0;
330 } /* sdb_store_json_finish */
332 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */