aggregation plugin: modernize the code a bit
[collectd.git] / src / aggregation.c
1 /**
2  * collectd - src/aggregation.c
3  * Copyright (C) 2012       Florian Forster
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  *   Florian Forster <octo at collectd.org>
25  **/
26
27 #include "collectd.h"
28
29 #include "common.h"
30 #include "meta_data.h"
31 #include "plugin.h"
32 #include "utils_cache.h" /* for uc_get_rate() */
33 #include "utils_subst.h"
34 #include "utils_vl_lookup.h"
35
36 #define AGG_MATCHES_ALL(str) (strcmp("/.*/", str) == 0)
37 #define AGG_FUNC_PLACEHOLDER "%{aggregation}"
38
39 struct aggregation_s /* {{{ */
40 {
41   lookup_identifier_t ident;
42   unsigned int group_by;
43
44   unsigned int regex_fields;
45
46   char *set_host;
47   char *set_plugin;
48   char *set_plugin_instance;
49   char *set_type_instance;
50
51   _Bool calc_num;
52   _Bool calc_sum;
53   _Bool calc_average;
54   _Bool calc_min;
55   _Bool calc_max;
56   _Bool calc_stddev;
57 }; /* }}} */
58 typedef struct aggregation_s aggregation_t;
59
60 struct agg_instance_s;
61 typedef struct agg_instance_s agg_instance_t;
62 struct agg_instance_s /* {{{ */
63 {
64   pthread_mutex_t lock;
65   lookup_identifier_t ident;
66
67   int ds_type;
68
69   derive_t num;
70   gauge_t sum;
71   gauge_t squares_sum;
72
73   gauge_t min;
74   gauge_t max;
75
76   rate_to_value_state_t *state_num;
77   rate_to_value_state_t *state_sum;
78   rate_to_value_state_t *state_average;
79   rate_to_value_state_t *state_min;
80   rate_to_value_state_t *state_max;
81   rate_to_value_state_t *state_stddev;
82
83   agg_instance_t *next;
84 }; /* }}} */
85
86 static lookup_t *lookup = NULL;
87
88 static pthread_mutex_t agg_instance_list_lock = PTHREAD_MUTEX_INITIALIZER;
89 static agg_instance_t *agg_instance_list_head = NULL;
90
91 static _Bool agg_is_regex(char const *str) /* {{{ */
92 {
93   if (str == NULL)
94     return 0;
95
96   size_t len = strlen(str);
97   if (len < 3)
98     return 0;
99
100   if ((str[0] == '/') && (str[len - 1] == '/'))
101     return 1;
102   else
103     return 0;
104 } /* }}} _Bool agg_is_regex */
105
106 static void agg_destroy(aggregation_t *agg) /* {{{ */
107 {
108   sfree(agg);
109 } /* }}} void agg_destroy */
110
111 /* Frees all dynamically allocated memory within the instance. */
112 static void agg_instance_destroy(agg_instance_t *inst) /* {{{ */
113 {
114   if (inst == NULL)
115     return;
116
117   /* Remove this instance from the global list of instances. */
118   pthread_mutex_lock(&agg_instance_list_lock);
119   if (agg_instance_list_head == inst)
120     agg_instance_list_head = inst->next;
121   else if (agg_instance_list_head != NULL) {
122     agg_instance_t *prev = agg_instance_list_head;
123     while ((prev != NULL) && (prev->next != inst))
124       prev = prev->next;
125     if (prev != NULL)
126       prev->next = inst->next;
127   }
128   pthread_mutex_unlock(&agg_instance_list_lock);
129
130   sfree(inst->state_num);
131   sfree(inst->state_sum);
132   sfree(inst->state_average);
133   sfree(inst->state_min);
134   sfree(inst->state_max);
135   sfree(inst->state_stddev);
136
137   memset(inst, 0, sizeof(*inst));
138   inst->ds_type = -1;
139   inst->min = NAN;
140   inst->max = NAN;
141 } /* }}} void agg_instance_destroy */
142
143 static int agg_instance_create_name(agg_instance_t *inst, /* {{{ */
144                                     value_list_t const *vl,
145                                     aggregation_t const *agg) {
146 #define COPY_FIELD(buffer, buffer_size, field, group_mask, all_value)          \
147   do {                                                                         \
148     if (agg->set_##field != NULL)                                              \
149       sstrncpy(buffer, agg->set_##field, buffer_size);                         \
150     else if ((agg->regex_fields & group_mask) && (agg->group_by & group_mask)) \
151       sstrncpy(buffer, vl->field, buffer_size);                                \
152     else if ((agg->regex_fields & group_mask) &&                               \
153              (AGG_MATCHES_ALL(agg->ident.field)))                              \
154       sstrncpy(buffer, all_value, buffer_size);                                \
155     else                                                                       \
156       sstrncpy(buffer, agg->ident.field, buffer_size);                         \
157   } while (0)
158
159   /* Host */
160   COPY_FIELD(inst->ident.host, sizeof(inst->ident.host), host, LU_GROUP_BY_HOST,
161              "global");
162
163   /* Plugin */
164   if (agg->set_plugin != NULL)
165     sstrncpy(inst->ident.plugin, agg->set_plugin, sizeof(inst->ident.plugin));
166   else
167     sstrncpy(inst->ident.plugin, "aggregation", sizeof(inst->ident.plugin));
168
169   /* Plugin instance */
170   if (agg->set_plugin_instance != NULL)
171     sstrncpy(inst->ident.plugin_instance, agg->set_plugin_instance,
172              sizeof(inst->ident.plugin_instance));
173   else {
174     char tmp_plugin[DATA_MAX_NAME_LEN];
175     char tmp_plugin_instance[DATA_MAX_NAME_LEN] = "";
176
177     if ((agg->regex_fields & LU_GROUP_BY_PLUGIN) &&
178         (agg->group_by & LU_GROUP_BY_PLUGIN))
179       sstrncpy(tmp_plugin, vl->plugin, sizeof(tmp_plugin));
180     else if ((agg->regex_fields & LU_GROUP_BY_PLUGIN) &&
181              (AGG_MATCHES_ALL(agg->ident.plugin)))
182       sstrncpy(tmp_plugin, "", sizeof(tmp_plugin));
183     else
184       sstrncpy(tmp_plugin, agg->ident.plugin, sizeof(tmp_plugin));
185
186     if ((agg->regex_fields & LU_GROUP_BY_PLUGIN_INSTANCE) &&
187         (agg->group_by & LU_GROUP_BY_PLUGIN_INSTANCE))
188       sstrncpy(tmp_plugin_instance, vl->plugin_instance,
189                sizeof(tmp_plugin_instance));
190     else if ((agg->regex_fields & LU_GROUP_BY_PLUGIN_INSTANCE) &&
191              (AGG_MATCHES_ALL(agg->ident.plugin_instance)))
192       sstrncpy(tmp_plugin_instance, "", sizeof(tmp_plugin_instance));
193     else
194       sstrncpy(tmp_plugin_instance, agg->ident.plugin_instance,
195                sizeof(tmp_plugin_instance));
196
197     if ((strcmp("", tmp_plugin) == 0) && (strcmp("", tmp_plugin_instance) == 0))
198       sstrncpy(inst->ident.plugin_instance, AGG_FUNC_PLACEHOLDER,
199                sizeof(inst->ident.plugin_instance));
200     else if (strcmp("", tmp_plugin) != 0)
201       snprintf(inst->ident.plugin_instance, sizeof(inst->ident.plugin_instance),
202                "%s-%s", tmp_plugin, AGG_FUNC_PLACEHOLDER);
203     else if (strcmp("", tmp_plugin_instance) != 0)
204       snprintf(inst->ident.plugin_instance, sizeof(inst->ident.plugin_instance),
205                "%s-%s", tmp_plugin_instance, AGG_FUNC_PLACEHOLDER);
206     else
207       snprintf(inst->ident.plugin_instance, sizeof(inst->ident.plugin_instance),
208                "%s-%s-%s", tmp_plugin, tmp_plugin_instance,
209                AGG_FUNC_PLACEHOLDER);
210   }
211
212   /* Type */
213   sstrncpy(inst->ident.type, agg->ident.type, sizeof(inst->ident.type));
214
215   /* Type instance */
216   COPY_FIELD(inst->ident.type_instance, sizeof(inst->ident.type_instance),
217              type_instance, LU_GROUP_BY_TYPE_INSTANCE, "");
218
219 #undef COPY_FIELD
220
221   return 0;
222 } /* }}} int agg_instance_create_name */
223
224 /* Create a new aggregation instance. */
225 static agg_instance_t *agg_instance_create(data_set_t const *ds, /* {{{ */
226                                            value_list_t const *vl,
227                                            aggregation_t *agg) {
228   DEBUG("aggregation plugin: Creating new instance.");
229
230   agg_instance_t *inst = calloc(1, sizeof(*inst));
231   if (inst == NULL) {
232     ERROR("aggregation plugin: calloc() failed.");
233     return NULL;
234   }
235   pthread_mutex_init(&inst->lock, /* attr = */ NULL);
236
237   inst->ds_type = ds->ds[0].type;
238
239   agg_instance_create_name(inst, vl, agg);
240
241   inst->min = NAN;
242   inst->max = NAN;
243
244 #define INIT_STATE(field)                                                      \
245   do {                                                                         \
246     inst->state_##field = NULL;                                                \
247     if (agg->calc_##field) {                                                   \
248       inst->state_##field = calloc(1, sizeof(*inst->state_##field));           \
249       if (inst->state_##field == NULL) {                                       \
250         agg_instance_destroy(inst);                                            \
251         free(inst);                                                            \
252         ERROR("aggregation plugin: calloc() failed.");                         \
253         return NULL;                                                           \
254       }                                                                        \
255     }                                                                          \
256   } while (0)
257
258   INIT_STATE(num);
259   INIT_STATE(sum);
260   INIT_STATE(average);
261   INIT_STATE(min);
262   INIT_STATE(max);
263   INIT_STATE(stddev);
264
265 #undef INIT_STATE
266
267   pthread_mutex_lock(&agg_instance_list_lock);
268   inst->next = agg_instance_list_head;
269   agg_instance_list_head = inst;
270   pthread_mutex_unlock(&agg_instance_list_lock);
271
272   return inst;
273 } /* }}} agg_instance_t *agg_instance_create */
274
275 /* Update the num, sum, min, max, ... fields of the aggregation instance, if
276  * the rate of the value list is available. Value lists with more than one data
277  * source are not supported and will return an error. Returns zero on success
278  * and non-zero otherwise. */
279 static int agg_instance_update(agg_instance_t *inst, /* {{{ */
280                                data_set_t const *ds, value_list_t const *vl) {
281   if (ds->ds_num != 1) {
282     ERROR("aggregation plugin: The \"%s\" type (data set) has more than one "
283           "data source. This is currently not supported by this plugin. "
284           "Sorry.",
285           ds->type);
286     return EINVAL;
287   }
288
289   gauge_t *rate = uc_get_rate(ds, vl);
290   if (rate == NULL) {
291     char ident[6 * DATA_MAX_NAME_LEN];
292     FORMAT_VL(ident, sizeof(ident), vl);
293     ERROR("aggregation plugin: Unable to read the current rate of \"%s\".",
294           ident);
295     return ENOENT;
296   }
297
298   if (isnan(rate[0])) {
299     sfree(rate);
300     return 0;
301   }
302
303   pthread_mutex_lock(&inst->lock);
304
305   inst->num++;
306   inst->sum += rate[0];
307   inst->squares_sum += (rate[0] * rate[0]);
308
309   if (isnan(inst->min) || (inst->min > rate[0]))
310     inst->min = rate[0];
311   if (isnan(inst->max) || (inst->max < rate[0]))
312     inst->max = rate[0];
313
314   pthread_mutex_unlock(&inst->lock);
315
316   sfree(rate);
317   return 0;
318 } /* }}} int agg_instance_update */
319
320 static int agg_instance_read_func(agg_instance_t *inst, /* {{{ */
321                                   char const *func, gauge_t rate,
322                                   rate_to_value_state_t *state,
323                                   value_list_t *vl, char const *pi_prefix,
324                                   cdtime_t t) {
325   if (pi_prefix[0] != 0)
326     subst_string(vl->plugin_instance, sizeof(vl->plugin_instance), pi_prefix,
327                  AGG_FUNC_PLACEHOLDER, func);
328   else
329     sstrncpy(vl->plugin_instance, func, sizeof(vl->plugin_instance));
330
331   value_t v;
332
333   int status = rate_to_value(&v, rate, state, inst->ds_type, t);
334   if (status != 0) {
335     /* If this is the first iteration and rate_to_value() was asked to return a
336      * COUNTER or a DERIVE, it will return EAGAIN. Catch this and handle
337      * gracefully. */
338     if (status == EAGAIN)
339       return 0;
340
341     WARNING("aggregation plugin: rate_to_value failed with status %i.", status);
342     return -1;
343   }
344
345   vl->values = &v;
346   vl->values_len = 1;
347
348   plugin_dispatch_values(vl);
349
350   vl->values = NULL;
351   vl->values_len = 0;
352
353   return 0;
354 } /* }}} int agg_instance_read_func */
355
356 static int agg_instance_read(agg_instance_t *inst, cdtime_t t) /* {{{ */
357 {
358   value_list_t vl = VALUE_LIST_INIT;
359
360   /* Pre-set all the fields in the value list that will not change per
361    * aggregation type (sum, average, ...). The struct will be re-used and must
362    * therefore be dispatched using the "secure" function. */
363
364   vl.time = t;
365   vl.interval = 0;
366
367   vl.meta = meta_data_create();
368   if (vl.meta == NULL) {
369     ERROR("aggregation plugin: meta_data_create failed.");
370     return -1;
371   }
372   meta_data_add_boolean(vl.meta, "aggregation:created", 1);
373
374   sstrncpy(vl.host, inst->ident.host, sizeof(vl.host));
375   sstrncpy(vl.plugin, inst->ident.plugin, sizeof(vl.plugin));
376   sstrncpy(vl.type, inst->ident.type, sizeof(vl.type));
377   sstrncpy(vl.type_instance, inst->ident.type_instance,
378            sizeof(vl.type_instance));
379
380 #define READ_FUNC(func, rate)                                                  \
381   do {                                                                         \
382     if (inst->state_##func != NULL) {                                          \
383       agg_instance_read_func(inst, #func, rate, inst->state_##func, &vl,       \
384                              inst->ident.plugin_instance, t);                  \
385     }                                                                          \
386   } while (0)
387
388   pthread_mutex_lock(&inst->lock);
389
390   READ_FUNC(num, (gauge_t)inst->num);
391
392   /* All other aggregations are only defined when there have been any values
393    * at all. */
394   if (inst->num > 0) {
395     READ_FUNC(sum, inst->sum);
396     READ_FUNC(average, (inst->sum / ((gauge_t)inst->num)));
397     READ_FUNC(min, inst->min);
398     READ_FUNC(max, inst->max);
399     READ_FUNC(stddev, sqrt((((gauge_t)inst->num) * inst->squares_sum) -
400                            (inst->sum * inst->sum)) /
401                           ((gauge_t)inst->num));
402   }
403
404   /* Reset internal state. */
405   inst->num = 0;
406   inst->sum = 0.0;
407   inst->squares_sum = 0.0;
408   inst->min = NAN;
409   inst->max = NAN;
410
411   pthread_mutex_unlock(&inst->lock);
412
413   meta_data_destroy(vl.meta);
414   vl.meta = NULL;
415
416   return 0;
417 } /* }}} int agg_instance_read */
418
419 /* lookup_class_callback_t for utils_vl_lookup */
420 static void *agg_lookup_class_callback(/* {{{ */
421                                        data_set_t const *ds,
422                                        value_list_t const *vl,
423                                        void *user_class) {
424   return agg_instance_create(ds, vl, (aggregation_t *)user_class);
425 } /* }}} void *agg_class_callback */
426
427 /* lookup_obj_callback_t for utils_vl_lookup */
428 static int agg_lookup_obj_callback(data_set_t const *ds, /* {{{ */
429                                    value_list_t const *vl,
430                                    __attribute__((unused)) void *user_class,
431                                    void *user_obj) {
432   return agg_instance_update((agg_instance_t *)user_obj, ds, vl);
433 } /* }}} int agg_lookup_obj_callback */
434
435 /* lookup_free_class_callback_t for utils_vl_lookup */
436 static void agg_lookup_free_class_callback(void *user_class) /* {{{ */
437 {
438   agg_destroy((aggregation_t *)user_class);
439 } /* }}} void agg_lookup_free_class_callback */
440
441 /* lookup_free_obj_callback_t for utils_vl_lookup */
442 static void agg_lookup_free_obj_callback(void *user_obj) /* {{{ */
443 {
444   agg_instance_destroy((agg_instance_t *)user_obj);
445 } /* }}} void agg_lookup_free_obj_callback */
446
447 /*
448  * <Plugin "aggregation">
449  *   <Aggregation>
450  *     Plugin "cpu"
451  *     Type "cpu"
452  *
453  *     GroupBy Host
454  *     GroupBy TypeInstance
455  *
456  *     CalculateNum true
457  *     CalculateSum true
458  *     CalculateAverage true
459  *     CalculateMinimum true
460  *     CalculateMaximum true
461  *     CalculateStddev true
462  *   </Aggregation>
463  * </Plugin>
464  */
465 static int agg_config_handle_group_by(oconfig_item_t const *ci, /* {{{ */
466                                       aggregation_t *agg) {
467   for (int i = 0; i < ci->values_num; i++) {
468     if (ci->values[i].type != OCONFIG_TYPE_STRING) {
469       ERROR("aggregation plugin: Argument %i of the \"GroupBy\" option "
470             "is not a string.",
471             i + 1);
472       continue;
473     }
474
475     const char *value = ci->values[i].value.string;
476
477     if (strcasecmp("Host", value) == 0)
478       agg->group_by |= LU_GROUP_BY_HOST;
479     else if (strcasecmp("Plugin", value) == 0)
480       agg->group_by |= LU_GROUP_BY_PLUGIN;
481     else if (strcasecmp("PluginInstance", value) == 0)
482       agg->group_by |= LU_GROUP_BY_PLUGIN_INSTANCE;
483     else if (strcasecmp("TypeInstance", value) == 0)
484       agg->group_by |= LU_GROUP_BY_TYPE_INSTANCE;
485     else if (strcasecmp("Type", value) == 0)
486       ERROR("aggregation plugin: Grouping by type is not supported.");
487     else
488       WARNING("aggregation plugin: The \"%s\" argument to the \"GroupBy\" "
489               "option is invalid and will be ignored.",
490               value);
491   } /* for (ci->values) */
492
493   return 0;
494 } /* }}} int agg_config_handle_group_by */
495
496 static int agg_config_aggregation(oconfig_item_t *ci) /* {{{ */
497 {
498   aggregation_t *agg = calloc(1, sizeof(*agg));
499   if (agg == NULL) {
500     ERROR("aggregation plugin: calloc failed.");
501     return -1;
502   }
503
504   sstrncpy(agg->ident.host, "/.*/", sizeof(agg->ident.host));
505   sstrncpy(agg->ident.plugin, "/.*/", sizeof(agg->ident.plugin));
506   sstrncpy(agg->ident.plugin_instance, "/.*/",
507            sizeof(agg->ident.plugin_instance));
508   sstrncpy(agg->ident.type, "/.*/", sizeof(agg->ident.type));
509   sstrncpy(agg->ident.type_instance, "/.*/", sizeof(agg->ident.type_instance));
510
511   for (int i = 0; i < ci->children_num; i++) {
512     oconfig_item_t *child = ci->children + i;
513     int status = 0;
514
515     if (strcasecmp("Host", child->key) == 0)
516       status = cf_util_get_string_buffer(child, agg->ident.host,
517                                          sizeof(agg->ident.host));
518     else if (strcasecmp("Plugin", child->key) == 0)
519       status = cf_util_get_string_buffer(child, agg->ident.plugin,
520                                          sizeof(agg->ident.plugin));
521     else if (strcasecmp("PluginInstance", child->key) == 0)
522       status = cf_util_get_string_buffer(child, agg->ident.plugin_instance,
523                                          sizeof(agg->ident.plugin_instance));
524     else if (strcasecmp("Type", child->key) == 0)
525       status = cf_util_get_string_buffer(child, agg->ident.type,
526                                          sizeof(agg->ident.type));
527     else if (strcasecmp("TypeInstance", child->key) == 0)
528       status = cf_util_get_string_buffer(child, agg->ident.type_instance,
529                                          sizeof(agg->ident.type_instance));
530     else if (strcasecmp("SetHost", child->key) == 0)
531       status = cf_util_get_string(child, &agg->set_host);
532     else if (strcasecmp("SetPlugin", child->key) == 0)
533       status = cf_util_get_string(child, &agg->set_plugin);
534     else if (strcasecmp("SetPluginInstance", child->key) == 0)
535       status = cf_util_get_string(child, &agg->set_plugin_instance);
536     else if (strcasecmp("SetTypeInstance", child->key) == 0)
537       status = cf_util_get_string(child, &agg->set_type_instance);
538     else if (strcasecmp("GroupBy", child->key) == 0)
539       status = agg_config_handle_group_by(child, agg);
540     else if (strcasecmp("CalculateNum", child->key) == 0)
541       status = cf_util_get_boolean(child, &agg->calc_num);
542     else if (strcasecmp("CalculateSum", child->key) == 0)
543       status = cf_util_get_boolean(child, &agg->calc_sum);
544     else if (strcasecmp("CalculateAverage", child->key) == 0)
545       status = cf_util_get_boolean(child, &agg->calc_average);
546     else if (strcasecmp("CalculateMinimum", child->key) == 0)
547       status = cf_util_get_boolean(child, &agg->calc_min);
548     else if (strcasecmp("CalculateMaximum", child->key) == 0)
549       status = cf_util_get_boolean(child, &agg->calc_max);
550     else if (strcasecmp("CalculateStddev", child->key) == 0)
551       status = cf_util_get_boolean(child, &agg->calc_stddev);
552     else
553       WARNING("aggregation plugin: The \"%s\" key is not allowed inside "
554               "<Aggregation /> blocks and will be ignored.",
555               child->key);
556
557     if (status != 0) {
558       sfree(agg);
559       return status;
560     }
561   } /* for (int i = 0; i < ci->children_num; i++) */
562
563   if (agg_is_regex(agg->ident.host))
564     agg->regex_fields |= LU_GROUP_BY_HOST;
565   if (agg_is_regex(agg->ident.plugin))
566     agg->regex_fields |= LU_GROUP_BY_PLUGIN;
567   if (agg_is_regex(agg->ident.plugin_instance))
568     agg->regex_fields |= LU_GROUP_BY_PLUGIN_INSTANCE;
569   if (agg_is_regex(agg->ident.type_instance))
570     agg->regex_fields |= LU_GROUP_BY_TYPE_INSTANCE;
571
572   /* Sanity checking */
573   _Bool is_valid = 1;
574   if (strcmp("/.*/", agg->ident.type) == 0) /* {{{ */
575   {
576     ERROR("aggregation plugin: It appears you did not specify the required "
577           "\"Type\" option in this aggregation. "
578           "(Host \"%s\", Plugin \"%s\", PluginInstance \"%s\", "
579           "Type \"%s\", TypeInstance \"%s\")",
580           agg->ident.host, agg->ident.plugin, agg->ident.plugin_instance,
581           agg->ident.type, agg->ident.type_instance);
582     is_valid = 0;
583   } else if (strchr(agg->ident.type, '/') != NULL) {
584     ERROR("aggregation plugin: The \"Type\" may not contain the '/' "
585           "character. Especially, it may not be a regex. The current "
586           "value is \"%s\".",
587           agg->ident.type);
588     is_valid = 0;
589   } /* }}} */
590
591   /* Check that there is at least one regex field without a grouping. {{{ */
592   if ((agg->regex_fields & ~agg->group_by) == 0) {
593     ERROR("aggregation plugin: An aggregation must contain at least one "
594           "wildcard. This is achieved by leaving at least one of the \"Host\", "
595           "\"Plugin\", \"PluginInstance\" and \"TypeInstance\" options blank "
596           "or using a regular expression and not grouping by that field. "
597           "(Host \"%s\", Plugin \"%s\", PluginInstance \"%s\", "
598           "Type \"%s\", TypeInstance \"%s\")",
599           agg->ident.host, agg->ident.plugin, agg->ident.plugin_instance,
600           agg->ident.type, agg->ident.type_instance);
601     is_valid = 0;
602   } /* }}} */
603
604   /* Check that all grouping fields are regular expressions. {{{ */
605   if (agg->group_by & ~agg->regex_fields) {
606     ERROR("aggregation plugin: Only wildcard fields (fields for which a "
607           "regular expression is configured or which are left blank) can be "
608           "specified in the \"GroupBy\" option. "
609           "(Host \"%s\", Plugin \"%s\", PluginInstance \"%s\", "
610           "Type \"%s\", TypeInstance \"%s\")",
611           agg->ident.host, agg->ident.plugin, agg->ident.plugin_instance,
612           agg->ident.type, agg->ident.type_instance);
613     is_valid = 0;
614   } /* }}} */
615
616   if (!agg->calc_num && !agg->calc_sum && !agg->calc_average /* {{{ */
617       && !agg->calc_min && !agg->calc_max && !agg->calc_stddev) {
618     ERROR("aggregation plugin: No aggregation function has been specified. "
619           "Without this, I don't know what I should be calculating. "
620           "(Host \"%s\", Plugin \"%s\", PluginInstance \"%s\", "
621           "Type \"%s\", TypeInstance \"%s\")",
622           agg->ident.host, agg->ident.plugin, agg->ident.plugin_instance,
623           agg->ident.type, agg->ident.type_instance);
624     is_valid = 0;
625   } /* }}} */
626
627   if (!is_valid) { /* {{{ */
628     sfree(agg);
629     return -1;
630   } /* }}} */
631
632   int status = lookup_add(lookup, &agg->ident, agg->group_by, agg);
633   if (status != 0) {
634     ERROR("aggregation plugin: lookup_add failed with status %i.", status);
635     sfree(agg);
636     return -1;
637   }
638
639   DEBUG("aggregation plugin: Successfully added aggregation: "
640         "(Host \"%s\", Plugin \"%s\", PluginInstance \"%s\", "
641         "Type \"%s\", TypeInstance \"%s\")",
642         agg->ident.host, agg->ident.plugin, agg->ident.plugin_instance,
643         agg->ident.type, agg->ident.type_instance);
644   return 0;
645 } /* }}} int agg_config_aggregation */
646
647 static int agg_config(oconfig_item_t *ci) /* {{{ */
648 {
649   pthread_mutex_lock(&agg_instance_list_lock);
650
651   if (lookup == NULL) {
652     lookup = lookup_create(agg_lookup_class_callback, agg_lookup_obj_callback,
653                            agg_lookup_free_class_callback,
654                            agg_lookup_free_obj_callback);
655     if (lookup == NULL) {
656       pthread_mutex_unlock(&agg_instance_list_lock);
657       ERROR("aggregation plugin: lookup_create failed.");
658       return -1;
659     }
660   }
661
662   for (int i = 0; i < ci->children_num; i++) {
663     oconfig_item_t *child = ci->children + i;
664
665     if (strcasecmp("Aggregation", child->key) == 0)
666       agg_config_aggregation(child);
667     else
668       WARNING("aggregation plugin: The \"%s\" key is not allowed inside "
669               "<Plugin aggregation /> blocks and will be ignored.",
670               child->key);
671   }
672
673   pthread_mutex_unlock(&agg_instance_list_lock);
674
675   return 0;
676 } /* }}} int agg_config */
677
678 static int agg_read(void) /* {{{ */
679 {
680   cdtime_t t = cdtime();
681   int success = 0;
682
683   pthread_mutex_lock(&agg_instance_list_lock);
684
685   /* agg_instance_list_head only holds data, after the "write" callback has
686    * been called with a matching value list at least once. So on startup,
687    * there's a race between the aggregations read() and write() callback. If
688    * the read() callback is called first, agg_instance_list_head is NULL and
689    * "success" may be zero. This is expected and should not result in an error.
690    * Therefore we need to handle this case separately. */
691   if (agg_instance_list_head == NULL) {
692     pthread_mutex_unlock(&agg_instance_list_lock);
693     return 0;
694   }
695
696   for (agg_instance_t *this = agg_instance_list_head; this != NULL;
697        this = this->next) {
698     int status = agg_instance_read(this, t);
699     if (status != 0)
700       WARNING("aggregation plugin: Reading an aggregation instance "
701               "failed with status %i.",
702               status);
703     else
704       success++;
705   }
706
707   pthread_mutex_unlock(&agg_instance_list_lock);
708
709   return (success > 0) ? 0 : -1;
710 } /* }}} int agg_read */
711
712 static int agg_write(data_set_t const *ds, value_list_t const *vl, /* {{{ */
713                      __attribute__((unused)) user_data_t *user_data) {
714   _Bool created_by_aggregation = 0;
715   /* Ignore values that were created by the aggregation plugin to avoid weird
716    * effects. */
717   (void)meta_data_get_boolean(vl->meta, "aggregation:created",
718                               &created_by_aggregation);
719   if (created_by_aggregation)
720     return 0;
721
722   int status;
723
724   if (lookup == NULL)
725     status = ENOENT;
726   else {
727     status = lookup_search(lookup, ds, vl);
728     if (status > 0)
729       status = 0;
730   }
731
732   return status;
733 } /* }}} int agg_write */
734
735 void module_register(void) {
736   plugin_register_complex_config("aggregation", agg_config);
737   plugin_register_read("aggregation", agg_read);
738   plugin_register_write("aggregation", agg_write, /* user_data = */ NULL);
739 }