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