Tree wide: Reformat with clang-format.
[collectd.git] / src / write_kafka.c
1 /**
2  * collectd - src/write_kafka.c
3  * Copyright (C) 2014       Pierre-Yves Ritschard
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  *   Pierre-Yves Ritschard <pyr at spootnik.org>
25  */
26
27 #include "collectd.h"
28
29 #include "common.h"
30 #include "plugin.h"
31 #include "utils_cmd_putval.h"
32 #include "utils_format_graphite.h"
33 #include "utils_format_json.h"
34
35 #include <errno.h>
36 #include <librdkafka/rdkafka.h>
37 #include <stdint.h>
38
39 struct kafka_topic_context {
40 #define KAFKA_FORMAT_JSON 0
41 #define KAFKA_FORMAT_COMMAND 1
42 #define KAFKA_FORMAT_GRAPHITE 2
43   uint8_t format;
44   unsigned int graphite_flags;
45   _Bool store_rates;
46   rd_kafka_topic_conf_t *conf;
47   rd_kafka_topic_t *topic;
48   rd_kafka_conf_t *kafka_conf;
49   rd_kafka_t *kafka;
50   char *key;
51   char *prefix;
52   char *postfix;
53   char escape_char;
54   char *topic_name;
55   pthread_mutex_t lock;
56 };
57
58 static int kafka_handle(struct kafka_topic_context *);
59 static int kafka_write(const data_set_t *, const value_list_t *, user_data_t *);
60 static int32_t kafka_partition(const rd_kafka_topic_t *, const void *, size_t,
61                                int32_t, void *, void *);
62
63 /* Version 0.9.0 of librdkafka deprecates rd_kafka_set_logger() in favor of
64  * rd_kafka_conf_set_log_cb(). This is to make sure we're not using the
65  * deprecated function. */
66 #ifdef HAVE_LIBRDKAFKA_LOG_CB
67 #undef HAVE_LIBRDKAFKA_LOGGER
68 #endif
69
70 #if defined(HAVE_LIBRDKAFKA_LOGGER) || defined(HAVE_LIBRDKAFKA_LOG_CB)
71 static void kafka_log(const rd_kafka_t *, int, const char *, const char *);
72
73 static void kafka_log(const rd_kafka_t *rkt, int level, const char *fac,
74                       const char *msg) {
75   plugin_log(level, "%s", msg);
76 }
77 #endif
78
79 static uint32_t kafka_hash(const char *keydata, size_t keylen) {
80   uint32_t hash = 5381;
81   for (; keylen > 0; keylen--)
82     hash = ((hash << 5) + hash) + keydata[keylen - 1];
83   return hash;
84 }
85
86 /* 31 bit -> 4 byte -> 8 byte hex string + null byte */
87 #define KAFKA_RANDOM_KEY_SIZE 9
88 #define KAFKA_RANDOM_KEY_BUFFER                                                \
89   (char[KAFKA_RANDOM_KEY_SIZE]) { "" }
90 static char *kafka_random_key(char buffer[static KAFKA_RANDOM_KEY_SIZE]) {
91   ssnprintf(buffer, KAFKA_RANDOM_KEY_SIZE, "%08lX", (unsigned long)mrand48());
92   return buffer;
93 }
94
95 static int32_t kafka_partition(const rd_kafka_topic_t *rkt, const void *keydata,
96                                size_t keylen, int32_t partition_cnt, void *p,
97                                void *m) {
98   uint32_t key = kafka_hash(keydata, keylen);
99   uint32_t target = key % partition_cnt;
100   int32_t i = partition_cnt;
101
102   while (--i > 0 && !rd_kafka_topic_partition_available(rkt, target)) {
103     target = (target + 1) % partition_cnt;
104   }
105   return target;
106 }
107
108 static int kafka_handle(struct kafka_topic_context *ctx) /* {{{ */
109 {
110   char errbuf[1024];
111   rd_kafka_conf_t *conf;
112   rd_kafka_topic_conf_t *topic_conf;
113
114   if (ctx->kafka != NULL && ctx->topic != NULL)
115     return (0);
116
117   if (ctx->kafka == NULL) {
118     if ((conf = rd_kafka_conf_dup(ctx->kafka_conf)) == NULL) {
119       ERROR("write_kafka plugin: cannot duplicate kafka config");
120       return (1);
121     }
122
123     if ((ctx->kafka = rd_kafka_new(RD_KAFKA_PRODUCER, conf, errbuf,
124                                    sizeof(errbuf))) == NULL) {
125       ERROR("write_kafka plugin: cannot create kafka handle.");
126       return 1;
127     }
128
129     rd_kafka_conf_destroy(ctx->kafka_conf);
130     ctx->kafka_conf = NULL;
131
132     INFO("write_kafka plugin: created KAFKA handle : %s",
133          rd_kafka_name(ctx->kafka));
134
135 #if defined(HAVE_LIBRDKAFKA_LOGGER) && !defined(HAVE_LIBRDKAFKA_LOG_CB)
136     rd_kafka_set_logger(ctx->kafka, kafka_log);
137 #endif
138   }
139
140   if (ctx->topic == NULL) {
141     if ((topic_conf = rd_kafka_topic_conf_dup(ctx->conf)) == NULL) {
142       ERROR("write_kafka plugin: cannot duplicate kafka topic config");
143       return 1;
144     }
145
146     if ((ctx->topic = rd_kafka_topic_new(ctx->kafka, ctx->topic_name,
147                                          topic_conf)) == NULL) {
148       ERROR("write_kafka plugin: cannot create topic : %s\n",
149             rd_kafka_err2str(rd_kafka_errno2err(errno)));
150       return errno;
151     }
152
153     rd_kafka_topic_conf_destroy(ctx->conf);
154     ctx->conf = NULL;
155
156     INFO("write_kafka plugin: handle created for topic : %s",
157          rd_kafka_topic_name(ctx->topic));
158   }
159
160   return (0);
161
162 } /* }}} int kafka_handle */
163
164 static int kafka_write(const data_set_t *ds, /* {{{ */
165                        const value_list_t *vl, user_data_t *ud) {
166   int status = 0;
167   void *key;
168   size_t keylen = 0;
169   char buffer[8192];
170   size_t bfree = sizeof(buffer);
171   size_t bfill = 0;
172   size_t blen = 0;
173   struct kafka_topic_context *ctx = ud->data;
174
175   if ((ds == NULL) || (vl == NULL) || (ctx == NULL))
176     return EINVAL;
177
178   pthread_mutex_lock(&ctx->lock);
179   status = kafka_handle(ctx);
180   pthread_mutex_unlock(&ctx->lock);
181   if (status != 0)
182     return status;
183
184   bzero(buffer, sizeof(buffer));
185
186   switch (ctx->format) {
187   case KAFKA_FORMAT_COMMAND:
188     status = cmd_create_putval(buffer, sizeof(buffer), ds, vl);
189     if (status != 0) {
190       ERROR("write_kafka plugin: cmd_create_putval failed with status %i.",
191             status);
192       return status;
193     }
194     blen = strlen(buffer);
195     break;
196   case KAFKA_FORMAT_JSON:
197     format_json_initialize(buffer, &bfill, &bfree);
198     format_json_value_list(buffer, &bfill, &bfree, ds, vl, ctx->store_rates);
199     format_json_finalize(buffer, &bfill, &bfree);
200     blen = strlen(buffer);
201     break;
202   case KAFKA_FORMAT_GRAPHITE:
203     status =
204         format_graphite(buffer, sizeof(buffer), ds, vl, ctx->prefix,
205                         ctx->postfix, ctx->escape_char, ctx->graphite_flags);
206     if (status != 0) {
207       ERROR("write_kafka plugin: format_graphite failed with status %i.",
208             status);
209       return status;
210     }
211     blen = strlen(buffer);
212     break;
213   default:
214     ERROR("write_kafka plugin: invalid format %i.", ctx->format);
215     return -1;
216   }
217
218   key =
219       (ctx->key != NULL) ? ctx->key : kafka_random_key(KAFKA_RANDOM_KEY_BUFFER);
220   keylen = strlen(key);
221
222   rd_kafka_produce(ctx->topic, RD_KAFKA_PARTITION_UA, RD_KAFKA_MSG_F_COPY,
223                    buffer, blen, key, keylen, NULL);
224
225   return status;
226 } /* }}} int kafka_write */
227
228 static void kafka_topic_context_free(void *p) /* {{{ */
229 {
230   struct kafka_topic_context *ctx = p;
231
232   if (ctx == NULL)
233     return;
234
235   if (ctx->topic_name != NULL)
236     sfree(ctx->topic_name);
237   if (ctx->topic != NULL)
238     rd_kafka_topic_destroy(ctx->topic);
239   if (ctx->conf != NULL)
240     rd_kafka_topic_conf_destroy(ctx->conf);
241   if (ctx->kafka_conf != NULL)
242     rd_kafka_conf_destroy(ctx->kafka_conf);
243   if (ctx->kafka != NULL)
244     rd_kafka_destroy(ctx->kafka);
245
246   sfree(ctx);
247 } /* }}} void kafka_topic_context_free */
248
249 static void kafka_config_topic(rd_kafka_conf_t *conf,
250                                oconfig_item_t *ci) /* {{{ */
251 {
252   int status;
253   struct kafka_topic_context *tctx;
254   char *key = NULL;
255   char *val;
256   char callback_name[DATA_MAX_NAME_LEN];
257   char errbuf[1024];
258   oconfig_item_t *child;
259   rd_kafka_conf_res_t ret;
260
261   if ((tctx = calloc(1, sizeof(*tctx))) == NULL) {
262     ERROR("write_kafka plugin: calloc failed.");
263     return;
264   }
265
266   tctx->escape_char = '.';
267   tctx->store_rates = 1;
268   tctx->format = KAFKA_FORMAT_JSON;
269   tctx->key = NULL;
270
271   if ((tctx->kafka_conf = rd_kafka_conf_dup(conf)) == NULL) {
272     sfree(tctx);
273     ERROR("write_kafka plugin: cannot allocate memory for kafka config");
274     return;
275   }
276
277 #ifdef HAVE_LIBRDKAFKA_LOG_CB
278   rd_kafka_conf_set_log_cb(tctx->kafka_conf, kafka_log);
279 #endif
280
281   if ((tctx->conf = rd_kafka_topic_conf_new()) == NULL) {
282     rd_kafka_conf_destroy(tctx->kafka_conf);
283     sfree(tctx);
284     ERROR("write_kafka plugin: cannot create topic configuration.");
285     return;
286   }
287
288   if (ci->values_num != 1) {
289     WARNING("kafka topic name needed.");
290     goto errout;
291   }
292
293   if (ci->values[0].type != OCONFIG_TYPE_STRING) {
294     WARNING("kafka topic needs a string argument.");
295     goto errout;
296   }
297
298   if ((tctx->topic_name = strdup(ci->values[0].value.string)) == NULL) {
299     ERROR("write_kafka plugin: cannot copy topic name.");
300     goto errout;
301   }
302
303   for (int i = 0; i < ci->children_num; i++) {
304     /*
305      * The code here could be simplified but makes room
306      * for easy adding of new options later on.
307      */
308     child = &ci->children[i];
309     status = 0;
310
311     if (strcasecmp("Property", child->key) == 0) {
312       if (child->values_num != 2) {
313         WARNING("kafka properties need both a key and a value.");
314         goto errout;
315       }
316       if (child->values[0].type != OCONFIG_TYPE_STRING ||
317           child->values[1].type != OCONFIG_TYPE_STRING) {
318         WARNING("kafka properties needs string arguments.");
319         goto errout;
320       }
321       key = child->values[0].value.string;
322       val = child->values[1].value.string;
323       ret =
324           rd_kafka_topic_conf_set(tctx->conf, key, val, errbuf, sizeof(errbuf));
325       if (ret != RD_KAFKA_CONF_OK) {
326         WARNING("cannot set kafka topic property %s to %s: %s.", key, val,
327                 errbuf);
328         goto errout;
329       }
330
331     } else if (strcasecmp("Key", child->key) == 0) {
332       if (cf_util_get_string(child, &tctx->key) != 0)
333         continue;
334       if (strcasecmp("Random", tctx->key) == 0) {
335         sfree(tctx->key);
336         tctx->key = strdup(kafka_random_key(KAFKA_RANDOM_KEY_BUFFER));
337       }
338     } else if (strcasecmp("Format", child->key) == 0) {
339       status = cf_util_get_string(child, &key);
340       if (status != 0)
341         goto errout;
342
343       assert(key != NULL);
344
345       if (strcasecmp(key, "Command") == 0) {
346         tctx->format = KAFKA_FORMAT_COMMAND;
347
348       } else if (strcasecmp(key, "Graphite") == 0) {
349         tctx->format = KAFKA_FORMAT_GRAPHITE;
350
351       } else if (strcasecmp(key, "Json") == 0) {
352         tctx->format = KAFKA_FORMAT_JSON;
353
354       } else {
355         WARNING("write_kafka plugin: Invalid format string: %s", key);
356       }
357
358       sfree(key);
359
360     } else if (strcasecmp("StoreRates", child->key) == 0) {
361       status = cf_util_get_boolean(child, &tctx->store_rates);
362       (void)cf_util_get_flag(child, &tctx->graphite_flags,
363                              GRAPHITE_STORE_RATES);
364
365     } else if (strcasecmp("GraphiteSeparateInstances", child->key) == 0) {
366       status = cf_util_get_flag(child, &tctx->graphite_flags,
367                                 GRAPHITE_SEPARATE_INSTANCES);
368
369     } else if (strcasecmp("GraphiteAlwaysAppendDS", child->key) == 0) {
370       status = cf_util_get_flag(child, &tctx->graphite_flags,
371                                 GRAPHITE_ALWAYS_APPEND_DS);
372
373     } else if (strcasecmp("GraphitePreserveSeparator", child->key) == 0) {
374       status = cf_util_get_flag(child, &tctx->graphite_flags,
375                                 GRAPHITE_PRESERVE_SEPARATOR);
376
377     } else if (strcasecmp("GraphitePrefix", child->key) == 0) {
378       status = cf_util_get_string(child, &tctx->prefix);
379     } else if (strcasecmp("GraphitePostfix", child->key) == 0) {
380       status = cf_util_get_string(child, &tctx->postfix);
381     } else if (strcasecmp("GraphiteEscapeChar", child->key) == 0) {
382       char *tmp_buff = NULL;
383       status = cf_util_get_string(child, &tmp_buff);
384       if (strlen(tmp_buff) > 1)
385         WARNING("write_kafka plugin: The option \"GraphiteEscapeChar\" handles "
386                 "only one character. Others will be ignored.");
387       tctx->escape_char = tmp_buff[0];
388       sfree(tmp_buff);
389     } else {
390       WARNING("write_kafka plugin: Invalid directive: %s.", child->key);
391     }
392
393     if (status != 0)
394       break;
395   }
396
397   rd_kafka_topic_conf_set_partitioner_cb(tctx->conf, kafka_partition);
398   rd_kafka_topic_conf_set_opaque(tctx->conf, tctx);
399
400   ssnprintf(callback_name, sizeof(callback_name), "write_kafka/%s",
401             tctx->topic_name);
402
403   status = plugin_register_write(
404       callback_name, kafka_write,
405       &(user_data_t){
406           .data = tctx, .free_func = kafka_topic_context_free,
407       });
408   if (status != 0) {
409     WARNING("write_kafka plugin: plugin_register_write (\"%s\") "
410             "failed with status %i.",
411             callback_name, status);
412     goto errout;
413   }
414
415   pthread_mutex_init(&tctx->lock, /* attr = */ NULL);
416
417   return;
418 errout:
419   if (tctx->topic_name != NULL)
420     free(tctx->topic_name);
421   if (tctx->conf != NULL)
422     rd_kafka_topic_conf_destroy(tctx->conf);
423   if (tctx->kafka_conf != NULL)
424     rd_kafka_conf_destroy(tctx->kafka_conf);
425   sfree(tctx);
426 } /* }}} int kafka_config_topic */
427
428 static int kafka_config(oconfig_item_t *ci) /* {{{ */
429 {
430   oconfig_item_t *child;
431   rd_kafka_conf_t *conf;
432   rd_kafka_conf_res_t ret;
433   char errbuf[1024];
434
435   if ((conf = rd_kafka_conf_new()) == NULL) {
436     WARNING("cannot allocate kafka configuration.");
437     return -1;
438   }
439   for (int i = 0; i < ci->children_num; i++) {
440     child = &ci->children[i];
441
442     if (strcasecmp("Topic", child->key) == 0) {
443       kafka_config_topic(conf, child);
444     } else if (strcasecmp(child->key, "Property") == 0) {
445       char *key = NULL;
446       char *val = NULL;
447
448       if (child->values_num != 2) {
449         WARNING("kafka properties need both a key and a value.");
450         goto errout;
451       }
452       if (child->values[0].type != OCONFIG_TYPE_STRING ||
453           child->values[1].type != OCONFIG_TYPE_STRING) {
454         WARNING("kafka properties needs string arguments.");
455         goto errout;
456       }
457       if ((key = strdup(child->values[0].value.string)) == NULL) {
458         WARNING("cannot allocate memory for attribute key.");
459         goto errout;
460       }
461       if ((val = strdup(child->values[1].value.string)) == NULL) {
462         WARNING("cannot allocate memory for attribute value.");
463         sfree(key);
464         goto errout;
465       }
466       ret = rd_kafka_conf_set(conf, key, val, errbuf, sizeof(errbuf));
467       if (ret != RD_KAFKA_CONF_OK) {
468         WARNING("cannot set kafka property %s to %s: %s", key, val, errbuf);
469         sfree(key);
470         sfree(val);
471         goto errout;
472       }
473       sfree(key);
474       sfree(val);
475     } else {
476       WARNING("write_kafka plugin: Ignoring unknown "
477               "configuration option \"%s\" at top level.",
478               child->key);
479     }
480   }
481   if (conf != NULL)
482     rd_kafka_conf_destroy(conf);
483   return (0);
484 errout:
485   if (conf != NULL)
486     rd_kafka_conf_destroy(conf);
487   return -1;
488 } /* }}} int kafka_config */
489
490 void module_register(void) {
491   plugin_register_complex_config("write_kafka", kafka_config);
492 }