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