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