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