Code

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