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