Code

878cc4fe265886653c754a60a83ef23889af1668
[sysdb.git] / src / core / store_json.c
1 /*
2  * SysDB - src/core/store_json.c
3  * Copyright (C) 2013-2014 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         /* The current host context when processing non-host objects */
62         sdb_store_obj_t *current_host;
64         int type;
65         int flags;
66 };
67 #define F(obj) ((sdb_store_json_formatter_t *)(obj))
69 static int
70 formatter_init(sdb_object_t *obj, va_list ap)
71 {
72         sdb_store_json_formatter_t *f = F(obj);
74         f->buf = va_arg(ap, sdb_strbuf_t *);
75         if (! f->buf)
76                 return -1;
78         f->type = va_arg(ap, int);
79         if ((f->type != SDB_HOST) && (f->type != SDB_SERVICE) && (f->type != SDB_METRIC))
80                 return -1;
82         f->flags = va_arg(ap, int);
84         f->context[0] = 0;
85         f->current = 0;
87         f->current_host = NULL;
88         return 0;
89 } /* formatter_init */
91 static sdb_type_t formatter_type = {
92         /* size = */ sizeof(sdb_store_json_formatter_t),
93         /* init = */ formatter_init,
94         /* destroy = */ NULL,
95 };
97 /*
98  * private helper functions
99  */
101 static void
102 escape_string(const char *src, char *dest)
104         size_t i = 1;
105         dest[0] = '"';
106         for ( ; *src; ++src) {
107                 char c = *src;
108                 if ((c == '"') || (c == '\\') || iscntrl((int)c)) {
109                         dest[i] = '\\';
110                         ++i;
111                 }
112                 switch (c) {
113                         case '\a': dest[i] = 'a'; break;
114                         case '\b': dest[i] = 'b'; break;
115                         case '\t': dest[i] = 't'; break;
116                         case '\n': dest[i] = 'n'; break;
117                         case '\v': dest[i] = 'v'; break;
118                         case '\f': dest[i] = 'f'; break;
119                         case '\r': dest[i] = 'r'; break;
120                         default: dest[i] = c; break;
121                 }
122                 ++i;
123         }
124         dest[i] = '"';
125         dest[i + 1] = '\0';
126 } /* escape_string */
128 static int
129 json_emit(sdb_store_json_formatter_t *f, sdb_store_obj_t *obj)
131         char time_str[64];
132         char interval_str[64];
133         char name[2 * strlen(SDB_OBJ(obj)->name) + 3];
134         size_t i;
136         assert(f && obj);
138         if ((f->type != SDB_HOST) && (f->type == obj->type)) {
139                 /* create the host for the current entry first */
140                 assert(obj->parent && (obj->parent->type == SDB_HOST));
141                 if (f->current_host != obj->parent) {
142                         json_emit(f, obj->parent);
143                         sdb_strbuf_append(f->buf, ", \"%ss\": [",
144                                         SDB_STORE_TYPE_TO_NAME(obj->type));
145                         f->current_host = obj->parent;
146                 }
147         }
149         escape_string(SDB_OBJ(obj)->name, name);
150         sdb_strbuf_append(f->buf, "{\"name\": %s, ", name);
151         if (obj->type == SDB_ATTRIBUTE) {
152                 char tmp[sdb_data_strlen(&ATTR(obj)->value) + 1];
153                 char val[2 * sizeof(tmp) + 3];
154                 if (! sdb_data_format(&ATTR(obj)->value, tmp, sizeof(tmp),
155                                         SDB_DOUBLE_QUOTED))
156                         snprintf(tmp, sizeof(tmp), "<error>");
158                 if (tmp[0] == '"') {
159                         /* a string; escape_string handles quoting */
160                         tmp[strlen(tmp) - 1] = '\0';
161                         escape_string(tmp + 1, val);
162                         sdb_strbuf_append(f->buf, "\"value\": %s, ", val);
163                 }
164                 else
165                         sdb_strbuf_append(f->buf, "\"value\": %s, ", tmp);
166         }
167         else if (obj->type == SDB_METRIC) {
168                 if (METRIC(obj)->store.type != NULL)
169                         sdb_strbuf_append(f->buf, "\"timeseries\": true, ");
170                 else
171                         sdb_strbuf_append(f->buf, "\"timeseries\": false, ");
172         }
174         /* TODO: make time and interval formats configurable */
175         if (! sdb_strftime(time_str, sizeof(time_str), obj->last_update))
176                 snprintf(time_str, sizeof(time_str), "<error>");
177         time_str[sizeof(time_str) - 1] = '\0';
179         if (! sdb_strfinterval(interval_str, sizeof(interval_str),
180                                 obj->interval))
181                 snprintf(interval_str, sizeof(interval_str), "<error>");
182         interval_str[sizeof(interval_str) - 1] = '\0';
184         sdb_strbuf_append(f->buf, "\"last_update\": \"%s\", "
185                         "\"update_interval\": \"%s\", \"backends\": [",
186                         time_str, interval_str);
188         for (i = 0; i < obj->backends_num; ++i) {
189                 sdb_strbuf_append(f->buf, "\"%s\"", obj->backends[i]);
190                 if (i < obj->backends_num - 1)
191                         sdb_strbuf_append(f->buf, ",");
192         }
193         sdb_strbuf_append(f->buf, "]");
194         return 0;
195 } /* json_emit */
197 /*
198  * public API
199  */
201 sdb_store_json_formatter_t *
202 sdb_store_json_formatter(sdb_strbuf_t *buf, int type, int flags)
204         return F(sdb_object_create("json-formatter", formatter_type,
205                                 buf, type, flags));
206 } /* sdb_store_json_formatter */
208 int
209 sdb_store_json_emit(sdb_store_json_formatter_t *f, sdb_store_obj_t *obj)
211         if ((! f) || (! obj))
212                 return -1;
214         if ((f->type != SDB_HOST) && (obj->type == SDB_HOST)) {
215                 sdb_log(SDB_LOG_ERR, "store: Unexpected object of type host "
216                                 "during %s JSON serialization",
217                                 SDB_STORE_TYPE_TO_NAME(f->type));
218                 return -1;
219         }
221         /* first top-level object */
222         if (! f->context[0]) {
223                 if (obj->type != f->type) {
224                         sdb_log(SDB_LOG_ERR, "store: Unexpected object of type %s "
225                                         "as the first element during %s JSON serialization",
226                                         SDB_STORE_TYPE_TO_NAME(obj->type),
227                                         SDB_STORE_TYPE_TO_NAME(f->type));
228                         return -1;
229                 }
230                 if (f->flags & SDB_WANT_ARRAY)
231                         sdb_strbuf_append(f->buf, "[");
232                 assert(f->current == 0);
233                 f->context[0] = obj->type;
234                 return json_emit(f, obj);
235         }
237         if ((f->current >= 1) && (obj->type != SDB_ATTRIBUTE)) {
238                 /* new entry of a previous type or a new type on the same level;
239                  * rewind to the right state */
240                 while (f->current > 0) {
241                         if (f->context[f->current] == obj->type)
242                                 break;
243                         sdb_strbuf_append(f->buf, "}]");
244                         --f->current;
245                 }
246         }
247         if ((obj->type == f->type) && (f->type != SDB_HOST))
248                 if (obj->parent != f->current_host)
249                         sdb_strbuf_append(f->buf, "}]");
251         if (obj->type == f->context[f->current]) {
252                 /* new entry of the same type */
253                 sdb_strbuf_append(f->buf, "},");
254         }
255         else if ((f->context[f->current] == SDB_HOST)
256                         || (obj->type == SDB_ATTRIBUTE)) {
257                 assert(obj->type != SDB_HOST);
258                 /* all object types may be children of a host;
259                  * attributes may be children of any type */
260                 sdb_strbuf_append(f->buf, ", \"%ss\": [",
261                                 SDB_STORE_TYPE_TO_NAME(obj->type));
262                 ++f->current;
263         }
264         else {
265                 sdb_log(SDB_LOG_ERR, "store: Unexpected object of type %s "
266                                 "on level %zu during JSON serialization",
267                                 SDB_STORE_TYPE_TO_NAME(obj->type), f->current);
268                 return -1;
269         }
271         json_emit(f, obj);
272         assert(f->current < SDB_STATIC_ARRAY_LEN(f->context));
273         f->context[f->current] = obj->type;
274         return 0;
275 } /* sdb_store_json_emit */
277 int
278 sdb_store_json_emit_full(sdb_store_json_formatter_t *f, sdb_store_obj_t *obj,
279                 sdb_store_matcher_t *filter)
281         sdb_avltree_t *trees[] = { NULL, NULL, NULL };
282         size_t i;
284         if (sdb_store_json_emit(f, obj))
285                 return -1;
287         if (obj->type == SDB_HOST) {
288                 trees[0] = HOST(obj)->attributes;
289                 trees[1] = HOST(obj)->metrics;
290                 trees[2] = HOST(obj)->services;
291         }
292         else if (obj->type == SDB_SERVICE)
293                 trees[0] = SVC(obj)->attributes;
294         else if (obj->type == SDB_METRIC)
295                 trees[0] = METRIC(obj)->attributes;
296         else if (obj->type == SDB_ATTRIBUTE)
297                 return 0;
298         else
299                 return -1;
301         for (i = 0; i < SDB_STATIC_ARRAY_LEN(trees); ++i) {
302                 sdb_avltree_iter_t *iter;
304                 if (! trees[i])
305                         continue;
307                 iter = sdb_avltree_get_iter(trees[i]);
308                 while (sdb_avltree_iter_has_next(iter)) {
309                         sdb_store_obj_t *child;
310                         child = STORE_OBJ(sdb_avltree_iter_get_next(iter));
312                         if (filter && (! sdb_store_matcher_matches(filter, child, NULL)))
313                                 continue;
315                         if (sdb_store_json_emit_full(f, child, filter)) {
316                                 sdb_avltree_iter_destroy(iter);
317                                 return -1;
318                         }
319                 }
320                 sdb_avltree_iter_destroy(iter);
321         }
322         return 0;
323 } /* sdb_store_json_emit_full */
325 int
326 sdb_store_json_finish(sdb_store_json_formatter_t *f)
328         if (! f)
329                 return -1;
331         if (! f->context[0]) {
332                 /* no content */
333                 if (f->flags & SDB_WANT_ARRAY)
334                         sdb_strbuf_append(f->buf, "[]");
335                 return 0;
336         }
338         while (f->current > 0) {
339                 sdb_strbuf_append(f->buf, "}]");
340                 --f->current;
341         }
342         if (f->context[0] != SDB_HOST) {
343                 assert(f->type != SDB_HOST);
344                 sdb_strbuf_append(f->buf, "}]}");
345         }
346         else
347                 sdb_strbuf_append(f->buf, "}");
349         if (f->flags & SDB_WANT_ARRAY)
350                 sdb_strbuf_append(f->buf, "]");
351         return 0;
352 } /* sdb_store_json_finish */
354 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */