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