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