-
Notifications
You must be signed in to change notification settings - Fork 483
/
kcat.c
2644 lines (2232 loc) · 95.7 KB
/
kcat.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* kcat - Apache Kafka consumer and producer
*
* Copyright (c) 2014-2021, Magnus Edenhill
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _MSC_VER
#include <unistd.h>
#include <syslog.h>
#include <sys/time.h>
#include <sys/mman.h>
#else
#pragma comment(lib, "ws2_32.lib")
#include "win32/wingetopt.h"
#include <io.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <signal.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "kcat.h"
#include "input.h"
#if ENABLE_MOCK
#include <librdkafka/rdkafka_mock.h>
#endif
#if RD_KAFKA_VERSION >= 0x01040000
#define ENABLE_TXNS 1
#endif
#if RD_KAFKA_VERSION >= 0x01060000
#define ENABLE_INCREMENTAL_ASSIGN 1
#endif
struct conf conf = {
.run = 1,
.verbosity = 1,
.exitonerror = 1,
.partition = RD_KAFKA_PARTITION_UA,
.msg_size = 1024*1024,
.null_str = "NULL",
.fixed_key = NULL,
.metadata_timeout = 5,
.offset = RD_KAFKA_OFFSET_INVALID,
};
static struct stats {
uint64_t tx;
uint64_t tx_err_q;
uint64_t tx_err_dr;
uint64_t tx_delivered;
uint64_t rx;
} stats;
/* Partition's stopped state array */
int *part_stop = NULL;
/* Number of partitions that are stopped */
int part_stop_cnt = 0;
/* Threshold level (partitions stopped) before exiting */
int part_stop_thres = 0;
/**
* Fatal error: print error and exit
*/
void RD_NORETURN fatal0 (const char *func, int line,
const char *fmt, ...) {
va_list ap;
char buf[1024];
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
KC_INFO(2, "Fatal error at %s:%i:\n", func, line);
fprintf(stderr, "%% ERROR: %s\n", buf);
exit(1);
}
/**
* Print error and exit if needed
*/
void error0 (int exitonerror, const char *func, int line,
const char *fmt, ...) {
va_list ap;
char buf[1024];
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
if (exitonerror)
KC_INFO(2, "Error at %s:%i:\n", func, line);
fprintf(stderr, "%% ERROR: %s%s\n",
buf, exitonerror ? ": terminating":"");
if (exitonerror)
exit(1);
}
/**
* The delivery report callback is called once per message to
* report delivery success or failure.
*/
static void dr_msg_cb (rd_kafka_t *rk, const rd_kafka_message_t *rkmessage,
void *opaque) {
int32_t broker_id = -1;
struct buf *b = rkmessage->_private;
#if RD_KAFKA_VERSION < 0x01000000
static int say_once = 1;
#endif
if (b)
buf_destroy(b);
if (rkmessage->err) {
KC_INFO(1, "Delivery failed for message: %s\n",
rd_kafka_err2str(rkmessage->err));
stats.tx_err_dr++;
return;
}
#if RD_KAFKA_VERSION >= 0x010500ff
broker_id = rd_kafka_message_broker_id(rkmessage);
#endif
KC_INFO(3,
"Message delivered to partition %"PRId32" (offset %"PRId64") "
"on broker %"PRId32"\n",
rkmessage->partition, rkmessage->offset, broker_id);
#if RD_KAFKA_VERSION < 0x01000000
if (rkmessage->offset == 0 && say_once) {
KC_INFO(3, "Enable message offset reporting "
"with '-X topic.produce.offset.report=true'\n");
say_once = 0;
}
#endif
stats.tx_delivered++;
}
/**
* Produces a single message, retries on queue congestion, and
* exits hard on error.
*/
static void produce (void *buf, size_t len,
const void *key, size_t key_len, int msgflags,
void *msg_opaque) {
rd_kafka_headers_t *hdrs = NULL;
/* Headers are freed on successful producev(), pass a copy. */
if (conf.headers)
hdrs = rd_kafka_headers_copy(conf.headers);
/* Produce message: keep trying until it succeeds. */
do {
rd_kafka_resp_err_t err;
if (!conf.run)
KC_FATAL("Program terminated while "
"producing message of %zd bytes", len);
err = rd_kafka_producev(
conf.rk,
RD_KAFKA_V_RKT(conf.rkt),
RD_KAFKA_V_PARTITION(conf.partition),
RD_KAFKA_V_MSGFLAGS(msgflags),
RD_KAFKA_V_VALUE(buf, len),
RD_KAFKA_V_KEY(key, key_len),
RD_KAFKA_V_HEADERS(hdrs),
RD_KAFKA_V_OPAQUE(msg_opaque),
RD_KAFKA_V_END);
if (!err) {
stats.tx++;
break;
}
if (err != RD_KAFKA_RESP_ERR__QUEUE_FULL)
KC_FATAL("Failed to produce message (%zd bytes): %s",
len, rd_kafka_err2str(err));
stats.tx_err_q++;
/* Internal queue full, sleep to allow
* messages to be produced/time out
* before trying again. */
rd_kafka_poll(conf.rk, 5);
} while (1);
/* Poll for delivery reports, errors, etc. */
rd_kafka_poll(conf.rk, 0);
}
/**
* Produce contents of file as a single message.
* Returns the file length on success, else -1.
*/
static ssize_t produce_file (const char *path) {
int fd;
void *ptr;
struct stat st;
ssize_t sz;
int msgflags = 0;
if ((fd = _COMPAT(open)(path, O_RDONLY)) == -1) {
KC_INFO(1, "Failed to open %s: %s\n", path, strerror(errno));
return -1;
}
if (fstat(fd, &st) == -1) {
KC_INFO(1, "Failed to stat %s: %s\n", path, strerror(errno));
_COMPAT(close)(fd);
return -1;
}
if (st.st_size == 0) {
KC_INFO(3, "Skipping empty file %s\n", path);
_COMPAT(close)(fd);
return 0;
}
#ifndef _MSC_VER
ptr = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (ptr == MAP_FAILED) {
KC_INFO(1, "Failed to mmap %s: %s\n", path, strerror(errno));
_COMPAT(close)(fd);
return -1;
}
sz = st.st_size;
msgflags = RD_KAFKA_MSG_F_COPY;
#else
ptr = malloc(st.st_size);
if (!ptr) {
KC_INFO(1, "Failed to allocate message for %s: %s\n",
path, strerror(errno));
_COMPAT(close)(fd);
return -1;
}
sz = _read(fd, ptr, st.st_size);
if (sz < st.st_size) {
KC_INFO(1, "Read failed for %s (%zd/%zd): %s\n",
path, sz, (size_t)st.st_size, sz == -1 ? strerror(errno) :
"incomplete read");
free(ptr);
close(fd);
return -1;
}
msgflags = RD_KAFKA_MSG_F_FREE;
#endif
KC_INFO(4, "Producing file %s (%"PRIdMAX" bytes)\n",
path, (intmax_t)st.st_size);
produce(ptr, sz, conf.fixed_key, conf.fixed_key_len, msgflags, NULL);
_COMPAT(close)(fd);
if (!(msgflags & RD_KAFKA_MSG_F_FREE)) {
#ifndef _MSC_VER
munmap(ptr, st.st_size);
#else
free(ptr);
#endif
}
return sz;
}
static char *rd_strnstr (const char *haystack, size_t size,
const char *needle, size_t needle_len) {
const char *nend = needle + needle_len - 1;
const char *t;
size_t of = needle_len - 1;
while (of < size &&
(t = (const char *)memchr((void *)(haystack + of),
(int)*nend,
size - of))) {
const char *n = nend;
const char *p = t;
do {
n--;
p--;
} while (n >= needle && *n == *p);
if (n < needle)
return (char *)p+1;
of = (size_t)(t - haystack) + 1;
}
return NULL;
}
/**
* Run producer, reading messages from 'fp' and producing to kafka.
* Or if 'pathcnt' is > 0, read messages from files in 'paths' instead.
*/
static void producer_run (FILE *fp, char **paths, int pathcnt) {
char errstr[512];
char tmp[16];
size_t tsize = sizeof(tmp);
if (rd_kafka_conf_get(conf.rk_conf, "transactional.id",
tmp, &tsize) == RD_KAFKA_CONF_OK && tsize > 1) {
KC_INFO(1, "Using transactional producer\n");
conf.txn = 1;
}
tsize = sizeof(tmp);
if (rd_kafka_conf_get(conf.rk_conf, "message.max.bytes",
tmp, &tsize) == RD_KAFKA_CONF_OK && tsize > 1) {
int msg_max_bytes = atoi(tmp);
KC_INFO(3, "Setting producer input buffer max size to "
"message.max.bytes value %d\n", msg_max_bytes);
conf.msg_size = msg_max_bytes;
}
/* Assign per-message delivery report callback. */
rd_kafka_conf_set_dr_msg_cb(conf.rk_conf, dr_msg_cb);
/* Create producer */
if (!(conf.rk = rd_kafka_new(RD_KAFKA_PRODUCER, conf.rk_conf,
errstr, sizeof(errstr))))
KC_FATAL("Failed to create producer: %s", errstr);
if (!conf.debug && conf.verbosity == 0)
rd_kafka_set_log_level(conf.rk, 0);
#if ENABLE_TXNS
if (conf.txn) {
rd_kafka_error_t *error;
error = rd_kafka_init_transactions(conf.rk,
conf.metadata_timeout*1000);
if (error)
KC_FATAL("init_transactions(): %s",
rd_kafka_error_string(error));
error = rd_kafka_begin_transaction(conf.rk);
if (error)
KC_FATAL("begin_transaction(): %s",
rd_kafka_error_string(error));
}
#endif
/* Create topic */
if (!(conf.rkt = rd_kafka_topic_new(conf.rk, conf.topic,
conf.rkt_conf)))
KC_FATAL("Failed to create topic %s: %s", conf.topic,
rd_kafka_err2str(rd_kafka_last_error()));
conf.rk_conf = NULL;
conf.rkt_conf = NULL;
if (pathcnt > 0 && !(conf.flags & CONF_F_LINE)) {
int i;
int good = 0;
/* Read messages from files, each file is its own message. */
for (i = 0 ; i < pathcnt ; i++)
if (produce_file(paths[i]) != -1)
good++;
if (!good)
conf.exitcode = 1;
else if (good < pathcnt)
KC_INFO(1, "Failed to produce from %i/%i files\n",
pathcnt - good, pathcnt);
} else {
struct inbuf inbuf;
struct buf *b;
int at_eof = 0;
inbuf_init(&inbuf, conf.msg_size, conf.delim, conf.delim_size);
/* Read messages from input, delimited by conf.delim */
while (conf.run &&
!(at_eof = !inbuf_read_to_delimeter(&inbuf, fp, &b))) {
int msgflags = 0;
char *buf = b->buf;
char *key = NULL;
size_t key_len = 0;
size_t len = b->size;
if (len == 0) {
buf_destroy(b);
continue;
}
/* Extract key, if desired and found. */
if (conf.flags & CONF_F_KEY_DELIM) {
char *t;
if ((t = rd_strnstr(buf, len,
conf.key_delim,
conf.key_delim_size))) {
key_len = (size_t)(t-buf);
key = buf;
buf = t + conf.key_delim_size;
len -= key_len + conf.key_delim_size;
if (conf.flags & CONF_F_NULL) {
if (len == 0)
buf = NULL;
if (key_len == 0)
key = NULL;
}
}
}
if (!key && conf.fixed_key) {
key = conf.fixed_key;
key_len = conf.fixed_key_len;
}
if (len < 1024) {
/* If message is smaller than this arbitrary
* threshold it will be more effective to
* copy the data in librdkafka. */
msgflags |= RD_KAFKA_MSG_F_COPY;
}
/* Produce message */
produce(buf, len, key, key_len, msgflags,
(msgflags & RD_KAFKA_MSG_F_COPY) ?
NULL : b);
if (conf.flags & CONF_F_TEE &&
fwrite(b->buf, b->size, 1, stdout) != 1)
KC_FATAL("Tee write error for message "
"of %zd bytes: %s",
b->size, strerror(errno));
if (msgflags & RD_KAFKA_MSG_F_COPY) {
/* librdkafka made a copy of the input. */
buf_destroy(b);
}
/* Enforce -c <cnt> */
if (stats.tx == (uint64_t)conf.msg_cnt)
conf.run = 0;
}
if (conf.run && !at_eof)
KC_FATAL("Unable to read message: %s",
strerror(errno));
}
#if ENABLE_TXNS
if (conf.txn) {
rd_kafka_error_t *error;
const char *what;
if (conf.term_sig) {
KC_INFO(0,
"Aborting transaction due to "
"termination signal\n");
what = "abort_transaction()";
error = rd_kafka_abort_transaction(
conf.rk, conf.metadata_timeout * 1000);
} else {
KC_INFO(1, "Committing transaction\n");
what = "commit_transaction()";
error = rd_kafka_commit_transaction(
conf.rk, conf.metadata_timeout * 1000);
if (!error)
KC_INFO(1,
"Transaction successfully committed\n");
}
if (error)
KC_FATAL("%s: %s", what, rd_kafka_error_string(error));
}
#endif
/* Wait for all messages to be transmitted */
conf.run = 1;
while (conf.run && rd_kafka_outq_len(conf.rk))
rd_kafka_poll(conf.rk, 50);
rd_kafka_topic_destroy(conf.rkt);
rd_kafka_destroy(conf.rk);
if (stats.tx_err_dr)
conf.exitcode = 1;
}
static void stop_partition (rd_kafka_message_t *rkmessage) {
if (!part_stop[rkmessage->partition]) {
/* Stop consuming this partition */
rd_kafka_consume_stop(rkmessage->rkt,
rkmessage->partition);
part_stop[rkmessage->partition] = 1;
part_stop_cnt++;
if (part_stop_cnt >= part_stop_thres)
conf.run = 0;
}
}
/**
* @brief Mark partition as not at EOF
*/
static void partition_not_eof (const rd_kafka_message_t *rkmessage) {
rd_kafka_topic_partition_t *rktpar;
if (conf.mode != 'G' || !conf.exit_eof ||
!conf.assignment || conf.eof_cnt == 0)
return;
/* Find partition in assignment */
rktpar = rd_kafka_topic_partition_list_find(
conf.assignment,
rd_kafka_topic_name(rkmessage->rkt),
rkmessage->partition);
if (!rktpar || rktpar->err != RD_KAFKA_RESP_ERR__PARTITION_EOF)
return;
rktpar->err = RD_KAFKA_RESP_ERR_NO_ERROR;
conf.eof_cnt--;
}
/**
* @brief Mark partition as at EOF
*/
static void partition_at_eof (rd_kafka_message_t *rkmessage) {
if (conf.mode == 'C') {
/* Store EOF offset.
* If partition is empty and at offset 0,
* store future first message (0). */
rd_kafka_offset_store(rkmessage->rkt,
rkmessage->partition,
rkmessage->offset == 0 ?
0 : rkmessage->offset-1);
if (conf.exit_eof) {
stop_partition(rkmessage);
}
} else if (conf.mode == 'G' && conf.exit_eof && conf.assignment) {
/* Find partition in assignment */
rd_kafka_topic_partition_t *rktpar;
rktpar = rd_kafka_topic_partition_list_find(
conf.assignment,
rd_kafka_topic_name(rkmessage->rkt),
rkmessage->partition);
if (rktpar && rktpar->err != RD_KAFKA_RESP_ERR__PARTITION_EOF) {
rktpar->err = RD_KAFKA_RESP_ERR__PARTITION_EOF;
conf.eof_cnt++;
if (conf.eof_cnt == conf.assignment->cnt)
conf.run = 0;
}
}
KC_INFO(1, "Reached end of topic %s [%"PRId32"] "
"at offset %"PRId64"%s\n",
rd_kafka_topic_name(rkmessage->rkt),
rkmessage->partition,
rkmessage->offset,
!conf.run ? ": exiting" : "");
}
/**
* Consume callback, called for each message consumed.
*/
static void consume_cb (rd_kafka_message_t *rkmessage, void *opaque) {
FILE *fp = opaque;
if (!conf.run)
return;
if (rkmessage->err) {
if (rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF) {
partition_at_eof(rkmessage);
return;
}
if (rkmessage->rkt)
KC_FATAL("Topic %s [%"PRId32"] error: %s",
rd_kafka_topic_name(rkmessage->rkt),
rkmessage->partition,
rd_kafka_message_errstr(rkmessage));
else
KC_FATAL("Consumer error: %s",
rd_kafka_message_errstr(rkmessage));
} else {
partition_not_eof(rkmessage);
}
if (conf.stopts) {
int64_t ts = rd_kafka_message_timestamp(rkmessage, NULL);
if (ts >= conf.stopts) {
stop_partition(rkmessage);
KC_INFO(1, "Reached stop timestamp for topic "
"%s [%"PRId32"] "
"at offset %"PRId64"%s\n",
rd_kafka_topic_name(rkmessage->rkt),
rkmessage->partition,
rkmessage->offset,
!conf.run ? ": exiting" : "");
return;
}
}
/* Print message */
fmt_msg_output(fp, rkmessage);
if (conf.mode == 'C') {
rd_kafka_offset_store(rkmessage->rkt,
rkmessage->partition,
rkmessage->offset);
}
if (++stats.rx == (uint64_t)conf.msg_cnt) {
conf.run = 0;
rd_kafka_yield(conf.rk);
}
}
#if RD_KAFKA_VERSION >= 0x00090000
static void throttle_cb (rd_kafka_t *rk, const char *broker_name,
int32_t broker_id, int throttle_time_ms, void *opaque){
KC_INFO(1, "Broker %s (%"PRId32") throttled request for %dms\n",
broker_name, broker_id, throttle_time_ms);
}
#endif
#if ENABLE_KAFKACONSUMER
static void print_partition_list (int is_assigned,
const rd_kafka_topic_partition_list_t
*partitions) {
int i;
for (i = 0 ; i < partitions->cnt ; i++) {
fprintf(stderr, "%s%s [%"PRId32"]",
i > 0 ? ", ":"",
partitions->elems[i].topic,
partitions->elems[i].partition);
}
fprintf(stderr, "\n");
}
#if ENABLE_INCREMENTAL_ASSIGN
static void
incremental_rebalance_cb (rd_kafka_t *rk, rd_kafka_resp_err_t err,
rd_kafka_topic_partition_list_t *partitions,
void *opaque) {
rd_kafka_error_t *error = NULL;
int i;
KC_INFO(1, "Group %s rebalanced: incremental %s of %d partition(s) "
"(memberid %s%s, %s rebalance protocol): ",
conf.group,
err == RD_KAFKA_RESP_ERR__ASSIGN_PARTITIONS ?
"assignment" : "revoke",
partitions->cnt,
rd_kafka_memberid(rk),
rd_kafka_assignment_lost(rk) ? ", assignment lost" : "",
rd_kafka_rebalance_protocol(rk));
switch (err)
{
case RD_KAFKA_RESP_ERR__ASSIGN_PARTITIONS:
if (conf.verbosity >= 1)
print_partition_list(1, partitions);
if (!conf.assignment)
conf.assignment =
rd_kafka_topic_partition_list_new(
partitions->cnt);
for (i = 0 ; i < partitions->cnt ; i++) {
rd_kafka_topic_partition_t *rktpar =
&partitions->elems[i];
/* Set start offset from -o .. */
if (conf.offset != RD_KAFKA_OFFSET_INVALID)
rktpar->offset = conf.offset;
rktpar->offset = conf.offset;
rd_kafka_topic_partition_list_add(conf.assignment,
rktpar->topic,
rktpar->partition);
}
error = rd_kafka_incremental_assign(rk, partitions);
break;
case RD_KAFKA_RESP_ERR__REVOKE_PARTITIONS:
if (conf.verbosity >= 1)
print_partition_list(1, partitions);
/* Remove partitions from conf.assignment in reverse order
* to minimize array shrink sizes. */
for (i = partitions->cnt - 1 ;
conf.assignment && i >= 0 ;
i--) {
rd_kafka_topic_partition_t *rktpar =
&partitions->elems[i];
rd_kafka_topic_partition_list_del(conf.assignment,
rktpar->topic,
rktpar->partition);
}
error = rd_kafka_incremental_unassign(rk, partitions);
break;
default:
KC_INFO(0, "failed: %s\n", rd_kafka_err2str(err));
break;
}
if (error) {
KC_ERROR("Incremental rebalance %s of %d partition(s) "
"failed: %s\n",
err == RD_KAFKA_RESP_ERR__ASSIGN_PARTITIONS ?
"assign" : "unassign",
partitions->cnt, rd_kafka_error_string(error));
rd_kafka_error_destroy(error);
}
}
#endif
static void rebalance_cb (rd_kafka_t *rk, rd_kafka_resp_err_t err,
rd_kafka_topic_partition_list_t *partitions,
void *opaque) {
rd_kafka_resp_err_t ret_err = RD_KAFKA_RESP_ERR_NO_ERROR;
#if ENABLE_INCREMENTAL_ASSIGN
if (!strcmp(rd_kafka_rebalance_protocol(rk), "COOPERATIVE")) {
incremental_rebalance_cb(rk, err, partitions, opaque);
return;
}
#endif
KC_INFO(1, "Group %s rebalanced (memberid %s): ",
conf.group, rd_kafka_memberid(rk));
switch (err)
{
case RD_KAFKA_RESP_ERR__ASSIGN_PARTITIONS:
if (conf.verbosity >= 1) {
fprintf(stderr, "assigned: ");
print_partition_list(1, partitions);
}
if (conf.offset != RD_KAFKA_OFFSET_INVALID) {
int i;
for (i = 0 ; i < partitions->cnt ; i++)
partitions->elems[i].offset = conf.offset;
}
if (conf.assignment)
rd_kafka_topic_partition_list_destroy(conf.assignment);
conf.assignment =
rd_kafka_topic_partition_list_copy(partitions);
ret_err = rd_kafka_assign(rk, partitions);
break;
case RD_KAFKA_RESP_ERR__REVOKE_PARTITIONS:
if (conf.verbosity >= 1) {
fprintf(stderr, "revoked: ");
print_partition_list(1, partitions);
}
if (conf.assignment) {
rd_kafka_topic_partition_list_destroy(conf.assignment);
conf.assignment = NULL;
}
ret_err = rd_kafka_assign(rk, NULL);
break;
default:
KC_INFO(0, "failed: %s\n", rd_kafka_err2str(err));
break;
}
if (ret_err)
KC_ERROR("Rebalance %s of %d partition(s) failed: %s\n",
err == RD_KAFKA_RESP_ERR__ASSIGN_PARTITIONS ?
"assign" : "unassign",
partitions->cnt, rd_kafka_err2str(ret_err));
}
/**
* Run high-level KafkaConsumer, write messages to 'fp'
*/
static void kafkaconsumer_run (FILE *fp, char *const *topics, int topic_cnt) {
char errstr[512];
rd_kafka_resp_err_t err;
rd_kafka_topic_partition_list_t *topiclist;
int i;
rd_kafka_conf_set_rebalance_cb(conf.rk_conf, rebalance_cb);
rd_kafka_conf_set_default_topic_conf(conf.rk_conf, conf.rkt_conf);
conf.rkt_conf = NULL;
/* Create consumer */
if (!(conf.rk = rd_kafka_new(RD_KAFKA_CONSUMER, conf.rk_conf,
errstr, sizeof(errstr))))
KC_FATAL("Failed to create consumer: %s", errstr);
conf.rk_conf = NULL;
/* Forward main event queue to consumer queue so we can
* serve both queues with a single consumer_poll() call. */
rd_kafka_poll_set_consumer(conf.rk);
if (conf.debug)
rd_kafka_set_log_level(conf.rk, LOG_DEBUG);
else if (conf.verbosity == 0)
rd_kafka_set_log_level(conf.rk, 0);
/* Build subscription set */
topiclist = rd_kafka_topic_partition_list_new(topic_cnt);
for (i = 0 ; i < topic_cnt ; i++)
rd_kafka_topic_partition_list_add(topiclist, topics[i], -1);
/* Subscribe */
if ((err = rd_kafka_subscribe(conf.rk, topiclist)))
KC_FATAL("Failed to subscribe to %d topics: %s\n",
topiclist->cnt, rd_kafka_err2str(err));
KC_INFO(1, "Waiting for group rebalance\n");
rd_kafka_topic_partition_list_destroy(topiclist);
/* Read messages from Kafka, write to 'fp'. */
while (conf.run) {
rd_kafka_message_t *rkmessage;
rkmessage = rd_kafka_consumer_poll(conf.rk, 100);
if (!rkmessage)
continue;
consume_cb(rkmessage, fp);
rd_kafka_message_destroy(rkmessage);
}
if ((err = rd_kafka_consumer_close(conf.rk)))
KC_FATAL("Failed to close consumer: %s\n",
rd_kafka_err2str(err));
/* Wait for outstanding requests to finish. */
conf.run = 1;
while (conf.run && rd_kafka_outq_len(conf.rk) > 0)
rd_kafka_poll(conf.rk, 50);
if (conf.assignment)
rd_kafka_topic_partition_list_destroy(conf.assignment);
rd_kafka_destroy(conf.rk);
}
#endif
/**
* Get offsets from conf.startts for consumer_run
*/
static int64_t *get_offsets (rd_kafka_metadata_topic_t *topic) {
int i;
int64_t *offsets;
rd_kafka_resp_err_t err;
rd_kafka_topic_partition_list_t *rktparlistp =
rd_kafka_topic_partition_list_new(1);
for (i = 0 ; i < topic->partition_cnt ; i++) {
int32_t partition = topic->partitions[i].id;
/* If -p <part> was specified: skip unwanted partitions */
if (conf.partition != RD_KAFKA_PARTITION_UA &&
conf.partition != partition)
continue;
rd_kafka_topic_partition_list_add(
rktparlistp,
rd_kafka_topic_name(conf.rkt),
partition)->offset = conf.startts;
if (conf.partition != RD_KAFKA_PARTITION_UA)
break;
}
err = rd_kafka_offsets_for_times(conf.rk, rktparlistp,
conf.metadata_timeout * 1000);
if (err)
KC_FATAL("offsets_for_times failed: %s", rd_kafka_err2str(err));
offsets = calloc(sizeof(int64_t), topic->partition_cnt);
for (i = 0 ; i < rktparlistp->cnt ; i++) {
const rd_kafka_topic_partition_t *p = &rktparlistp->elems[i];
offsets[p->partition] = p->offset;
}
rd_kafka_topic_partition_list_destroy(rktparlistp);
return offsets;
}
/**
* Run consumer, consuming messages from Kafka and writing to 'fp'.
*/
static void consumer_run (FILE *fp) {
char errstr[512];
rd_kafka_resp_err_t err;
const rd_kafka_metadata_t *metadata;
int i;
int64_t *offsets = NULL;
rd_kafka_queue_t *rkqu;
/* Create consumer */
if (!(conf.rk = rd_kafka_new(RD_KAFKA_CONSUMER, conf.rk_conf,
errstr, sizeof(errstr))))
KC_FATAL("Failed to create consumer: %s", errstr);
if (!conf.debug && conf.verbosity == 0)
rd_kafka_set_log_level(conf.rk, 0);
/* The callback-based consumer API's offset store granularity is
* not good enough for us, disable automatic offset store
* and do it explicitly per-message in the consume callback instead. */
if (rd_kafka_topic_conf_set(conf.rkt_conf,
"auto.commit.enable", "false",
errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK)
KC_FATAL("%s", errstr);
/* Create topic */
if (!(conf.rkt = rd_kafka_topic_new(conf.rk, conf.topic,
conf.rkt_conf)))
KC_FATAL("Failed to create topic %s: %s", conf.topic,
rd_kafka_err2str(rd_kafka_last_error()));
conf.rk_conf = NULL;
conf.rkt_conf = NULL;
/* Query broker for topic + partition information. */
if ((err = rd_kafka_metadata(conf.rk, 0, conf.rkt, &metadata,
conf.metadata_timeout * 1000)))
KC_FATAL("Failed to query metadata for topic %s: %s",
rd_kafka_topic_name(conf.rkt), rd_kafka_err2str(err));
/* Error handling */
if (metadata->topic_cnt == 0)
KC_FATAL("No such topic in cluster: %s",
rd_kafka_topic_name(conf.rkt));