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