1 /**
2  * collectd - src/utils_db_query.c
3  * Copyright (C) 2008,2009  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  **/
26 
27 #include "collectd.h"
28 
29 #include "plugin.h"
30 #include "utils/common/common.h"
31 #include "utils/db_query/db_query.h"
32 
33 /*
34  * Data types
35  */
36 struct udb_result_s; /* {{{ */
37 typedef struct udb_result_s udb_result_t;
38 struct udb_result_s {
39   char *type;
40   char *instance_prefix;
41   char **instances;
42   size_t instances_num;
43   char **values;
44   size_t values_num;
45   char **metadata;
46   size_t metadata_num;
47 
48   udb_result_t *next;
49 }; /* }}} */
50 
51 struct udb_query_s /* {{{ */
52 {
53   char *name;
54   char *statement;
55   void *user_data;
56   char *plugin_instance_from;
57 
58   unsigned int min_version;
59   unsigned int max_version;
60 
61   udb_result_t *results;
62 }; /* }}} */
63 
64 struct udb_result_preparation_area_s /* {{{ */
65 {
66   const data_set_t *ds;
67   size_t *instances_pos;
68   size_t *values_pos;
69   size_t *metadata_pos;
70   char **instances_buffer;
71   char **values_buffer;
72   char **metadata_buffer;
73   char *plugin_instance;
74 
75   struct udb_result_preparation_area_s *next;
76 }; /* }}} */
77 typedef struct udb_result_preparation_area_s udb_result_preparation_area_t;
78 
79 struct udb_query_preparation_area_s /* {{{ */
80 {
81   size_t column_num;
82   size_t plugin_instance_pos;
83   char *host;
84   char *plugin;
85   char *db_name;
86 
87   udb_result_preparation_area_t *result_prep_areas;
88 }; /* }}} */
89 
90 /*
91  * Config Private functions
92  */
udb_config_add_string(char *** ret_array,size_t * ret_array_len,oconfig_item_t * ci)93 static int udb_config_add_string(char ***ret_array, /* {{{ */
94                                  size_t *ret_array_len, oconfig_item_t *ci) {
95   char **array;
96   size_t array_len;
97 
98   if (ci->values_num < 1) {
99     P_WARNING("The `%s' config option "
100               "needs at least one argument.",
101               ci->key);
102     return -1;
103   }
104 
105   for (int i = 0; i < ci->values_num; i++) {
106     if (ci->values[i].type != OCONFIG_TYPE_STRING) {
107       P_WARNING("Argument %i to the `%s' option "
108                 "is not a string.",
109                 i + 1, ci->key);
110       return -1;
111     }
112   }
113 
114   array_len = *ret_array_len;
115   array = realloc(*ret_array, sizeof(char *) * (array_len + ci->values_num));
116   if (array == NULL) {
117     P_ERROR("udb_config_add_string: realloc failed.");
118     return -1;
119   }
120   *ret_array = array;
121 
122   for (int i = 0; i < ci->values_num; i++) {
123     array[array_len] = strdup(ci->values[i].value.string);
124     if (array[array_len] == NULL) {
125       P_ERROR("udb_config_add_string: strdup failed.");
126       *ret_array_len = array_len;
127       return -1;
128     }
129     array_len++;
130   }
131 
132   *ret_array_len = array_len;
133   return 0;
134 } /* }}} int udb_config_add_string */
135 
udb_config_set_uint(unsigned int * ret_value,oconfig_item_t * ci)136 static int udb_config_set_uint(unsigned int *ret_value, /* {{{ */
137                                oconfig_item_t *ci) {
138 
139   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER)) {
140     P_WARNING("The `%s' config option "
141               "needs exactly one numeric argument.",
142               ci->key);
143     return -1;
144   }
145 
146   double tmp = ci->values[0].value.number;
147   if ((tmp < 0.0) || (tmp > ((double)UINT_MAX))) {
148     P_WARNING("The value given for the `%s` option is out of range.", ci->key);
149     return -ERANGE;
150   }
151 
152   *ret_value = (unsigned int)(tmp + .5);
153   return 0;
154 } /* }}} int udb_config_set_uint */
155 
156 /*
157  * Result private functions
158  */
udb_result_submit(udb_result_t * r,udb_result_preparation_area_t * r_area,udb_query_t const * q,udb_query_preparation_area_t * q_area)159 static int udb_result_submit(udb_result_t *r, /* {{{ */
160                              udb_result_preparation_area_t *r_area,
161                              udb_query_t const *q,
162                              udb_query_preparation_area_t *q_area) {
163   value_list_t vl = VALUE_LIST_INIT;
164 
165   assert(r != NULL);
166   assert(r_area->ds != NULL);
167   assert(((size_t)r_area->ds->ds_num) == r->values_num);
168   assert(r->values_num > 0);
169 
170   vl.values = calloc(r->values_num, sizeof(*vl.values));
171   if (vl.values == NULL) {
172     P_ERROR("udb_result_submit: calloc failed.");
173     return -1;
174   }
175   vl.values_len = r_area->ds->ds_num;
176 
177   for (size_t i = 0; i < r->values_num; i++) {
178     char *value_str = r_area->values_buffer[i];
179 
180     if (0 != parse_value(value_str, &vl.values[i], r_area->ds->ds[i].type)) {
181       P_ERROR("udb_result_submit: Parsing `%s' as %s failed.", value_str,
182               DS_TYPE_TO_STRING(r_area->ds->ds[i].type));
183       errno = EINVAL;
184       free(vl.values);
185       return -1;
186     }
187   }
188 
189   sstrncpy(vl.host, q_area->host, sizeof(vl.host));
190   sstrncpy(vl.plugin, q_area->plugin, sizeof(vl.plugin));
191   sstrncpy(vl.type, r->type, sizeof(vl.type));
192 
193   /* Set vl.plugin_instance */
194   if (q->plugin_instance_from != NULL) {
195     sstrncpy(vl.plugin_instance, r_area->plugin_instance,
196              sizeof(vl.plugin_instance));
197   } else {
198     sstrncpy(vl.plugin_instance, q_area->db_name, sizeof(vl.plugin_instance));
199   }
200 
201   /* Set vl.type_instance {{{ */
202   if (r->instances_num == 0) {
203     if (r->instance_prefix == NULL)
204       vl.type_instance[0] = 0;
205     else
206       sstrncpy(vl.type_instance, r->instance_prefix, sizeof(vl.type_instance));
207   } else /* if ((r->instances_num > 0) */
208   {
209     if (r->instance_prefix == NULL) {
210       int status = strjoin(vl.type_instance, sizeof(vl.type_instance),
211                            r_area->instances_buffer, r->instances_num, "-");
212       if (status < 0) {
213         P_ERROR(
214             "udb_result_submit: creating type_instance failed with status %d.",
215             status);
216         return status;
217       }
218     } else {
219       char tmp[DATA_MAX_NAME_LEN];
220 
221       int status = strjoin(tmp, sizeof(tmp), r_area->instances_buffer,
222                            r->instances_num, "-");
223       if (status < 0) {
224         P_ERROR(
225             "udb_result_submit: creating type_instance failed with status %d.",
226             status);
227         return status;
228       }
229       tmp[sizeof(tmp) - 1] = '\0';
230 
231       ssnprintf(vl.type_instance, sizeof(vl.type_instance), "%s-%s",
232                 r->instance_prefix, tmp);
233     }
234   }
235   vl.type_instance[sizeof(vl.type_instance) - 1] = '\0';
236   /* }}} */
237 
238   /* Annotate meta data. {{{ */
239   if (r->metadata_num > 0) {
240     vl.meta = meta_data_create();
241     if (vl.meta == NULL) {
242       P_ERROR("udb_result_submit: meta_data_create failed.");
243       free(vl.values);
244       return -ENOMEM;
245     }
246 
247     for (size_t i = 0; i < r->metadata_num; i++) {
248       int status = meta_data_add_string(vl.meta, r->metadata[i],
249                                         r_area->metadata_buffer[i]);
250       if (status != 0) {
251         P_ERROR("udb_result_submit: meta_data_add_string failed.");
252         meta_data_destroy(vl.meta);
253         vl.meta = NULL;
254         free(vl.values);
255         return status;
256       }
257     }
258   }
259   /* }}} */
260 
261   plugin_dispatch_values(&vl);
262 
263   if (r->metadata_num > 0) {
264     meta_data_destroy(vl.meta);
265     vl.meta = NULL;
266   }
267   sfree(vl.values);
268   return 0;
269 } /* }}} void udb_result_submit */
270 
udb_result_finish_result(udb_result_t const * r,udb_result_preparation_area_t * prep_area)271 static void udb_result_finish_result(udb_result_t const *r, /* {{{ */
272                                      udb_result_preparation_area_t *prep_area) {
273   if ((r == NULL) || (prep_area == NULL))
274     return;
275 
276   prep_area->ds = NULL;
277   sfree(prep_area->instances_pos);
278   sfree(prep_area->values_pos);
279   sfree(prep_area->metadata_pos);
280   sfree(prep_area->instances_buffer);
281   sfree(prep_area->values_buffer);
282   sfree(prep_area->metadata_buffer);
283 } /* }}} void udb_result_finish_result */
284 
udb_result_handle_result(udb_result_t * r,udb_query_preparation_area_t * q_area,udb_result_preparation_area_t * r_area,udb_query_t const * q,char ** column_values)285 static int udb_result_handle_result(udb_result_t *r, /* {{{ */
286                                     udb_query_preparation_area_t *q_area,
287                                     udb_result_preparation_area_t *r_area,
288                                     udb_query_t const *q,
289                                     char **column_values) {
290   assert(r && q_area && r_area);
291 
292   for (size_t i = 0; i < r->instances_num; i++)
293     r_area->instances_buffer[i] = column_values[r_area->instances_pos[i]];
294 
295   for (size_t i = 0; i < r->values_num; i++)
296     r_area->values_buffer[i] = column_values[r_area->values_pos[i]];
297 
298   for (size_t i = 0; i < r->metadata_num; i++)
299     r_area->metadata_buffer[i] = column_values[r_area->metadata_pos[i]];
300 
301   if (q->plugin_instance_from)
302     r_area->plugin_instance = column_values[q_area->plugin_instance_pos];
303 
304   return udb_result_submit(r, r_area, q, q_area);
305 } /* }}} int udb_result_handle_result */
306 
udb_result_prepare_result(udb_result_t const * r,udb_result_preparation_area_t * prep_area,char ** column_names,size_t column_num)307 static int udb_result_prepare_result(udb_result_t const *r, /* {{{ */
308                                      udb_result_preparation_area_t *prep_area,
309                                      char **column_names, size_t column_num) {
310   if ((r == NULL) || (prep_area == NULL))
311     return -EINVAL;
312 
313 #if COLLECT_DEBUG
314   assert(prep_area->ds == NULL);
315   assert(prep_area->instances_pos == NULL);
316   assert(prep_area->values_pos == NULL);
317   assert(prep_area->metadata_pos == NULL);
318   assert(prep_area->instances_buffer == NULL);
319   assert(prep_area->values_buffer == NULL);
320   assert(prep_area->metadata_buffer == NULL);
321 #endif
322 
323 #define BAIL_OUT(status)                                                       \
324   udb_result_finish_result(r, prep_area);                                      \
325   return (status)
326 
327   /* Read `ds' and check number of values {{{ */
328   prep_area->ds = plugin_get_ds(r->type);
329   if (prep_area->ds == NULL) {
330     P_ERROR("udb_result_prepare_result: Type `%s' is not "
331             "known by the daemon. See types.db(5) for details.",
332             r->type);
333     BAIL_OUT(-1);
334   }
335 
336   if (prep_area->ds->ds_num != r->values_num) {
337     P_ERROR("udb_result_prepare_result: The type `%s' "
338             "requires exactly %" PRIsz
339             " value%s, but the configuration specifies %" PRIsz ".",
340             r->type, prep_area->ds->ds_num,
341             (prep_area->ds->ds_num == 1) ? "" : "s", r->values_num);
342     BAIL_OUT(-1);
343   }
344   /* }}} */
345 
346   /* Allocate r->instances_pos, r->values_pos, r->metadata_post,
347    * r->instances_buffer, r->values_buffer, and r->metadata_buffer {{{ */
348   if (r->instances_num > 0) {
349     prep_area->instances_pos =
350         calloc(r->instances_num, sizeof(*prep_area->instances_pos));
351     if (prep_area->instances_pos == NULL) {
352       P_ERROR("udb_result_prepare_result: calloc failed.");
353       BAIL_OUT(-ENOMEM);
354     }
355 
356     prep_area->instances_buffer =
357         calloc(r->instances_num, sizeof(*prep_area->instances_buffer));
358     if (prep_area->instances_buffer == NULL) {
359       P_ERROR("udb_result_prepare_result: calloc failed.");
360       BAIL_OUT(-ENOMEM);
361     }
362   } /* if (r->instances_num > 0) */
363 
364   prep_area->values_pos = calloc(r->values_num, sizeof(*prep_area->values_pos));
365   if (prep_area->values_pos == NULL) {
366     P_ERROR("udb_result_prepare_result: calloc failed.");
367     BAIL_OUT(-ENOMEM);
368   }
369 
370   prep_area->values_buffer =
371       calloc(r->values_num, sizeof(*prep_area->values_buffer));
372   if (prep_area->values_buffer == NULL) {
373     P_ERROR("udb_result_prepare_result: calloc failed.");
374     BAIL_OUT(-ENOMEM);
375   }
376 
377   prep_area->metadata_pos =
378       calloc(r->metadata_num, sizeof(*prep_area->metadata_pos));
379   if (prep_area->metadata_pos == NULL) {
380     P_ERROR("udb_result_prepare_result: calloc failed.");
381     BAIL_OUT(-ENOMEM);
382   }
383 
384   prep_area->metadata_buffer =
385       calloc(r->metadata_num, sizeof(*prep_area->metadata_buffer));
386   if (prep_area->metadata_buffer == NULL) {
387     P_ERROR("udb_result_prepare_result: calloc failed.");
388     BAIL_OUT(-ENOMEM);
389   }
390 
391   /* }}} */
392 
393   /* Determine the position of the plugin instance column {{{ */
394   for (size_t i = 0; i < r->instances_num; i++) {
395     size_t j;
396 
397     for (j = 0; j < column_num; j++) {
398       if (strcasecmp(r->instances[i], column_names[j]) == 0) {
399         prep_area->instances_pos[i] = j;
400         break;
401       }
402     }
403 
404     if (j >= column_num) {
405       P_ERROR("udb_result_prepare_result: "
406               "Column `%s' could not be found.",
407               r->instances[i]);
408       BAIL_OUT(-ENOENT);
409     }
410   } /* }}} for (i = 0; i < r->instances_num; i++) */
411 
412   /* Determine the position of the value columns {{{ */
413   for (size_t i = 0; i < r->values_num; i++) {
414     size_t j;
415 
416     for (j = 0; j < column_num; j++) {
417       if (strcasecmp(r->values[i], column_names[j]) == 0) {
418         prep_area->values_pos[i] = j;
419         break;
420       }
421     }
422 
423     if (j >= column_num) {
424       P_ERROR("udb_result_prepare_result: "
425               "Column `%s' could not be found.",
426               r->values[i]);
427       BAIL_OUT(-ENOENT);
428     }
429   } /* }}} for (i = 0; i < r->values_num; i++) */
430 
431   /* Determine the position of the metadata columns {{{ */
432   for (size_t i = 0; i < r->metadata_num; i++) {
433     size_t j;
434 
435     for (j = 0; j < column_num; j++) {
436       if (strcasecmp(r->metadata[i], column_names[j]) == 0) {
437         prep_area->metadata_pos[i] = j;
438         break;
439       }
440     }
441 
442     if (j >= column_num) {
443       P_ERROR("udb_result_prepare_result: "
444               "Metadata column `%s' could not be found.",
445               r->values[i]);
446       BAIL_OUT(-ENOENT);
447     }
448   } /* }}} for (i = 0; i < r->metadata_num; i++) */
449 
450 #undef BAIL_OUT
451   return 0;
452 } /* }}} int udb_result_prepare_result */
453 
udb_result_free(udb_result_t * r)454 static void udb_result_free(udb_result_t *r) /* {{{ */
455 {
456   if (r == NULL)
457     return;
458 
459   sfree(r->type);
460   sfree(r->instance_prefix);
461 
462   for (size_t i = 0; i < r->instances_num; i++)
463     sfree(r->instances[i]);
464   sfree(r->instances);
465 
466   for (size_t i = 0; i < r->values_num; i++)
467     sfree(r->values[i]);
468   sfree(r->values);
469 
470   for (size_t i = 0; i < r->metadata_num; i++)
471     sfree(r->metadata[i]);
472   sfree(r->metadata);
473 
474   udb_result_free(r->next);
475 
476   sfree(r);
477 } /* }}} void udb_result_free */
478 
udb_result_create(const char * query_name,udb_result_t ** r_head,oconfig_item_t * ci)479 static int udb_result_create(const char *query_name, /* {{{ */
480                              udb_result_t **r_head, oconfig_item_t *ci) {
481   udb_result_t *r;
482   int status;
483 
484   if (ci->values_num != 0) {
485     P_WARNING("The `Result' block doesn't accept "
486               "any arguments. Ignoring %i argument%s.",
487               ci->values_num, (ci->values_num == 1) ? "" : "s");
488   }
489 
490   r = calloc(1, sizeof(*r));
491   if (r == NULL) {
492     P_ERROR("udb_result_create: calloc failed.");
493     return -1;
494   }
495   r->type = NULL;
496   r->instance_prefix = NULL;
497   r->instances = NULL;
498   r->values = NULL;
499   r->metadata = NULL;
500   r->next = NULL;
501 
502   /* Fill the `udb_result_t' structure.. */
503   status = 0;
504   for (int i = 0; i < ci->children_num; i++) {
505     oconfig_item_t *child = ci->children + i;
506 
507     if (strcasecmp("Type", child->key) == 0)
508       status = cf_util_get_string(child, &r->type);
509     else if (strcasecmp("InstancePrefix", child->key) == 0)
510       status = cf_util_get_string(child, &r->instance_prefix);
511     else if (strcasecmp("InstancesFrom", child->key) == 0)
512       status = udb_config_add_string(&r->instances, &r->instances_num, child);
513     else if (strcasecmp("ValuesFrom", child->key) == 0)
514       status = udb_config_add_string(&r->values, &r->values_num, child);
515     else if (strcasecmp("MetadataFrom", child->key) == 0)
516       status = udb_config_add_string(&r->metadata, &r->metadata_num, child);
517     else {
518       P_WARNING("Query `%s': Option `%s' not allowed here.", query_name,
519                 child->key);
520       status = -1;
521     }
522 
523     if (status != 0)
524       break;
525   }
526 
527   /* Check that all necessary options have been given. */
528   while (status == 0) {
529     if (r->type == NULL) {
530       P_WARNING("udb_result_create: `Type' not given for "
531                 "result in query `%s'",
532                 query_name);
533       status = -1;
534     }
535     if (r->values == NULL) {
536       P_WARNING("udb_result_create: `ValuesFrom' not given for "
537                 "result in query `%s'",
538                 query_name);
539       status = -1;
540     }
541 
542     break;
543   } /* while (status == 0) */
544 
545   if (status != 0) {
546     udb_result_free(r);
547     return -1;
548   }
549 
550   /* If all went well, add this result to the list of results. */
551   if (*r_head == NULL) {
552     *r_head = r;
553   } else {
554     udb_result_t *last;
555 
556     last = *r_head;
557     while (last->next != NULL)
558       last = last->next;
559 
560     last->next = r;
561   }
562 
563   return 0;
564 } /* }}} int udb_result_create */
565 
566 /*
567  * Query private functions
568  */
udb_query_free_one(udb_query_t * q)569 static void udb_query_free_one(udb_query_t *q) /* {{{ */
570 {
571   if (q == NULL)
572     return;
573 
574   sfree(q->name);
575   sfree(q->statement);
576   sfree(q->plugin_instance_from);
577 
578   udb_result_free(q->results);
579 
580   sfree(q);
581 } /* }}} void udb_query_free_one */
582 
583 /*
584  * Query public functions
585  */
udb_query_create(udb_query_t *** ret_query_list,size_t * ret_query_list_len,oconfig_item_t * ci,udb_query_create_callback_t cb)586 int udb_query_create(udb_query_t ***ret_query_list, /* {{{ */
587                      size_t *ret_query_list_len, oconfig_item_t *ci,
588                      udb_query_create_callback_t cb) {
589   udb_query_t **query_list;
590   size_t query_list_len;
591 
592   udb_query_t *q;
593   int status;
594 
595   if ((ret_query_list == NULL) || (ret_query_list_len == NULL))
596     return -EINVAL;
597   query_list = *ret_query_list;
598   query_list_len = *ret_query_list_len;
599 
600   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
601     P_WARNING("udb_result_create: The `Query' block "
602               "needs exactly one string argument.");
603     return -1;
604   }
605 
606   q = calloc(1, sizeof(*q));
607   if (q == NULL) {
608     P_ERROR("udb_query_create: calloc failed.");
609     return -1;
610   }
611   q->min_version = 0;
612   q->max_version = UINT_MAX;
613   q->statement = NULL;
614   q->results = NULL;
615   q->plugin_instance_from = NULL;
616 
617   status = cf_util_get_string(ci, &q->name);
618   if (status != 0) {
619     sfree(q);
620     return status;
621   }
622 
623   /* Fill the `udb_query_t' structure.. */
624   for (int i = 0; i < ci->children_num; i++) {
625     oconfig_item_t *child = ci->children + i;
626 
627     if (strcasecmp("Statement", child->key) == 0)
628       status = cf_util_get_string(child, &q->statement);
629     else if (strcasecmp("Result", child->key) == 0)
630       status = udb_result_create(q->name, &q->results, child);
631     else if (strcasecmp("MinVersion", child->key) == 0)
632       status = udb_config_set_uint(&q->min_version, child);
633     else if (strcasecmp("MaxVersion", child->key) == 0)
634       status = udb_config_set_uint(&q->max_version, child);
635     else if (strcasecmp("PluginInstanceFrom", child->key) == 0)
636       status = cf_util_get_string(child, &q->plugin_instance_from);
637 
638     /* Call custom callbacks */
639     else if (cb != NULL) {
640       status = (*cb)(q, child);
641       if (status != 0) {
642         P_WARNING("The configuration callback failed "
643                   "to handle `%s'.",
644                   child->key);
645       }
646     } else {
647       P_WARNING("Query `%s': Option `%s' not allowed here.", q->name,
648                 child->key);
649       status = -1;
650     }
651 
652     if (status != 0)
653       break;
654   }
655 
656   /* Check that all necessary options have been given. */
657   if (status == 0) {
658     if (q->statement == NULL) {
659       P_WARNING("Query `%s': No `Statement' given.", q->name);
660       status = -1;
661     }
662     if (q->results == NULL) {
663       P_WARNING("Query `%s': No (valid) `Result' block given.", q->name);
664       status = -1;
665     }
666   } /* if (status == 0) */
667 
668   /* If all went well, add this query to the list of queries within the
669    * database structure. */
670   if (status == 0) {
671     udb_query_t **temp;
672 
673     temp = realloc(query_list, sizeof(*query_list) * (query_list_len + 1));
674     if (temp == NULL) {
675       P_ERROR("udb_query_create: realloc failed");
676       status = -1;
677     } else {
678       query_list = temp;
679       query_list[query_list_len] = q;
680       query_list_len++;
681     }
682   }
683 
684   if (status != 0) {
685     udb_query_free_one(q);
686     return -1;
687   }
688 
689   *ret_query_list = query_list;
690   *ret_query_list_len = query_list_len;
691 
692   return 0;
693 } /* }}} int udb_query_create */
694 
udb_query_free(udb_query_t ** query_list,size_t query_list_len)695 void udb_query_free(udb_query_t **query_list, size_t query_list_len) /* {{{ */
696 {
697   if (query_list == NULL)
698     return;
699 
700   for (size_t i = 0; i < query_list_len; i++)
701     udb_query_free_one(query_list[i]);
702 
703   sfree(query_list);
704 } /* }}} void udb_query_free */
705 
udb_query_pick_from_list_by_name(const char * name,udb_query_t ** src_list,size_t src_list_len,udb_query_t *** dst_list,size_t * dst_list_len)706 int udb_query_pick_from_list_by_name(const char *name, /* {{{ */
707                                      udb_query_t **src_list,
708                                      size_t src_list_len,
709                                      udb_query_t ***dst_list,
710                                      size_t *dst_list_len) {
711   int num_added;
712 
713   if ((name == NULL) || (src_list == NULL) || (dst_list == NULL) ||
714       (dst_list_len == NULL)) {
715     P_ERROR("udb_query_pick_from_list_by_name: "
716             "Invalid argument.");
717     return -EINVAL;
718   }
719 
720   num_added = 0;
721   for (size_t i = 0; i < src_list_len; i++) {
722     udb_query_t **tmp_list;
723     size_t tmp_list_len;
724 
725     if (strcasecmp(name, src_list[i]->name) != 0)
726       continue;
727 
728     tmp_list_len = *dst_list_len;
729     tmp_list = realloc(*dst_list, (tmp_list_len + 1) * sizeof(udb_query_t *));
730     if (tmp_list == NULL) {
731       P_ERROR("udb_query_pick_from_list_by_name: realloc failed.");
732       return -ENOMEM;
733     }
734 
735     tmp_list[tmp_list_len] = src_list[i];
736     tmp_list_len++;
737 
738     *dst_list = tmp_list;
739     *dst_list_len = tmp_list_len;
740 
741     num_added++;
742   } /* for (i = 0; i < src_list_len; i++) */
743 
744   if (num_added <= 0) {
745     P_ERROR("Cannot find query `%s'. Make sure the <Query> "
746             "block is above the database definition!",
747             name);
748     return -ENOENT;
749   } else {
750     DEBUG("Added %i versions of query `%s'.", num_added, name);
751   }
752 
753   return 0;
754 } /* }}} int udb_query_pick_from_list_by_name */
755 
udb_query_pick_from_list(oconfig_item_t * ci,udb_query_t ** src_list,size_t src_list_len,udb_query_t *** dst_list,size_t * dst_list_len)756 int udb_query_pick_from_list(oconfig_item_t *ci, /* {{{ */
757                              udb_query_t **src_list, size_t src_list_len,
758                              udb_query_t ***dst_list, size_t *dst_list_len) {
759   const char *name;
760 
761   if ((ci == NULL) || (src_list == NULL) || (dst_list == NULL) ||
762       (dst_list_len == NULL)) {
763     P_ERROR("udb_query_pick_from_list: "
764             "Invalid argument.");
765     return -EINVAL;
766   }
767 
768   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
769     P_ERROR("The `%s' config option "
770             "needs exactly one string argument.",
771             ci->key);
772     return -1;
773   }
774   name = ci->values[0].value.string;
775 
776   return udb_query_pick_from_list_by_name(name, src_list, src_list_len,
777                                           dst_list, dst_list_len);
778 } /* }}} int udb_query_pick_from_list */
779 
udb_query_get_name(udb_query_t * q)780 const char *udb_query_get_name(udb_query_t *q) /* {{{ */
781 {
782   if (q == NULL)
783     return NULL;
784 
785   return q->name;
786 } /* }}} const char *udb_query_get_name */
787 
udb_query_get_statement(udb_query_t * q)788 const char *udb_query_get_statement(udb_query_t *q) /* {{{ */
789 {
790   if (q == NULL)
791     return NULL;
792 
793   return q->statement;
794 } /* }}} const char *udb_query_get_statement */
795 
udb_query_set_user_data(udb_query_t * q,void * user_data)796 void udb_query_set_user_data(udb_query_t *q, void *user_data) /* {{{ */
797 {
798   if (q == NULL)
799     return;
800 
801   q->user_data = user_data;
802 } /* }}} void udb_query_set_user_data */
803 
udb_query_get_user_data(udb_query_t * q)804 void *udb_query_get_user_data(udb_query_t *q) /* {{{ */
805 {
806   if (q == NULL)
807     return NULL;
808 
809   return q->user_data;
810 } /* }}} void *udb_query_get_user_data */
811 
udb_query_check_version(udb_query_t * q,unsigned int version)812 int udb_query_check_version(udb_query_t *q, unsigned int version) /* {{{ */
813 {
814   if (q == NULL)
815     return -EINVAL;
816 
817   if ((version < q->min_version) || (version > q->max_version))
818     return 0;
819 
820   return 1;
821 } /* }}} int udb_query_check_version */
822 
udb_query_finish_result(udb_query_t const * q,udb_query_preparation_area_t * prep_area)823 void udb_query_finish_result(udb_query_t const *q, /* {{{ */
824                              udb_query_preparation_area_t *prep_area) {
825   udb_result_preparation_area_t *r_area;
826   udb_result_t *r;
827 
828   if ((q == NULL) || (prep_area == NULL))
829     return;
830 
831   prep_area->column_num = 0;
832   sfree(prep_area->host);
833   sfree(prep_area->plugin);
834   sfree(prep_area->db_name);
835 
836   for (r = q->results, r_area = prep_area->result_prep_areas; r != NULL;
837        r = r->next, r_area = r_area->next) {
838     /* this may happen during error conditions of the caller */
839     if (r_area == NULL)
840       break;
841     udb_result_finish_result(r, r_area);
842   }
843 } /* }}} void udb_query_finish_result */
844 
udb_query_handle_result(udb_query_t const * q,udb_query_preparation_area_t * prep_area,char ** column_values)845 int udb_query_handle_result(udb_query_t const *q, /* {{{ */
846                             udb_query_preparation_area_t *prep_area,
847                             char **column_values) {
848   udb_result_preparation_area_t *r_area;
849   udb_result_t *r;
850   int success;
851   int status;
852 
853   if ((q == NULL) || (prep_area == NULL))
854     return -EINVAL;
855 
856   if ((prep_area->column_num < 1) || (prep_area->host == NULL) ||
857       (prep_area->plugin == NULL) || (prep_area->db_name == NULL)) {
858     P_ERROR("Query `%s': Query is not prepared; "
859             "can't handle result.",
860             q->name);
861     return -EINVAL;
862   }
863 
864 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG /* {{{ */
865   do {
866     for (size_t i = 0; i < prep_area->column_num; i++) {
867       DEBUG("udb_query_handle_result (%s, %s): "
868             "column[%" PRIsz "] = %s;",
869             prep_area->db_name, q->name, i, column_values[i]);
870     }
871   } while (0);
872 #endif /* }}} */
873 
874   success = 0;
875   for (r = q->results, r_area = prep_area->result_prep_areas; r != NULL;
876        r = r->next, r_area = r_area->next) {
877     status = udb_result_handle_result(r, prep_area, r_area, q, column_values);
878     if (status == 0)
879       success++;
880   }
881 
882   if (success == 0) {
883     P_ERROR("udb_query_handle_result (%s, %s): "
884             "All results failed.",
885             prep_area->db_name, q->name);
886     return -1;
887   }
888 
889   return 0;
890 } /* }}} int udb_query_handle_result */
891 
udb_query_prepare_result(udb_query_t const * q,udb_query_preparation_area_t * prep_area,const char * host,const char * plugin,const char * db_name,char ** column_names,size_t column_num)892 int udb_query_prepare_result(udb_query_t const *q, /* {{{ */
893                              udb_query_preparation_area_t *prep_area,
894                              const char *host, const char *plugin,
895                              const char *db_name, char **column_names,
896                              size_t column_num) {
897   udb_result_preparation_area_t *r_area;
898   udb_result_t *r;
899   int status;
900 
901   if ((q == NULL) || (prep_area == NULL))
902     return -EINVAL;
903 
904 #if COLLECT_DEBUG
905   assert(prep_area->column_num == 0);
906   assert(prep_area->host == NULL);
907   assert(prep_area->plugin == NULL);
908   assert(prep_area->db_name == NULL);
909 #endif
910 
911   prep_area->column_num = column_num;
912   prep_area->host = strdup(host);
913   prep_area->plugin = strdup(plugin);
914   prep_area->db_name = strdup(db_name);
915 
916   if ((prep_area->host == NULL) || (prep_area->plugin == NULL) ||
917       (prep_area->db_name == NULL)) {
918     P_ERROR("Query `%s': Prepare failed: Out of memory.", q->name);
919     udb_query_finish_result(q, prep_area);
920     return -ENOMEM;
921   }
922 
923 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG
924   do {
925     for (size_t i = 0; i < column_num; i++) {
926       DEBUG("udb_query_prepare_result: "
927             "query = %s; column[%" PRIsz "] = %s;",
928             q->name, i, column_names[i]);
929     }
930   } while (0);
931 #endif
932 
933   /* Determine the position of the PluginInstance column {{{ */
934   if (q->plugin_instance_from != NULL) {
935     size_t i;
936 
937     for (i = 0; i < column_num; i++) {
938       if (strcasecmp(q->plugin_instance_from, column_names[i]) == 0) {
939         prep_area->plugin_instance_pos = i;
940         break;
941       }
942     }
943 
944     if (i >= column_num) {
945       P_ERROR("udb_query_prepare_result: "
946               "Column `%s' from `PluginInstanceFrom' could not be found.",
947               q->plugin_instance_from);
948       udb_query_finish_result(q, prep_area);
949       return -ENOENT;
950     }
951   }
952   /* }}} */
953 
954   for (r = q->results, r_area = prep_area->result_prep_areas; r != NULL;
955        r = r->next, r_area = r_area->next) {
956     if (!r_area) {
957       P_ERROR("Query `%s': Invalid number of result "
958               "preparation areas.",
959               q->name);
960       udb_query_finish_result(q, prep_area);
961       return -EINVAL;
962     }
963 
964     status = udb_result_prepare_result(r, r_area, column_names, column_num);
965     if (status != 0) {
966       udb_query_finish_result(q, prep_area);
967       return status;
968     }
969   }
970 
971   return 0;
972 } /* }}} int udb_query_prepare_result */
973 
974 udb_query_preparation_area_t *
udb_query_allocate_preparation_area(udb_query_t * q)975 udb_query_allocate_preparation_area(udb_query_t *q) /* {{{ */
976 {
977   udb_query_preparation_area_t *q_area;
978   udb_result_preparation_area_t **next_r_area;
979   udb_result_t *r;
980 
981   q_area = calloc(1, sizeof(*q_area));
982   if (q_area == NULL)
983     return NULL;
984 
985   next_r_area = &q_area->result_prep_areas;
986   for (r = q->results; r != NULL; r = r->next) {
987     udb_result_preparation_area_t *r_area;
988 
989     r_area = calloc(1, sizeof(*r_area));
990     if (r_area == NULL) {
991       udb_result_preparation_area_t *a = q_area->result_prep_areas;
992 
993       while (a != NULL) {
994         udb_result_preparation_area_t *next = a->next;
995         sfree(a);
996         a = next;
997       }
998 
999       free(q_area);
1000       return NULL;
1001     }
1002 
1003     *next_r_area = r_area;
1004     next_r_area = &r_area->next;
1005   }
1006 
1007   return q_area;
1008 } /* }}} udb_query_preparation_area_t *udb_query_allocate_preparation_area */
1009 
udb_query_delete_preparation_area(udb_query_preparation_area_t * q_area)1010 void udb_query_delete_preparation_area(
1011     udb_query_preparation_area_t *q_area) /* {{{ */
1012 {
1013   udb_result_preparation_area_t *r_area;
1014 
1015   if (q_area == NULL)
1016     return;
1017 
1018   r_area = q_area->result_prep_areas;
1019   while (r_area != NULL) {
1020     udb_result_preparation_area_t *area = r_area;
1021 
1022     r_area = r_area->next;
1023 
1024     sfree(area->instances_pos);
1025     sfree(area->values_pos);
1026     sfree(area->instances_buffer);
1027     sfree(area->values_buffer);
1028     free(area);
1029   }
1030 
1031   sfree(q_area->host);
1032   sfree(q_area->plugin);
1033   sfree(q_area->db_name);
1034 
1035   free(q_area);
1036 } /* }}} void udb_query_delete_preparation_area */
1037