Code

c8e35fe73584632fb60bd524835862d0da00a9ce
[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->current >= 1) && (obj->type != SDB_ATTRIBUTE)) {
146                 /* new entry of a previous type or a new type on the same level;
147                  * rewind to the right state */
148                 while ((f->current > 0)
149                                 && (f->context[f->current] == obj->type)) {
150                         sdb_strbuf_append(f->buf, "}]");
151                         --f->current;
152                 }
153         }
155         if (obj->type == f->context[f->current]) {
156                 /* new entry of the same type */
157                 sdb_strbuf_append(f->buf, "},");
158         }
159         else if ((f->context[f->current] == SDB_HOST)
160                         || (obj->type == SDB_ATTRIBUTE)) {
161                 assert(obj->type != SDB_HOST);
162                 /* all object types may be children of a host;
163                  * attributes may be children of any type */
164                 sdb_strbuf_append(f->buf, ", \"%ss\": [",
165                                 SDB_STORE_TYPE_TO_NAME(obj->type));
166                 ++f->current;
167         }
168         else {
169                 sdb_log(SDB_LOG_ERR, "store: Unexpected object of type %s "
170                                 "on level %zu during JSON serialization",
171                                 SDB_STORE_TYPE_TO_NAME(obj->type), f->current);
172                 return -1;
173         }
175         assert(f->current < SDB_STATIC_ARRAY_LEN(f->context));
176         f->context[f->current] = obj->type;
177         return 0;
178 } /* handle_new_object */
180 static int
181 json_emit(sdb_store_json_formatter_t *f, sdb_store_obj_t *obj)
183         char time_str[64];
184         char interval_str[64];
185         char name[2 * strlen(SDB_OBJ(obj)->name) + 3];
186         size_t i;
188         assert(f && obj);
190         handle_new_object(f, obj);
192         escape_string(SDB_OBJ(obj)->name, name);
193         sdb_strbuf_append(f->buf, "{\"name\": %s, ", name);
194         if (obj->type == SDB_ATTRIBUTE) {
195                 char tmp[sdb_data_strlen(&ATTR(obj)->value) + 1];
196                 char val[2 * sizeof(tmp) + 3];
197                 if (! sdb_data_format(&ATTR(obj)->value, tmp, sizeof(tmp),
198                                         SDB_DOUBLE_QUOTED))
199                         snprintf(tmp, sizeof(tmp), "<error>");
201                 if (tmp[0] == '"') {
202                         /* a string; escape_string handles quoting */
203                         tmp[strlen(tmp) - 1] = '\0';
204                         escape_string(tmp + 1, val);
205                         sdb_strbuf_append(f->buf, "\"value\": %s, ", val);
206                 }
207                 else
208                         sdb_strbuf_append(f->buf, "\"value\": %s, ", tmp);
209         }
210         else if (obj->type == SDB_METRIC) {
211                 if (METRIC(obj)->store.type != NULL)
212                         sdb_strbuf_append(f->buf, "\"timeseries\": true, ");
213                 else
214                         sdb_strbuf_append(f->buf, "\"timeseries\": false, ");
215         }
217         /* TODO: make time and interval formats configurable */
218         if (! sdb_strftime(time_str, sizeof(time_str), obj->last_update))
219                 snprintf(time_str, sizeof(time_str), "<error>");
220         time_str[sizeof(time_str) - 1] = '\0';
222         if (! sdb_strfinterval(interval_str, sizeof(interval_str),
223                                 obj->interval))
224                 snprintf(interval_str, sizeof(interval_str), "<error>");
225         interval_str[sizeof(interval_str) - 1] = '\0';
227         sdb_strbuf_append(f->buf, "\"last_update\": \"%s\", "
228                         "\"update_interval\": \"%s\", \"backends\": [",
229                         time_str, interval_str);
231         for (i = 0; i < obj->backends_num; ++i) {
232                 sdb_strbuf_append(f->buf, "\"%s\"", obj->backends[i]);
233                 if (i < obj->backends_num - 1)
234                         sdb_strbuf_append(f->buf, ",");
235         }
236         sdb_strbuf_append(f->buf, "]");
237         return 0;
238 } /* json_emit */
240 /*
241  * public API
242  */
244 sdb_store_json_formatter_t *
245 sdb_store_json_formatter(sdb_strbuf_t *buf, int type, int flags)
247         return F(sdb_object_create("json-formatter", formatter_type,
248                                 buf, type, flags));
249 } /* sdb_store_json_formatter */
251 int
252 sdb_store_json_emit(sdb_store_json_formatter_t *f, sdb_store_obj_t *obj)
254         if ((! f) || (! obj))
255                 return -1;
256         return json_emit(f, obj);
257 } /* sdb_store_json_emit */
259 int
260 sdb_store_json_emit_full(sdb_store_json_formatter_t *f, sdb_store_obj_t *obj,
261                 sdb_store_matcher_t *filter)
263         sdb_avltree_t *trees[] = { NULL, NULL, NULL };
264         size_t i;
266         if (sdb_store_json_emit(f, obj))
267                 return -1;
269         if (obj->type == SDB_HOST) {
270                 trees[0] = HOST(obj)->attributes;
271                 trees[1] = HOST(obj)->metrics;
272                 trees[2] = HOST(obj)->services;
273         }
274         else if (obj->type == SDB_SERVICE)
275                 trees[0] = SVC(obj)->attributes;
276         else if (obj->type == SDB_METRIC)
277                 trees[0] = METRIC(obj)->attributes;
278         else if (obj->type == SDB_ATTRIBUTE)
279                 return 0;
280         else
281                 return -1;
283         for (i = 0; i < SDB_STATIC_ARRAY_LEN(trees); ++i) {
284                 sdb_avltree_iter_t *iter;
286                 if (! trees[i])
287                         continue;
289                 iter = sdb_avltree_get_iter(trees[i]);
290                 while (sdb_avltree_iter_has_next(iter)) {
291                         sdb_store_obj_t *child;
292                         child = STORE_OBJ(sdb_avltree_iter_get_next(iter));
294                         if (filter && (! sdb_store_matcher_matches(filter, child, NULL)))
295                                 continue;
297                         if (sdb_store_json_emit_full(f, child, filter)) {
298                                 sdb_avltree_iter_destroy(iter);
299                                 return -1;
300                         }
301                 }
302                 sdb_avltree_iter_destroy(iter);
303         }
304         return 0;
305 } /* sdb_store_json_emit_full */
307 int
308 sdb_store_json_finish(sdb_store_json_formatter_t *f)
310         if (! f)
311                 return -1;
313         if (! f->context[0]) {
314                 /* no content */
315                 if (f->flags & SDB_WANT_ARRAY)
316                         sdb_strbuf_append(f->buf, "[]");
317                 return 0;
318         }
320         while (f->current > 0) {
321                 sdb_strbuf_append(f->buf, "}]");
322                 --f->current;
323         }
324         sdb_strbuf_append(f->buf, "}");
326         if (f->flags & SDB_WANT_ARRAY)
327                 sdb_strbuf_append(f->buf, "]");
328         return 0;
329 } /* sdb_store_json_finish */
331 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */