Merge branch 'collectd-5.8'
[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 ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
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   size_t *tmp;
150   size_t num;
151
152   if (1 > ci->values_num) {
153     log_err("\"%s\" expects at least one argument.", name);
154     return 1;
155   }
156
157   num = (size_t)ci->values_num;
158   for (size_t i = 0; i < num; ++i) {
159     if (OCONFIG_TYPE_NUMBER != ci->values[i].type) {
160       log_err("\"%s\" expects numerical arguments only.", name);
161       return 1;
162     }
163   }
164
165   tmp = realloc(*var, ((*len) + num) * sizeof(**var));
166   if (NULL == tmp) {
167     log_err("realloc failed: %s.", STRERRNO);
168     return -1;
169   }
170   *var = tmp;
171
172   for (size_t i = 0; i < num; ++i) {
173     (*var)[*len] = (size_t)ci->values[i].value.number;
174     (*len)++;
175   }
176
177   return 0;
178 } /* tbl_config_append_array_s */
179
180 static int tbl_config_result(tbl_t *tbl, oconfig_item_t *ci) {
181   if (0 != ci->values_num) {
182     log_err("<Result> does not expect any arguments.");
183     return 1;
184   }
185
186   tbl_result_t *res =
187       realloc(tbl->results, (tbl->results_num + 1) * sizeof(*tbl->results));
188   if (res == NULL) {
189     log_err("realloc failed: %s.", STRERRNO);
190     return -1;
191   }
192
193   tbl->results = res;
194
195   res = tbl->results + tbl->results_num;
196   tbl_result_setup(res);
197
198   for (int i = 0; i < ci->children_num; ++i) {
199     oconfig_item_t *c = ci->children + i;
200
201     if (0 == strcasecmp(c->key, "Type"))
202       tbl_config_set_s(c->key, &res->type, c);
203     else if (0 == strcasecmp(c->key, "InstancePrefix"))
204       tbl_config_set_s(c->key, &res->instance_prefix, c);
205     else if (0 == strcasecmp(c->key, "InstancesFrom"))
206       tbl_config_append_array_i(c->key, &res->instances, &res->instances_num,
207                                 c);
208     else if (0 == strcasecmp(c->key, "ValuesFrom"))
209       tbl_config_append_array_i(c->key, &res->values, &res->values_num, c);
210     else
211       log_warn("Ignoring unknown config key \"%s\" "
212                " in <Result>.",
213                c->key);
214   }
215
216   int status = 0;
217   if (NULL == res->type) {
218     log_err("No \"Type\" option specified for <Result> in table \"%s\".",
219             tbl->file);
220     status = 1;
221   }
222
223   if (NULL == res->values) {
224     log_err("No \"ValuesFrom\" option specified for <Result> in table \"%s\".",
225             tbl->file);
226     status = 1;
227   }
228
229   if (0 != status) {
230     tbl_result_clear(res);
231     return status;
232   }
233
234   tbl->results_num++;
235   return 0;
236 } /* tbl_config_result */
237
238 static int tbl_config_table(oconfig_item_t *ci) {
239   if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
240     log_err("<Table> expects a single string argument.");
241     return 1;
242   }
243
244   tbl_t *tbl = realloc(tables, (tables_num + 1) * sizeof(*tables));
245   if (NULL == tbl) {
246     log_err("realloc failed: %s.", STRERRNO);
247     return -1;
248   }
249
250   tables = tbl;
251
252   tbl = tables + tables_num;
253   tbl_setup(tbl, ci->values[0].value.string);
254
255   for (size_t i = 0; i < ((size_t)ci->children_num); ++i) {
256     oconfig_item_t *c = ci->children + i;
257
258     if (0 == strcasecmp(c->key, "Separator"))
259       tbl_config_set_s(c->key, &tbl->sep, c);
260     else if (0 == strcasecmp(c->key, "Plugin"))
261       tbl_config_set_s(c->key, &tbl->plugin_name, c);
262     else if (0 == strcasecmp(c->key, "Instance"))
263       tbl_config_set_s(c->key, &tbl->instance, c);
264     else if (0 == strcasecmp(c->key, "Result"))
265       tbl_config_result(tbl, c);
266     else
267       log_warn("Ignoring unknown config key \"%s\" "
268                "in <Table %s>.",
269                c->key, tbl->file);
270   }
271
272   int status = 0;
273   if (NULL == tbl->sep) {
274     log_err("Table \"%s\" does not specify any separator.", tbl->file);
275     status = 1;
276   } else {
277     strunescape(tbl->sep, strlen(tbl->sep) + 1);
278   }
279
280   if (NULL == tbl->instance) {
281     tbl->instance = sstrdup(tbl->file);
282     replace_special(tbl->instance, strlen(tbl->instance));
283   }
284
285   if (NULL == tbl->results) {
286     assert(tbl->results_num == 0);
287     log_err("Table \"%s\" does not specify any (valid) results.", tbl->file);
288     status = 1;
289   }
290
291   if (0 != status) {
292     tbl_clear(tbl);
293     return status;
294   }
295
296   for (size_t i = 0; i < tbl->results_num; ++i) {
297     tbl_result_t *res = tbl->results + i;
298
299     for (size_t j = 0; j < res->instances_num; ++j)
300       if (res->instances[j] > tbl->max_colnum)
301         tbl->max_colnum = res->instances[j];
302
303     for (size_t j = 0; j < res->values_num; ++j)
304       if (res->values[j] > tbl->max_colnum)
305         tbl->max_colnum = res->values[j];
306   }
307
308   tables_num++;
309   return 0;
310 } /* tbl_config_table */
311
312 static int tbl_config(oconfig_item_t *ci) {
313   for (int i = 0; i < ci->children_num; ++i) {
314     oconfig_item_t *c = ci->children + i;
315
316     if (0 == strcasecmp(c->key, "Table"))
317       tbl_config_table(c);
318     else
319       log_warn("Ignoring unknown config key \"%s\".", c->key);
320   }
321   return 0;
322 } /* tbl_config */
323
324 /*
325  * result handling
326  */
327
328 static int tbl_prepare(tbl_t *tbl) {
329   for (size_t i = 0; i < tbl->results_num; ++i) {
330     tbl_result_t *res = tbl->results + i;
331
332     res->ds = plugin_get_ds(res->type);
333     if (NULL == res->ds) {
334       log_err("Unknown type \"%s\". See types.db(5) for details.", res->type);
335       return -1;
336     }
337
338     if (res->values_num != res->ds->ds_num) {
339       log_err("Invalid type \"%s\". Expected %zu data source%s, "
340               "got %zu.",
341               res->type, res->values_num, (1 == res->values_num) ? "" : "s",
342               res->ds->ds_num);
343       return -1;
344     }
345   }
346   return 0;
347 } /* tbl_prepare */
348
349 static int tbl_finish(tbl_t *tbl) {
350   for (size_t i = 0; i < tbl->results_num; ++i)
351     tbl->results[i].ds = NULL;
352   return 0;
353 } /* tbl_finish */
354
355 static int tbl_result_dispatch(tbl_t *tbl, tbl_result_t *res, char **fields,
356                                size_t fields_num) {
357   value_list_t vl = VALUE_LIST_INIT;
358   value_t values[res->values_num];
359
360   assert(NULL != res->ds);
361   assert(res->values_num == res->ds->ds_num);
362
363   for (size_t i = 0; i < res->values_num; ++i) {
364     char *value;
365
366     assert(res->values[i] < fields_num);
367     value = fields[res->values[i]];
368
369     if (0 != parse_value(value, &values[i], res->ds->ds[i].type))
370       return -1;
371   }
372
373   vl.values = values;
374   vl.values_len = STATIC_ARRAY_SIZE(values);
375
376   sstrncpy(vl.plugin, (tbl->plugin_name != NULL) ? tbl->plugin_name : "table",
377            sizeof(vl.plugin));
378   sstrncpy(vl.plugin_instance, tbl->instance, sizeof(vl.plugin_instance));
379   sstrncpy(vl.type, res->type, sizeof(vl.type));
380
381   if (0 == res->instances_num) {
382     if (NULL != res->instance_prefix)
383       sstrncpy(vl.type_instance, res->instance_prefix,
384                sizeof(vl.type_instance));
385   } else {
386     char *instances[res->instances_num];
387     char instances_str[DATA_MAX_NAME_LEN];
388
389     for (size_t i = 0; i < res->instances_num; ++i) {
390       assert(res->instances[i] < fields_num);
391       instances[i] = fields[res->instances[i]];
392     }
393
394     strjoin(instances_str, sizeof(instances_str), instances,
395             STATIC_ARRAY_SIZE(instances), "-");
396     instances_str[sizeof(instances_str) - 1] = '\0';
397
398     vl.type_instance[sizeof(vl.type_instance) - 1] = '\0';
399     if (NULL == res->instance_prefix)
400       strncpy(vl.type_instance, instances_str, sizeof(vl.type_instance));
401     else
402       snprintf(vl.type_instance, sizeof(vl.type_instance), "%s-%s",
403                res->instance_prefix, instances_str);
404
405     if ('\0' != vl.type_instance[sizeof(vl.type_instance) - 1]) {
406       vl.type_instance[sizeof(vl.type_instance) - 1] = '\0';
407       log_warn("Truncated type instance: %s.", vl.type_instance);
408     }
409   }
410
411   plugin_dispatch_values(&vl);
412   return 0;
413 } /* tbl_result_dispatch */
414
415 static int tbl_parse_line(tbl_t *tbl, char *line, size_t len) {
416   char *fields[tbl->max_colnum + 1];
417   char *ptr, *saveptr;
418
419   size_t i = 0;
420
421   ptr = line;
422   saveptr = NULL;
423   while (NULL != (fields[i] = strtok_r(ptr, tbl->sep, &saveptr))) {
424     ptr = NULL;
425     ++i;
426
427     if (i > tbl->max_colnum)
428       break;
429   }
430
431   if (i <= tbl->max_colnum) {
432     log_warn("Not enough columns in line "
433              "(expected at least %zu, got %zu).",
434              tbl->max_colnum + 1, i);
435     return -1;
436   }
437
438   for (i = 0; i < tbl->results_num; ++i)
439     if (0 != tbl_result_dispatch(tbl, tbl->results + i, fields,
440                                  STATIC_ARRAY_SIZE(fields))) {
441       log_err("Failed to dispatch result.");
442       continue;
443     }
444   return 0;
445 } /* tbl_parse_line */
446
447 static int tbl_read_table(tbl_t *tbl) {
448   FILE *fh;
449   char buf[4096];
450
451   fh = fopen(tbl->file, "r");
452   if (NULL == fh) {
453     log_err("Failed to open file \"%s\": %s.", tbl->file, STRERRNO);
454     return -1;
455   }
456
457   buf[sizeof(buf) - 1] = '\0';
458   while (NULL != fgets(buf, sizeof(buf), fh)) {
459     if ('\0' != buf[sizeof(buf) - 1]) {
460       buf[sizeof(buf) - 1] = '\0';
461       log_warn("Table %s: Truncated line: %s", tbl->file, buf);
462     }
463
464     if (0 != tbl_parse_line(tbl, buf, sizeof(buf))) {
465       log_warn("Table %s: Failed to parse line: %s", tbl->file, buf);
466       continue;
467     }
468   }
469
470   if (0 != ferror(fh)) {
471     log_err("Failed to read from file \"%s\": %s.", tbl->file, STRERRNO);
472     fclose(fh);
473     return -1;
474   }
475
476   fclose(fh);
477   return 0;
478 } /* tbl_read_table */
479
480 /*
481  * collectd callbacks
482  */
483
484 static int tbl_read(void) {
485   int status = -1;
486
487   if (0 == tables_num)
488     return 0;
489
490   for (size_t i = 0; i < tables_num; ++i) {
491     tbl_t *tbl = tables + i;
492
493     if (0 != tbl_prepare(tbl)) {
494       log_err("Failed to prepare and parse table \"%s\".", tbl->file);
495       continue;
496     }
497
498     if (0 == tbl_read_table(tbl))
499       status = 0;
500
501     tbl_finish(tbl);
502   }
503   return status;
504 } /* tbl_read */
505
506 static int tbl_shutdown(void) {
507   for (size_t i = 0; i < tables_num; ++i)
508     tbl_clear(&tables[i]);
509   sfree(tables);
510   return 0;
511 } /* tbl_shutdown */
512
513 static int tbl_init(void) {
514   if (0 == tables_num)
515     return 0;
516
517   plugin_register_read("table", tbl_read);
518   plugin_register_shutdown("table", tbl_shutdown);
519   return 0;
520 } /* tbl_init */
521
522 void module_register(void) {
523   plugin_register_complex_config("table", tbl_config);
524   plugin_register_init("table", tbl_init);
525 } /* module_register */