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