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