Merge pull request #2618 from ajssmith/amqp1_dev1_branch
[collectd.git] / src / table.c
1 /**
2  * collectd - src/table.c
3  * Copyright (C) 2009       Sebastian Harl
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  *   Sebastian Harl <sh at tokkee.org>
25  **/
26
27 /*
28  * This module provides generic means to parse and dispatch tabular data.
29  */
30
31 #include "collectd.h"
32
33 #include "common.h"
34
35 #include "plugin.h"
36
37 #define log_err(...) ERROR("table plugin: " __VA_ARGS__)
38 #define log_warn(...) WARNING("table plugin: " __VA_ARGS__)
39
40 /*
41  * private data types
42  */
43
44 typedef struct {
45   char *type;
46   char *instance_prefix;
47   size_t *instances;
48   size_t instances_num;
49   size_t *values;
50   size_t values_num;
51
52   const data_set_t *ds;
53 } tbl_result_t;
54
55 typedef struct {
56   char *file;
57   char *sep;
58   char *plugin_name;
59   char *instance;
60
61   tbl_result_t *results;
62   size_t results_num;
63
64   size_t max_colnum;
65 } tbl_t;
66
67 static void tbl_result_setup(tbl_result_t *res) {
68   res->type = NULL;
69
70   res->instance_prefix = NULL;
71   res->instances = NULL;
72   res->instances_num = 0;
73
74   res->values = NULL;
75   res->values_num = 0;
76
77   res->ds = NULL;
78 } /* tbl_result_setup */
79
80 static void tbl_result_clear(tbl_result_t *res) {
81   if (res == NULL) {
82     return;
83   }
84
85   sfree(res->type);
86
87   sfree(res->instance_prefix);
88   sfree(res->instances);
89   res->instances_num = 0;
90
91   sfree(res->values);
92   res->values_num = 0;
93
94   res->ds = NULL;
95 } /* tbl_result_clear */
96
97 static void tbl_setup(tbl_t *tbl, char *file) {
98   tbl->file = sstrdup(file);
99   tbl->sep = NULL;
100   tbl->plugin_name = NULL;
101   tbl->instance = NULL;
102
103   tbl->results = NULL;
104   tbl->results_num = 0;
105
106   tbl->max_colnum = 0;
107 } /* tbl_setup */
108
109 static void tbl_clear(tbl_t *tbl) {
110   if (tbl == NULL) {
111     return;
112   }
113
114   sfree(tbl->file);
115   sfree(tbl->sep);
116   sfree(tbl->plugin_name);
117   sfree(tbl->instance);
118
119   /* (tbl->results == NULL) -> (tbl->results_num == 0) */
120   assert((tbl->results != NULL) || (tbl->results_num == 0));
121   for (size_t i = 0; i < tbl->results_num; ++i)
122     tbl_result_clear(tbl->results + i);
123   sfree(tbl->results);
124   tbl->results_num = 0;
125
126   tbl->max_colnum = 0;
127 } /* tbl_clear */
128
129 static tbl_t *tables;
130 static size_t tables_num;
131
132 /*
133  * configuration handling
134  */
135
136 static int tbl_config_set_s(char *name, char **var, oconfig_item_t *ci) {
137   if (ci->values_num != 1 || ci->values[0].type != OCONFIG_TYPE_STRING) {
138     log_err("\"%s\" expects a single string argument.", name);
139     return 1;
140   }
141
142   sfree(*var);
143   *var = sstrdup(ci->values[0].value.string);
144   return 0;
145 } /* tbl_config_set_separator */
146
147 static int tbl_config_append_array_i(char *name, size_t **var, size_t *len,
148                                      oconfig_item_t *ci) {
149   if (ci->values_num < 1) {
150     log_err("\"%s\" expects at least one argument.", name);
151     return 1;
152   }
153
154   size_t num = ci->values_num;
155   for (size_t i = 0; i < num; ++i) {
156     if (OCONFIG_TYPE_NUMBER != ci->values[i].type) {
157       log_err("\"%s\" expects numerical arguments only.", name);
158       return 1;
159     }
160   }
161
162   size_t *tmp = realloc(*var, ((*len) + num) * sizeof(**var));
163   if (tmp == NULL) {
164     log_err("realloc failed: %s.", STRERRNO);
165     return -1;
166   }
167   *var = tmp;
168
169   for (size_t i = 0; i < num; ++i) {
170     (*var)[*len] = (size_t)ci->values[i].value.number;
171     (*len)++;
172   }
173
174   return 0;
175 } /* tbl_config_append_array_s */
176
177 static int tbl_config_result(tbl_t *tbl, oconfig_item_t *ci) {
178   if (ci->values_num != 0) {
179     log_err("<Result> does not expect any arguments.");
180     return 1;
181   }
182
183   tbl_result_t *res =
184       realloc(tbl->results, (tbl->results_num + 1) * sizeof(*tbl->results));
185   if (res == NULL) {
186     log_err("realloc failed: %s.", STRERRNO);
187     return -1;
188   }
189
190   tbl->results = res;
191
192   res = tbl->results + tbl->results_num;
193   tbl_result_setup(res);
194
195   for (int i = 0; i < ci->children_num; ++i) {
196     oconfig_item_t *c = ci->children + i;
197
198     if (strcasecmp(c->key, "Type") == 0)
199       tbl_config_set_s(c->key, &res->type, c);
200     else if (strcasecmp(c->key, "InstancePrefix") == 0)
201       tbl_config_set_s(c->key, &res->instance_prefix, c);
202     else if (strcasecmp(c->key, "InstancesFrom") == 0)
203       tbl_config_append_array_i(c->key, &res->instances, &res->instances_num,
204                                 c);
205     else if (strcasecmp(c->key, "ValuesFrom") == 0)
206       tbl_config_append_array_i(c->key, &res->values, &res->values_num, c);
207     else
208       log_warn("Ignoring unknown config key \"%s\" "
209                " in <Result>.",
210                c->key);
211   }
212
213   int status = 0;
214   if (res->type == NULL) {
215     log_err("No \"Type\" option specified for <Result> in table \"%s\".",
216             tbl->file);
217     status = 1;
218   }
219
220   if (res->values == NULL) {
221     log_err("No \"ValuesFrom\" option specified for <Result> in table \"%s\".",
222             tbl->file);
223     status = 1;
224   }
225
226   if (status != 0) {
227     tbl_result_clear(res);
228     return status;
229   }
230
231   tbl->results_num++;
232   return 0;
233 } /* tbl_config_result */
234
235 static int tbl_config_table(oconfig_item_t *ci) {
236   if (ci->values_num != 1 || ci->values[0].type != OCONFIG_TYPE_STRING) {
237     log_err("<Table> expects a single string argument.");
238     return 1;
239   }
240
241   tbl_t *tbl = realloc(tables, (tables_num + 1) * sizeof(*tables));
242   if (tbl == NULL) {
243     log_err("realloc failed: %s.", STRERRNO);
244     return -1;
245   }
246
247   tables = tbl;
248
249   tbl = tables + tables_num;
250   tbl_setup(tbl, ci->values[0].value.string);
251
252   for (int i = 0; i < ci->children_num; i++) {
253     oconfig_item_t *c = ci->children + i;
254
255     if (strcasecmp(c->key, "Separator") == 0)
256       tbl_config_set_s(c->key, &tbl->sep, c);
257     else if (strcasecmp(c->key, "Plugin") == 0)
258       tbl_config_set_s(c->key, &tbl->plugin_name, c);
259     else if (strcasecmp(c->key, "Instance") == 0)
260       tbl_config_set_s(c->key, &tbl->instance, c);
261     else if (strcasecmp(c->key, "Result") == 0)
262       tbl_config_result(tbl, c);
263     else
264       log_warn("Ignoring unknown config key \"%s\" "
265                "in <Table %s>.",
266                c->key, tbl->file);
267   }
268
269   int status = 0;
270   if (tbl->sep == NULL) {
271     log_err("Table \"%s\" does not specify any separator.", tbl->file);
272     status = 1;
273   } else {
274     strunescape(tbl->sep, strlen(tbl->sep) + 1);
275   }
276
277   if (tbl->instance == NULL) {
278     tbl->instance = sstrdup(tbl->file);
279     replace_special(tbl->instance, strlen(tbl->instance));
280   }
281
282   if (tbl->results == NULL) {
283     assert(tbl->results_num == 0);
284     log_err("Table \"%s\" does not specify any (valid) results.", tbl->file);
285     status = 1;
286   }
287
288   if (status != 0) {
289     tbl_clear(tbl);
290     return status;
291   }
292
293   for (size_t i = 0; i < tbl->results_num; ++i) {
294     tbl_result_t *res = tbl->results + i;
295
296     for (size_t j = 0; j < res->instances_num; ++j)
297       if (res->instances[j] > tbl->max_colnum)
298         tbl->max_colnum = res->instances[j];
299
300     for (size_t j = 0; j < res->values_num; ++j)
301       if (res->values[j] > tbl->max_colnum)
302         tbl->max_colnum = res->values[j];
303   }
304
305   tables_num++;
306   return 0;
307 } /* tbl_config_table */
308
309 static int tbl_config(oconfig_item_t *ci) {
310   for (int i = 0; i < ci->children_num; ++i) {
311     oconfig_item_t *c = ci->children + i;
312
313     if (strcasecmp(c->key, "Table") == 0)
314       tbl_config_table(c);
315     else
316       log_warn("Ignoring unknown config key \"%s\".", c->key);
317   }
318   return 0;
319 } /* tbl_config */
320
321 /*
322  * result handling
323  */
324
325 static int tbl_prepare(tbl_t *tbl) {
326   for (size_t i = 0; i < tbl->results_num; ++i) {
327     tbl_result_t *res = tbl->results + i;
328
329     res->ds = plugin_get_ds(res->type);
330     if (res->ds == NULL) {
331       log_err("Unknown type \"%s\". See types.db(5) for details.", res->type);
332       return -1;
333     }
334
335     if (res->values_num != res->ds->ds_num) {
336       log_err("Invalid type \"%s\". Expected %" PRIsz " data source%s, "
337               "got %" PRIsz ".",
338               res->type, res->values_num, (1 == res->values_num) ? "" : "s",
339               res->ds->ds_num);
340       return -1;
341     }
342   }
343   return 0;
344 } /* tbl_prepare */
345
346 static int tbl_finish(tbl_t *tbl) {
347   for (size_t i = 0; i < tbl->results_num; ++i)
348     tbl->results[i].ds = NULL;
349   return 0;
350 } /* tbl_finish */
351
352 static int tbl_result_dispatch(tbl_t *tbl, tbl_result_t *res, char **fields,
353                                size_t fields_num) {
354   value_list_t vl = VALUE_LIST_INIT;
355   value_t values[res->values_num];
356
357   assert(res->ds);
358   assert(res->values_num == res->ds->ds_num);
359
360   for (size_t i = 0; i < res->values_num; ++i) {
361     assert(res->values[i] < fields_num);
362     char *value = fields[res->values[i]];
363     if (parse_value(value, &values[i], res->ds->ds[i].type) != 0)
364       return -1;
365   }
366
367   vl.values = values;
368   vl.values_len = STATIC_ARRAY_SIZE(values);
369
370   sstrncpy(vl.plugin, (tbl->plugin_name != NULL) ? tbl->plugin_name : "table",
371            sizeof(vl.plugin));
372   sstrncpy(vl.plugin_instance, tbl->instance, sizeof(vl.plugin_instance));
373   sstrncpy(vl.type, res->type, sizeof(vl.type));
374
375   if (res->instances_num == 0) {
376     if (res->instance_prefix)
377       sstrncpy(vl.type_instance, res->instance_prefix,
378                sizeof(vl.type_instance));
379   } else {
380     char *instances[res->instances_num];
381     char instances_str[DATA_MAX_NAME_LEN];
382
383     for (size_t i = 0; i < res->instances_num; ++i) {
384       assert(res->instances[i] < fields_num);
385       instances[i] = fields[res->instances[i]];
386     }
387
388     strjoin(instances_str, sizeof(instances_str), instances,
389             STATIC_ARRAY_SIZE(instances), "-");
390     instances_str[sizeof(instances_str) - 1] = '\0';
391
392     int r;
393     if (res->instance_prefix == NULL)
394       r = snprintf(vl.type_instance, sizeof(vl.type_instance), "%s",
395                    instances_str);
396     else
397       r = snprintf(vl.type_instance, sizeof(vl.type_instance), "%s-%s",
398                    res->instance_prefix, instances_str);
399     if ((size_t)r >= sizeof(vl.type_instance))
400       log_warn("Truncated type instance: %s.", vl.type_instance);
401   }
402
403   plugin_dispatch_values(&vl);
404   return 0;
405 } /* tbl_result_dispatch */
406
407 static int tbl_parse_line(tbl_t *tbl, char *line, size_t len) {
408   char *fields[tbl->max_colnum + 1];
409   size_t i = 0;
410
411   char *ptr = line;
412   char *saveptr = NULL;
413   while ((fields[i] = strtok_r(ptr, tbl->sep, &saveptr)) != NULL) {
414     ptr = NULL;
415     i++;
416
417     if (i > tbl->max_colnum)
418       break;
419   }
420
421   if (i <= tbl->max_colnum) {
422     log_warn("Not enough columns in line "
423              "(expected at least %" PRIsz ", got %" PRIsz ").",
424              tbl->max_colnum + 1, i);
425     return -1;
426   }
427
428   for (i = 0; i < tbl->results_num; ++i)
429     if (tbl_result_dispatch(tbl, tbl->results + i, fields,
430                             STATIC_ARRAY_SIZE(fields)) != 0) {
431       log_err("Failed to dispatch result.");
432       continue;
433     }
434   return 0;
435 } /* tbl_parse_line */
436
437 static int tbl_read_table(tbl_t *tbl) {
438   char buf[4096];
439
440   FILE *fh = fopen(tbl->file, "r");
441   if (fh == NULL) {
442     log_err("Failed to open file \"%s\": %s.", tbl->file, STRERRNO);
443     return -1;
444   }
445
446   buf[sizeof(buf) - 1] = '\0';
447   while (fgets(buf, sizeof(buf), fh) != NULL) {
448     if (buf[sizeof(buf) - 1] != '\0') {
449       buf[sizeof(buf) - 1] = '\0';
450       log_warn("Table %s: Truncated line: %s", tbl->file, buf);
451     }
452
453     if (tbl_parse_line(tbl, buf, sizeof(buf)) != 0) {
454       log_warn("Table %s: Failed to parse line: %s", tbl->file, buf);
455       continue;
456     }
457   }
458
459   if (ferror(fh) != 0) {
460     log_err("Failed to read from file \"%s\": %s.", tbl->file, STRERRNO);
461     fclose(fh);
462     return -1;
463   }
464
465   fclose(fh);
466   return 0;
467 } /* tbl_read_table */
468
469 /*
470  * collectd callbacks
471  */
472
473 static int tbl_read(void) {
474   int status = -1;
475
476   if (tables_num == 0)
477     return 0;
478
479   for (size_t i = 0; i < tables_num; ++i) {
480     tbl_t *tbl = tables + i;
481
482     if (tbl_prepare(tbl) != 0) {
483       log_err("Failed to prepare and parse table \"%s\".", tbl->file);
484       continue;
485     }
486
487     if (tbl_read_table(tbl) == 0)
488       status = 0;
489
490     tbl_finish(tbl);
491   }
492   return status;
493 } /* tbl_read */
494
495 static int tbl_shutdown(void) {
496   for (size_t i = 0; i < tables_num; ++i)
497     tbl_clear(&tables[i]);
498   sfree(tables);
499   return 0;
500 } /* tbl_shutdown */
501
502 static int tbl_init(void) {
503   if (tables_num == 0)
504     return 0;
505
506   plugin_register_read("table", tbl_read);
507   plugin_register_shutdown("table", tbl_shutdown);
508   return 0;
509 } /* tbl_init */
510
511 void module_register(void) {
512   plugin_register_complex_config("table", tbl_config);
513   plugin_register_init("table", tbl_init);
514 } /* module_register */