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