dba09c03de4ea049437a0f3de33cd5a141c8ffc5
[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 = create_putval(buffer, sizeof(buffer), ds, vl);
189     if (status != 0) {
190       ERROR("write_kafka plugin: create_putval failed with status %i.", status);
191       return status;
192     }
193     blen = strlen(buffer);
194     break;
195   case KAFKA_FORMAT_JSON:
196     format_json_initialize(buffer, &bfill, &bfree);
197     format_json_value_list(buffer, &bfill, &bfree, ds, vl, ctx->store_rates);
198     format_json_finalize(buffer, &bfill, &bfree);
199     blen = strlen(buffer);
200     break;
201   case KAFKA_FORMAT_GRAPHITE:
202     status =
203         format_graphite(buffer, sizeof(buffer), ds, vl, ctx->prefix,
204                         ctx->postfix, ctx->escape_char, ctx->graphite_flags);
205     if (status != 0) {
206       ERROR("write_kafka plugin: format_graphite failed with status %i.",
207             status);
208       return status;
209     }
210     blen = strlen(buffer);
211     break;
212   default:
213     ERROR("write_kafka plugin: invalid format %i.", ctx->format);
214     return -1;
215   }
216
217   key =
218       (ctx->key != NULL) ? ctx->key : kafka_random_key(KAFKA_RANDOM_KEY_BUFFER);
219   keylen = strlen(key);
220
221   rd_kafka_produce(ctx->topic, RD_KAFKA_PARTITION_UA, RD_KAFKA_MSG_F_COPY,
222                    buffer, blen, key, keylen, NULL);
223
224   return status;
225 } /* }}} int kafka_write */
226
227 static void kafka_topic_context_free(void *p) /* {{{ */
228 {
229   struct kafka_topic_context *ctx = p;
230
231   if (ctx == NULL)
232     return;
233
234   if (ctx->topic_name != NULL)
235     sfree(ctx->topic_name);
236   if (ctx->topic != NULL)
237     rd_kafka_topic_destroy(ctx->topic);
238   if (ctx->conf != NULL)
239     rd_kafka_topic_conf_destroy(ctx->conf);
240   if (ctx->kafka_conf != NULL)
241     rd_kafka_conf_destroy(ctx->kafka_conf);
242   if (ctx->kafka != NULL)
243     rd_kafka_destroy(ctx->kafka);
244
245   sfree(ctx);
246 } /* }}} void kafka_topic_context_free */
247
248 static void kafka_config_topic(rd_kafka_conf_t *conf,
249                                oconfig_item_t *ci) /* {{{ */
250 {
251   int status;
252   struct kafka_topic_context *tctx;
253   char *key = NULL;
254   char *val;
255   char callback_name[DATA_MAX_NAME_LEN];
256   char errbuf[1024];
257   oconfig_item_t *child;
258   rd_kafka_conf_res_t ret;
259
260   if ((tctx = calloc(1, sizeof(*tctx))) == NULL) {
261     ERROR("write_kafka plugin: calloc failed.");
262     return;
263   }
264
265   tctx->escape_char = '.';
266   tctx->store_rates = 1;
267   tctx->format = KAFKA_FORMAT_JSON;
268   tctx->key = NULL;
269
270   if ((tctx->kafka_conf = rd_kafka_conf_dup(conf)) == NULL) {
271     sfree(tctx);
272     ERROR("write_kafka plugin: cannot allocate memory for kafka config");
273     return;
274   }
275
276 #ifdef HAVE_LIBRDKAFKA_LOG_CB
277   rd_kafka_conf_set_log_cb(tctx->kafka_conf, kafka_log);
278 #endif
279
280   if ((tctx->conf = rd_kafka_topic_conf_new()) == NULL) {
281     rd_kafka_conf_destroy(tctx->kafka_conf);
282     sfree(tctx);
283     ERROR("write_kafka plugin: cannot create topic configuration.");
284     return;
285   }
286
287   if (ci->values_num != 1) {
288     WARNING("kafka topic name needed.");
289     goto errout;
290   }
291
292   if (ci->values[0].type != OCONFIG_TYPE_STRING) {
293     WARNING("kafka topic needs a string argument.");
294     goto errout;
295   }
296
297   if ((tctx->topic_name = strdup(ci->values[0].value.string)) == NULL) {
298     ERROR("write_kafka plugin: cannot copy topic name.");
299     goto errout;
300   }
301
302   for (int i = 0; i < ci->children_num; i++) {
303     /*
304      * The code here could be simplified but makes room
305      * for easy adding of new options later on.
306      */
307     child = &ci->children[i];
308     status = 0;
309
310     if (strcasecmp("Property", child->key) == 0) {
311       if (child->values_num != 2) {
312         WARNING("kafka properties need both a key and a value.");
313         goto errout;
314       }
315       if (child->values[0].type != OCONFIG_TYPE_STRING ||
316           child->values[1].type != OCONFIG_TYPE_STRING) {
317         WARNING("kafka properties needs string arguments.");
318         goto errout;
319       }
320       key = child->values[0].value.string;
321       val = child->values[1].value.string;
322       ret =
323           rd_kafka_topic_conf_set(tctx->conf, key, val, errbuf, sizeof(errbuf));
324       if (ret != RD_KAFKA_CONF_OK) {
325         WARNING("cannot set kafka topic property %s to %s: %s.", key, val,
326                 errbuf);
327         goto errout;
328       }
329
330     } else if (strcasecmp("Key", child->key) == 0) {
331       if (cf_util_get_string(child, &tctx->key) != 0)
332         continue;
333       if (strcasecmp("Random", tctx->key) == 0) {
334         sfree(tctx->key);
335         tctx->key = strdup(kafka_random_key(KAFKA_RANDOM_KEY_BUFFER));
336       }
337     } else if (strcasecmp("Format", child->key) == 0) {
338       status = cf_util_get_string(child, &key);
339       if (status != 0)
340         goto errout;
341
342       assert(key != NULL);
343
344       if (strcasecmp(key, "Command") == 0) {
345         tctx->format = KAFKA_FORMAT_COMMAND;
346
347       } else if (strcasecmp(key, "Graphite") == 0) {
348         tctx->format = KAFKA_FORMAT_GRAPHITE;
349
350       } else if (strcasecmp(key, "Json") == 0) {
351         tctx->format = KAFKA_FORMAT_JSON;
352
353       } else {
354         WARNING("write_kafka plugin: Invalid format string: %s", key);
355       }
356
357       sfree(key);
358
359     } else if (strcasecmp("StoreRates", child->key) == 0) {
360       status = cf_util_get_boolean(child, &tctx->store_rates);
361       (void)cf_util_get_flag(child, &tctx->graphite_flags,
362                              GRAPHITE_STORE_RATES);
363
364     } else if (strcasecmp("GraphiteSeparateInstances", child->key) == 0) {
365       status = cf_util_get_flag(child, &tctx->graphite_flags,
366                                 GRAPHITE_SEPARATE_INSTANCES);
367
368     } else if (strcasecmp("GraphiteAlwaysAppendDS", child->key) == 0) {
369       status = cf_util_get_flag(child, &tctx->graphite_flags,
370                                 GRAPHITE_ALWAYS_APPEND_DS);
371
372     } else if (strcasecmp("GraphitePrefix", child->key) == 0) {
373       status = cf_util_get_string(child, &tctx->prefix);
374     } else if (strcasecmp("GraphitePostfix", child->key) == 0) {
375       status = cf_util_get_string(child, &tctx->postfix);
376     } else if (strcasecmp("GraphiteEscapeChar", child->key) == 0) {
377       char *tmp_buff = NULL;
378       status = cf_util_get_string(child, &tmp_buff);
379       if (strlen(tmp_buff) > 1)
380         WARNING("write_kafka plugin: The option \"GraphiteEscapeChar\" handles "
381                 "only one character. Others will be ignored.");
382       tctx->escape_char = tmp_buff[0];
383       sfree(tmp_buff);
384     } else {
385       WARNING("write_kafka plugin: Invalid directive: %s.", child->key);
386     }
387
388     if (status != 0)
389       break;
390   }
391
392   rd_kafka_topic_conf_set_partitioner_cb(tctx->conf, kafka_partition);
393   rd_kafka_topic_conf_set_opaque(tctx->conf, tctx);
394
395   ssnprintf(callback_name, sizeof(callback_name), "write_kafka/%s",
396             tctx->topic_name);
397
398   user_data_t ud = {.data = tctx, .free_func = kafka_topic_context_free};
399
400   status = plugin_register_write(callback_name, kafka_write, &ud);
401   if (status != 0) {
402     WARNING("write_kafka plugin: plugin_register_write (\"%s\") "
403             "failed with status %i.",
404             callback_name, status);
405     goto errout;
406   }
407
408   pthread_mutex_init(&tctx->lock, /* attr = */ NULL);
409
410   return;
411 errout:
412   if (tctx->topic_name != NULL)
413     free(tctx->topic_name);
414   if (tctx->conf != NULL)
415     rd_kafka_topic_conf_destroy(tctx->conf);
416   if (tctx->kafka_conf != NULL)
417     rd_kafka_conf_destroy(tctx->kafka_conf);
418   sfree(tctx);
419 } /* }}} int kafka_config_topic */
420
421 static int kafka_config(oconfig_item_t *ci) /* {{{ */
422 {
423   oconfig_item_t *child;
424   rd_kafka_conf_t *conf;
425   rd_kafka_conf_res_t ret;
426   char errbuf[1024];
427
428   if ((conf = rd_kafka_conf_new()) == NULL) {
429     WARNING("cannot allocate kafka configuration.");
430     return -1;
431   }
432   for (int i = 0; i < ci->children_num; i++) {
433     child = &ci->children[i];
434
435     if (strcasecmp("Topic", child->key) == 0) {
436       kafka_config_topic(conf, child);
437     } else if (strcasecmp(child->key, "Property") == 0) {
438       char *key = NULL;
439       char *val = NULL;
440
441       if (child->values_num != 2) {
442         WARNING("kafka properties need both a key and a value.");
443         goto errout;
444       }
445       if (child->values[0].type != OCONFIG_TYPE_STRING ||
446           child->values[1].type != OCONFIG_TYPE_STRING) {
447         WARNING("kafka properties needs string arguments.");
448         goto errout;
449       }
450       if ((key = strdup(child->values[0].value.string)) == NULL) {
451         WARNING("cannot allocate memory for attribute key.");
452         goto errout;
453       }
454       if ((val = strdup(child->values[1].value.string)) == NULL) {
455         WARNING("cannot allocate memory for attribute value.");
456         sfree(key);
457         goto errout;
458       }
459       ret = rd_kafka_conf_set(conf, key, val, errbuf, sizeof(errbuf));
460       if (ret != RD_KAFKA_CONF_OK) {
461         WARNING("cannot set kafka property %s to %s: %s", key, val, errbuf);
462         sfree(key);
463         sfree(val);
464         goto errout;
465       }
466       sfree(key);
467       sfree(val);
468     } else {
469       WARNING("write_kafka plugin: Ignoring unknown "
470               "configuration option \"%s\" at top level.",
471               child->key);
472     }
473   }
474   if (conf != NULL)
475     rd_kafka_conf_destroy(conf);
476   return (0);
477 errout:
478   if (conf != NULL)
479     rd_kafka_conf_destroy(conf);
480   return -1;
481 } /* }}} int kafka_config */
482
483 void module_register(void) {
484   plugin_register_complex_config("write_kafka", kafka_config);
485 }