1 /*
2 * SysDB - src/frontend/query.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 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
32 #include "sysdb.h"
34 #include "core/plugin.h"
35 #include "frontend/connection-private.h"
36 #include "parser/ast.h"
37 #include "parser/parser.h"
38 #include "utils/error.h"
39 #include "utils/proto.h"
40 #include "utils/strbuf.h"
42 #include <errno.h>
43 #include <ctype.h>
44 #include <string.h>
46 /*
47 * metric fetcher:
48 * Implements the callbacks necessary to read a metric object.
49 */
51 typedef struct {
52 char *type;
53 char *id;
54 sdb_time_t last_update;
55 } metric_store_t;
57 static int
58 metric_fetcher_host(sdb_store_host_t __attribute__((unused)) *host,
59 sdb_object_t __attribute__((unused)) *user_data)
60 {
61 return 0;
62 } /* metric_fetcher_host */
64 static int
65 metric_fetcher_metric(sdb_store_metric_t *metric, sdb_object_t *user_data)
66 {
67 metric_store_t *st = SDB_OBJ_WRAPPER(user_data)->data;
68 sdb_time_t last_update = 0;
69 size_t idx = 0, i;
71 if (! metric->stores_num)
72 return -1;
74 /* Find the most up to date data store.
75 * TODO: Consider merging multiple results? */
76 for (i = 0; i < metric->stores_num; ++i) {
77 if (metric->stores[i].last_update > last_update) {
78 last_update = metric->stores[i].last_update;
79 idx = i;
80 }
81 }
82 st->type = strdup(metric->stores[idx].type);
83 st->id = strdup(metric->stores[idx].id);
84 st->last_update = metric->stores[idx].last_update;
85 return 0;
86 } /* metric_fetcher_metric */
88 static sdb_store_writer_t metric_fetcher = {
89 metric_fetcher_host, NULL, metric_fetcher_metric, NULL,
90 };
92 /*
93 * private helper functions
94 */
96 static char *
97 sstrdup(const char *s)
98 {
99 return s ? strdup(s) : NULL;
100 } /* sstrdup */
102 static size_t
103 sstrlen(const char *s)
104 {
105 return s ? strlen(s) : 0;
106 } /* sstrlen */
108 static int
109 exec_query(sdb_ast_node_t *ast, sdb_strbuf_t *buf, sdb_strbuf_t *errbuf)
110 {
111 sdb_store_json_formatter_t *f;
112 int type = 0, flags = 0;
113 uint32_t res_type = 0;
114 int status;
116 switch (ast->type) {
117 case SDB_AST_TYPE_FETCH:
118 type = SDB_AST_FETCH(ast)->obj_type;
119 res_type = htonl(SDB_CONNECTION_FETCH);
120 break;
121 case SDB_AST_TYPE_LIST:
122 type = SDB_AST_LIST(ast)->obj_type;
123 flags = SDB_WANT_ARRAY;
124 res_type = htonl(SDB_CONNECTION_LIST);
125 break;
126 case SDB_AST_TYPE_LOOKUP:
127 type = SDB_AST_LOOKUP(ast)->obj_type;
128 flags = SDB_WANT_ARRAY;
129 res_type = htonl(SDB_CONNECTION_LOOKUP);
130 break;
131 default:
132 sdb_strbuf_sprintf(errbuf, "invalid command %s (%#x)",
133 SDB_AST_TYPE_TO_STRING(ast), ast->type);
134 return -1;
135 }
137 f = sdb_store_json_formatter(buf, type, flags);
138 sdb_strbuf_memcpy(buf, &res_type, sizeof(res_type));
139 status = sdb_plugin_query(ast, &sdb_store_json_writer, SDB_OBJ(f), errbuf);
140 if (status < 0)
141 sdb_strbuf_clear(buf);
142 sdb_store_json_finish(f);
143 sdb_object_deref(SDB_OBJ(f));
144 return status;
145 } /* exec_query */
147 static int
148 exec_store(sdb_ast_store_t *st, sdb_strbuf_t *buf, sdb_strbuf_t *errbuf)
149 {
150 char name[sstrlen(st->hostname) + sstrlen(st->parent) + sstrlen(st->name) + 3];
151 sdb_metric_store_t metric_store;
152 int type = st->obj_type, status = -1;
154 switch (st->obj_type) {
155 case SDB_HOST:
156 strncpy(name, st->name, sizeof(name));
157 status = sdb_plugin_store_host(st->name, st->last_update);
158 break;
160 case SDB_SERVICE:
161 snprintf(name, sizeof(name), "%s.%s", st->hostname, st->name);
162 status = sdb_plugin_store_service(st->hostname, st->name, st->last_update);
163 break;
165 case SDB_METRIC:
166 snprintf(name, sizeof(name), "%s.%s", st->hostname, st->name);
167 metric_store.type = st->store_type;
168 metric_store.id = st->store_id;
169 metric_store.last_update = st->store_last_update;
170 status = sdb_plugin_store_metric(st->hostname, st->name,
171 &metric_store, st->last_update);
172 break;
174 case SDB_ATTRIBUTE:
175 type |= st->parent_type;
177 if (st->parent)
178 snprintf(name, sizeof(name), "%s.%s.%s",
179 st->hostname, st->parent, st->name);
180 else
181 snprintf(name, sizeof(name), "%s.%s", st->hostname, st->name);
183 switch (st->parent_type) {
184 case 0:
185 type |= SDB_HOST;
186 status = sdb_plugin_store_attribute(st->hostname,
187 st->name, &st->value, st->last_update);
188 break;
190 case SDB_SERVICE:
191 status = sdb_plugin_store_service_attribute(st->hostname, st->parent,
192 st->name, &st->value, st->last_update);
193 break;
195 case SDB_METRIC:
196 status = sdb_plugin_store_metric_attribute(st->hostname, st->parent,
197 st->name, &st->value, st->last_update);
198 break;
200 default:
201 sdb_log(SDB_LOG_ERR, "store: Invalid parent type in STORE: %s",
202 SDB_STORE_TYPE_TO_NAME(st->parent_type));
203 return -1;
204 }
205 break;
207 default:
208 sdb_log(SDB_LOG_ERR, "store: Invalid object type in STORE: %s",
209 SDB_STORE_TYPE_TO_NAME(st->obj_type));
210 return -1;
211 }
213 if (status < 0) {
214 sdb_strbuf_sprintf(errbuf, "STORE: Failed to store %s object",
215 SDB_STORE_TYPE_TO_NAME(type));
216 return -1;
217 }
219 if (! status) {
220 sdb_strbuf_sprintf(buf, "Successfully stored %s %s",
221 SDB_STORE_TYPE_TO_NAME(type), name);
222 }
223 else {
224 char type_str[32];
225 strncpy(type_str, SDB_STORE_TYPE_TO_NAME(type), sizeof(type_str));
226 type_str[0] = (char)toupper((int)type_str[0]);
227 sdb_strbuf_sprintf(buf, "%s %s already up to date", type_str, name);
228 }
230 return SDB_CONNECTION_OK;
231 } /* exec_store */
233 static int
234 exec_timeseries(sdb_ast_timeseries_t *ts, sdb_strbuf_t *buf, sdb_strbuf_t *errbuf)
235 {
236 metric_store_t st = { NULL, NULL, 0 };
237 sdb_object_wrapper_t obj = SDB_OBJECT_WRAPPER_STATIC(&st);
238 sdb_ast_fetch_t fetch = SDB_AST_FETCH_INIT;
239 sdb_timeseries_opts_t opts = { 0, 0 };
240 sdb_timeseries_t *series = NULL;
241 int status;
243 if ((! ts) || (! ts->hostname) || (! ts->metric))
244 return -1;
246 fetch.obj_type = SDB_METRIC;
247 fetch.hostname = strdup(ts->hostname);
248 fetch.name = strdup(ts->metric);
249 opts.start = ts->start;
250 opts.end = ts->end;
252 status = sdb_plugin_query(SDB_AST_NODE(&fetch),
253 &metric_fetcher, SDB_OBJ(&obj), errbuf);
254 if ((status < 0) || (! st.type) || (! st.id)) {
255 sdb_log(SDB_LOG_ERR, "frontend: Failed to fetch time-series '%s/%s' "
256 "- no data-store configured for the stored metric",
257 ts->hostname, ts->metric);
258 status = -1;
259 }
260 if (status >= 0) {
261 series = sdb_plugin_fetch_timeseries(st.type, st.id, &opts);
262 if (series) {
263 uint32_t res_type = htonl(SDB_CONNECTION_TIMESERIES);
264 sdb_strbuf_memcpy(buf, &res_type, sizeof(res_type));
265 sdb_timeseries_tojson(series, buf);
266 sdb_timeseries_destroy(series);
267 }
268 else {
269 sdb_log(SDB_LOG_ERR, "frontend: Failed to fetch time-series '%s/%s' "
270 "- %s fetcher callback returned no data for '%s'",
271 ts->hostname, ts->metric, st.type, st.id);
272 status = -1;
273 }
274 }
276 free(fetch.hostname);
277 free(fetch.name);
278 if (st.type)
279 free(st.type);
280 if (st.id)
281 free(st.id);
282 return status;
283 } /* exec_timeseries */
285 static int
286 exec_cmd(sdb_conn_t *conn, sdb_ast_node_t *ast)
287 {
288 sdb_strbuf_t *buf;
289 int status;
291 if (! ast) {
292 sdb_strbuf_sprintf(conn->errbuf, "out of memory");
293 return -1;
294 }
296 buf = sdb_strbuf_create(1024);
297 if (! buf) {
298 sdb_strbuf_sprintf(conn->errbuf, "Out of memory");
299 return -1;
300 }
302 if (ast->type == SDB_AST_TYPE_STORE)
303 status = exec_store(SDB_AST_STORE(ast), buf, conn->errbuf);
304 else if (ast->type == SDB_AST_TYPE_TIMESERIES)
305 status = exec_timeseries(SDB_AST_TIMESERIES(ast), buf, conn->errbuf);
306 else
307 status = exec_query(ast, buf, conn->errbuf);
309 if (status < 0) {
310 char query[conn->cmd_len + 1];
311 strncpy(query, sdb_strbuf_string(conn->buf), conn->cmd_len);
312 query[sizeof(query) - 1] = '\0';
313 sdb_log(SDB_LOG_ERR, "frontend: failed to execute query '%s'", query);
314 }
315 else
316 sdb_connection_send(conn, status,
317 (uint32_t)sdb_strbuf_len(buf), sdb_strbuf_string(buf));
319 sdb_strbuf_destroy(buf);
320 return status < 0 ? status : 0;
321 } /* exec_cmd */
323 /*
324 * public API
325 */
327 int
328 sdb_conn_query(sdb_conn_t *conn)
329 {
330 sdb_llist_t *parsetree;
331 sdb_ast_node_t *ast = NULL;
332 int status = 0;
334 if ((! conn) || (conn->cmd != SDB_CONNECTION_QUERY))
335 return -1;
337 parsetree = sdb_parser_parse(sdb_strbuf_string(conn->buf),
338 (int)conn->cmd_len, conn->errbuf);
339 if (! parsetree) {
340 char query[conn->cmd_len + 1];
341 strncpy(query, sdb_strbuf_string(conn->buf), conn->cmd_len);
342 query[sizeof(query) - 1] = '\0';
343 sdb_log(SDB_LOG_ERR, "frontend: Failed to parse query '%s': %s",
344 query, sdb_strbuf_string(conn->errbuf));
345 return -1;
346 }
348 switch (sdb_llist_len(parsetree)) {
349 case 0:
350 /* skipping empty command; send back an empty reply */
351 sdb_connection_send(conn, SDB_CONNECTION_DATA, 0, NULL);
352 break;
353 case 1:
354 ast = SDB_AST_NODE(sdb_llist_get(parsetree, 0));
355 break;
357 default:
358 {
359 char query[conn->cmd_len + 1];
360 strncpy(query, sdb_strbuf_string(conn->buf), conn->cmd_len);
361 query[sizeof(query) - 1] = '\0';
362 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring %zu command%s "
363 "in multi-statement query '%s'",
364 sdb_llist_len(parsetree) - 1,
365 sdb_llist_len(parsetree) == 2 ? "" : "s",
366 query);
367 ast = SDB_AST_NODE(sdb_llist_get(parsetree, 0));
368 }
369 }
371 if (ast) {
372 status = exec_cmd(conn, ast);
373 sdb_object_deref(SDB_OBJ(ast));
374 }
375 sdb_llist_destroy(parsetree);
376 return status;
377 } /* sdb_conn_query */
379 int
380 sdb_conn_fetch(sdb_conn_t *conn)
381 {
382 sdb_ast_node_t *ast;
383 char hostname[conn->cmd_len + 1];
384 char name[conn->cmd_len + 1];
385 uint32_t type;
386 int status;
388 if ((! conn) || (conn->cmd != SDB_CONNECTION_FETCH))
389 return -1;
391 if (conn->cmd_len < sizeof(uint32_t)) {
392 sdb_log(SDB_LOG_ERR, "frontend: Invalid command length %d for "
393 "FETCH command", conn->cmd_len);
394 sdb_strbuf_sprintf(conn->errbuf, "FETCH: Invalid command length %d",
395 conn->cmd_len);
396 return -1;
397 }
399 /* TODO: support other types besides hosts */
400 hostname[0] = '\0';
402 sdb_proto_unmarshal_int32(SDB_STRBUF_STR(conn->buf), &type);
403 strncpy(name, sdb_strbuf_string(conn->buf) + sizeof(uint32_t),
404 conn->cmd_len - sizeof(uint32_t));
405 name[sizeof(name) - 1] = '\0';
407 ast = sdb_ast_fetch_create((int)type,
408 hostname[0] ? strdup(hostname) : NULL,
409 -1, NULL,
410 name[0] ? strdup(name) : NULL,
411 /* full */ 1, /* filter = */ NULL);
412 status = exec_cmd(conn, ast);
413 sdb_object_deref(SDB_OBJ(ast));
414 return status;
415 } /* sdb_conn_fetch */
417 int
418 sdb_conn_list(sdb_conn_t *conn)
419 {
420 sdb_ast_node_t *ast;
421 uint32_t type = SDB_HOST;
422 int status;
424 if ((! conn) || (conn->cmd != SDB_CONNECTION_LIST))
425 return -1;
427 if (conn->cmd_len == sizeof(uint32_t))
428 sdb_proto_unmarshal_int32(SDB_STRBUF_STR(conn->buf), &type);
429 else if (conn->cmd_len) {
430 sdb_log(SDB_LOG_ERR, "frontend: Invalid command length %d for "
431 "LIST command", conn->cmd_len);
432 sdb_strbuf_sprintf(conn->errbuf, "LIST: Invalid command length %d",
433 conn->cmd_len);
434 return -1;
435 }
437 ast = sdb_ast_list_create((int)type, /* filter = */ NULL);
438 status = exec_cmd(conn, ast);
439 sdb_object_deref(SDB_OBJ(ast));
440 return status;
441 } /* sdb_conn_list */
443 int
444 sdb_conn_lookup(sdb_conn_t *conn)
445 {
446 sdb_ast_node_t *ast, *m;
447 const char *matcher;
448 size_t matcher_len;
450 uint32_t type;
451 int status;
453 if ((! conn) || (conn->cmd != SDB_CONNECTION_LOOKUP))
454 return -1;
456 if (conn->cmd_len < sizeof(uint32_t)) {
457 sdb_log(SDB_LOG_ERR, "frontend: Invalid command length %d for "
458 "LOOKUP command", conn->cmd_len);
459 sdb_strbuf_sprintf(conn->errbuf, "LOOKUP: Invalid command length %d",
460 conn->cmd_len);
461 return -1;
462 }
463 sdb_proto_unmarshal_int32(SDB_STRBUF_STR(conn->buf), &type);
465 matcher = sdb_strbuf_string(conn->buf) + sizeof(uint32_t);
466 matcher_len = conn->cmd_len - sizeof(uint32_t);
467 m = sdb_parser_parse_conditional((int)type,
468 matcher, (int)matcher_len, conn->errbuf);
469 if (! m) {
470 char expr[matcher_len + 1];
471 char err[sdb_strbuf_len(conn->errbuf) + sizeof(expr) + 64];
472 strncpy(expr, matcher, sizeof(expr));
473 expr[sizeof(expr) - 1] = '\0';
474 snprintf(err, sizeof(err), "Failed to parse lookup condition '%s': %s",
475 expr, sdb_strbuf_string(conn->errbuf));
476 sdb_log(SDB_LOG_ERR, "frontend: %s", err);
477 sdb_strbuf_sprintf(conn->errbuf, "%s", err);
478 return -1;
479 }
481 ast = sdb_ast_lookup_create((int)type, m, /* filter = */ NULL);
482 status = exec_cmd(conn, ast);
483 if (! ast)
484 sdb_object_deref(SDB_OBJ(m));
485 sdb_object_deref(SDB_OBJ(ast));
486 return status;
487 } /* sdb_conn_lookup */
489 int
490 sdb_conn_store(sdb_conn_t *conn)
491 {
492 sdb_ast_node_t *ast = NULL;
493 const char *buf = sdb_strbuf_string(conn->buf);
494 size_t len = conn->cmd_len;
495 uint32_t type;
496 ssize_t n;
497 int status;
499 if ((! conn) || (conn->cmd != SDB_CONNECTION_STORE))
500 return -1;
502 if ((n = sdb_proto_unmarshal_int32(buf, len, &type)) < 0) {
503 sdb_log(SDB_LOG_ERR, "frontend: Invalid command length %zu for "
504 "STORE command", len);
505 sdb_strbuf_sprintf(conn->errbuf,
506 "STORE: Invalid command length %zu", len);
507 return -1;
508 }
510 switch (type) {
511 case SDB_HOST:
512 {
513 sdb_proto_host_t host;
514 if (sdb_proto_unmarshal_host(buf, len, &host) < 0) {
515 sdb_strbuf_sprintf(conn->errbuf,
516 "STORE: Failed to unmarshal host object");
517 return -1;
518 }
519 ast = sdb_ast_store_create(SDB_HOST, /* host */ NULL,
520 /* parent */ 0, NULL, sstrdup(host.name), host.last_update,
521 /* metric store */ NULL, NULL, 0, SDB_DATA_NULL);
522 }
523 break;
525 case SDB_SERVICE:
526 {
527 sdb_proto_service_t svc;
528 if (sdb_proto_unmarshal_service(buf, len, &svc) < 0) {
529 sdb_strbuf_sprintf(conn->errbuf,
530 "STORE: Failed to unmarshal service object");
531 return -1;
532 }
533 ast = sdb_ast_store_create(SDB_SERVICE, sstrdup(svc.hostname),
534 /* parent */ 0, NULL, sstrdup(svc.name), svc.last_update,
535 /* metric store */ NULL, NULL, 0, SDB_DATA_NULL);
536 }
537 break;
539 case SDB_METRIC:
540 {
541 sdb_proto_metric_t metric;
542 if (sdb_proto_unmarshal_metric(buf, len, &metric) < 0) {
543 sdb_strbuf_sprintf(conn->errbuf,
544 "STORE: Failed to unmarshal metric object");
545 return -1;
546 }
547 ast = sdb_ast_store_create(SDB_METRIC, sstrdup(metric.hostname),
548 /* parent */ 0, NULL, sstrdup(metric.name), metric.last_update,
549 sstrdup(metric.store_type), sstrdup(metric.store_id),
550 metric.store_last_update, SDB_DATA_NULL);
551 }
552 break;
553 }
555 if (type & SDB_ATTRIBUTE) {
556 sdb_proto_attribute_t attr;
557 const char *hostname, *parent;
558 int parent_type;
559 if (sdb_proto_unmarshal_attribute(buf, len, &attr) < 0) {
560 sdb_strbuf_sprintf(conn->errbuf,
561 "STORE: Failed to unmarshal attribute object");
562 return -1;
563 }
564 if (attr.parent_type == SDB_HOST) {
565 hostname = attr.parent;
566 parent_type = 0;
567 parent = NULL;
568 }
569 else {
570 hostname = attr.hostname;
571 parent_type = attr.parent_type;
572 parent = attr.parent;
573 }
574 ast = sdb_ast_store_create(SDB_ATTRIBUTE, sstrdup(hostname),
575 parent_type, sstrdup(parent), sstrdup(attr.key),
576 attr.last_update, /* metric store */ NULL, NULL, 0,
577 attr.value);
578 }
580 if (! ast) {
581 sdb_log(SDB_LOG_ERR, "frontend: Invalid object type %d for "
582 "STORE COMMAND", type);
583 sdb_strbuf_sprintf(conn->errbuf, "STORE: Invalid object type %d", type);
584 return -1;
585 }
587 status = sdb_parser_analyze(ast, conn->errbuf);
588 if (! status)
589 status = exec_cmd(conn, ast);
590 sdb_object_deref(SDB_OBJ(ast));
591 return status;
592 } /* sdb_conn_store */
594 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */