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