-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathcli.cpp
More file actions
2102 lines (1686 loc) · 107 KB
/
cli.cpp
File metadata and controls
2102 lines (1686 loc) · 107 KB
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
#include "tank_client.h"
#include <date.h>
#include <fcntl.h>
#include <network.h>
#include <set>
#include <sys/stat.h>
#include <sys/types.h>
#include <sysexits.h>
#include <text.h>
#include <unordered_map>
//#ifdef SWITCH_PHAISTOS
#include <text_table.h>
//#endif
static uint64_t parse_timestamp(strwlen32_t s) {
strwlen32_t c;
struct tm tm;
if (s.StripPrefix(_S("T-"))) {
const char *p = s.data(), *const e = p + s.size();
if (p == e || !isdigit(*p)) {
return 0;
}
uint32_t v{0};
do {
v = v * 10 + (*(p++) - '0');
} while (p < e && isdigit(*p));
if (p < e) {
if (*p == 's' || *p == 'S') {
// seconds
} else if (*p == 'm' || *p == 'M') {
v *= 60;
} else if (*p == 'h' || *p == 'H') {
v *= 3600;
} else if (*p == 'd' || *p == 'D') {
v *= 86400;
}
}
return Timings::Seconds::ToMillis(time(nullptr) - v);
}
// for now, YYYYMMDDHH:MM:SS
// Eventually, will support more date/timeformats
if (s.StripPrefix(_S("today"))) {
auto now = time(nullptr);
localtime_r(&now, &tm);
} else if (s.StripPrefix(_S("yesterday"))) {
auto now = time(nullptr) - 86400;
localtime_r(&now, &tm);
} else {
if (s.size() < "20181001"_len) {
return 0;
}
c = s.Prefix(4);
if (!c.all_of_digits()) {
return 0;
}
s.StripPrefix(4);
tm.tm_year = c.AsUint32() - 1900;
s.StripPrefix(_S("."));
c = s.Prefix(2);
if (!c.all_of_digits()) {
return 0;
}
s.StripPrefix(2);
tm.tm_mon = c.AsUint32() - 1;
s.StripPrefix(_S("."));
c = s.Prefix(2);
if (!c.all_of_digits()) {
return 0;
}
s.StripPrefix(2);
tm.tm_mday = c.AsUint32();
}
if (s && (s.front() == '@' || s.front() == ':')) {
s.strip_prefix(1);
}
c = s.Prefix(2);
s.StripPrefix(2);
tm.tm_hour = c.AsUint32();
if (s && s.StripPrefix(_S(":"))) {
c = s.Prefix(2);
s.StripPrefix(2);
tm.tm_min = c.AsUint32();
if (s && s.StripPrefix(_S(":"))) {
c = s.Prefix(2);
s.StripPrefix(2);
tm.tm_sec = c.AsUint32();
} else {
tm.tm_sec = 0;
}
} else {
tm.tm_min = 0;
tm.tm_sec = 0;
}
tm.tm_isdst = -1;
// SLog(Date::ts_repr(mktime(&tm)), "\n"); exit(0);
if (const auto res = mktime(&tm); - 1 == res) {
return 0;
} else {
return Timings::Seconds::ToMillis(res);
}
}
static uint64_t lcrng(const uint64_t state) noexcept {
return state * 6364136223846793005 + 1442695040888963407;
}
int main(int argc, char *argv[]) {
Buffer topic, endpoint;
uint16_t partition{0};
bool partition_specified{false};
int r;
TankClient tank_client;
const char *const app = argv[0];
bool verbose{false}, retry{true /* now, explicitly to true */};
if (argc == 1) {
goto help;
}
tank_client.set_retry_strategy(TankClient::RetryStrategy::RetryNever);
while ((r = getopt(argc, argv, "+vb:t:p:hrS:R:")) != -1) // see GETOPT(3) for '+' initial character semantics
{
switch (r) {
case 'S':
tank_client.set_sock_sndbuf_size(strwlen32_t::make_with_cstr(optarg).AsUint32());
break;
case 'R':
tank_client.set_sock_rcvbuf_size(strwlen32_t::make_with_cstr(optarg).AsUint32());
break;
case 'r':
retry = true;
tank_client.set_retry_strategy(TankClient::RetryStrategy::RetryAlways);
break;
case 'v':
verbose = true;
break;
case 'b':
endpoint.clear();
endpoint.append(optarg);
break;
case 't': {
const auto s = str_view32::make_with_cstr(optarg);
topic.clear();
if (const auto p = s.Search('/')) {
const auto str = s.SuffixFrom(p + 1);
if (!str.IsDigits()) {
Print("Invalid partition [", str, "]\n");
return 1;
}
const auto v = str.AsInt32();
if (v < 0 || v > UINT16_MAX) {
Print("Invalid partition [", str, "]\n");
return 1;
}
topic.append(s.PrefixUpto(p));
partition = v;
partition_specified = true;
} else {
topic.append(s);
}
if (!IsBetweenRangeInclusive<uint32_t>(topic.size(), 1, 240)) {
Print("Inalid topic name '", topic, "'\n");
return 1;
}
} break;
case 'p': {
const auto s = str_view32::make_with_cstr(optarg);
if (!s.IsDigits()) {
Print("Invalid partition '", s, "'. Expected numeric id from 0 upto ", UINT16_MAX, "\n");
return 1;
}
const auto v = s.AsInt32();
if (v < 0 || v > UINT16_MAX) {
Print("Invalid partition\n");
return 1;
}
partition_specified = true;
partition = v;
} break;
case 'h':
help:
Print("Usage: ", app, " <settings> [other common options] <command> [args]\n");
Print("\nSettings:\n");
Print(Buffer{}.append(align_to(5), "-b broker endpoint"_s32, align_to(32), "The endpoint of the TANK broker. If not specified, the default is localhost:11011"_s32), "\n");
Print(Buffer{}.append(align_to(5), "-t topic"_s32, align_to(32), "Selected topic"_s32), "\n");
Print(Buffer{}.append(align_to(5), "-p partition"_s32, align_to(32), "Selected partition. You can also use -t topic/partition to specify both the topic and the partition with -t"_s32), "\n");
Print("\nOther common options:\n");
Print(Buffer{}.append(align_to(5), "-S bytes"_s32, align_to(32), "Sets TANK Client's socket send buffer size"_s32), "\n");
Print(Buffer{}.append(align_to(5), "-R bytes"_s32, align_to(32), "Sets TANK Client's socket receive buffer size"_s32), "\n");
Print(Buffer{}.append(align_to(5), "-v"_s32, align_to(32), "Enables Verbose output"_s32), "\n");
Print("\nCommands:\n");
Print(Buffer{}.append(align_to(5), "consume"_s32, align_to(32), "Consumes content from partition"_s32), "\n");
Print(Buffer{}.append(align_to(5), "produce"_s32, align_to(32), "Produce content(events, messages) to partition"_s32), "\n");
Print(Buffer{}.append(align_to(5), "benchmark"_s32, align_to(32), "Benchmark TANK"_s32), "\n");
Print(Buffer{}.append(align_to(5), "discover_partitions"_s32, align_to(32), "Enumerates all defined topic's partitions"_s32), "\n");
Print(Buffer{}.append(align_to(5), "create_topic"_s32, align_to(32), "Creates a new topic"_s32), "\n");
Print(Buffer{}.append(align_to(5), "mirror"_s32, align_to(32), "Mirror partitions across TANK nodes"_s32), "\n");
Print(Buffer{}.append(align_to(5), "reload_config"_s32, align_to(32), "Reload per-topic configuration"_s32), "\n");
Print(Buffer{}.append(align_to(5), "status"_s32, align_to(32), "Displays service status"_s32), "\n");
Print(Buffer{}.append(align_to(5), "discover_topics"_s32, align_to(32), "Enumerares created topics "_s32), "\n");
Print(Buffer{}.append(align_to(5), "topology"_s32, align_to(32), "Displays cluster nodes topology "_s32), "\n");
return 0;
default:
Print("Please use ", app, " -h for options\n");
return 1;
}
}
argc -= optind;
argv += optind;
try {
if (not endpoint.empty()) {
tank_client.set_default_leader(endpoint.as_s32());
} else {
// By default, access local instance
tank_client.set_default_leader(":11011"_s32);
}
} catch (const std::exception &e) {
Print("The broker endpoint \"", endpoint, "\" endpoint specified is invalid.\n");
Print("Examples of valid endpoints include:\n");
Print(Buffer{}.append(align_to(5), "localhost:11011"_s32), "\n");
Print(Buffer{}.append(align_to(5), ":11011"_s32), "\n");
Print(Buffer{}.append(align_to(5), "127.0.0.1:11011"_s32), "\n");
Print(Buffer{}.append(align_to(5), "127.0.0.1"_s32), "\n");
return 1;
}
if (0 == argc) {
Print("Command was not specified. Please run ", app, " for a list of all available commands.\n");
return 1;
}
const auto cmd = str_view32::make_with_cstr(argv[0]);
if (topic.empty()) {
if (not cmd.Eq(_S("status")) and
not cmd.Eq(_S("discover_topics")) and
not cmd.Eq(_S("topology"))) {
Print("Topic was not specified. Use ", ansifmt::bold, "-t", ansifmt::reset, " to specify the topic name\n");
return 1;
}
}
const TankClient::topic_partition topicPartition(topic.AsS8(), partition);
const auto consider_fault = [](const TankClient::fault &f) {
switch (f.type) {
case TankClient::fault::Type::UnsupportedReq:
Print("Unable to process request. Service likely running in cluster-aware mode?\n");
break;
case TankClient::fault::Type::BoundaryCheck:
Print("Boundary Check fault. first available sequence number is ", f.ctx.firstAvailSeqNum, ", high watermark is ", f.ctx.highWaterMark, "\n");
break;
case TankClient::fault::Type::UnknownTopic:
Print("Unknown topic '", f.topic, "' error\n");
break;
case TankClient::fault::Type::UnknownPartition:
Print("Unknown partition of '", f.topic, "' error\n");
break;
case TankClient::fault::Type::Access:
Print("Access Error\n");
break;
case TankClient::fault::Type::SystemFail:
Print("System Error\n");
break;
case TankClient::fault::Type::InsufficientReplicas:
Print("Insufficient Replicas\n");
break;
case TankClient::fault::Type::InvalidReq:
Print("Invalid Request\n");
break;
case TankClient::fault::Type::Network:
Print("Network error\n");
break;
case TankClient::fault::Type::AlreadyExists:
Print("Already Exists\n");
break;
case TankClient::fault::Type::Timeout:
Print("Timeout\n");
break;
default:
break;
}
};
if (cmd.Eq(_S("get")) || cmd.Eq(_S("consume"))) {
uint64_t next{0};
enum class Fields : uint8_t {
SeqNum = 0,
Key,
Content,
TS,
TS_MS,
Size,
TimeSince,
};
uint8_t displayFields{1u << uint8_t(Fields::Content)};
bool no_output = false;
size_t defaultMinFetchSize{128 * 1024 * 1024};
uint32_t pendingResp{0};
bool statsOnly{false}, asKV{false};
IOBuffer buf;
range64_t time_range{0, UINT64_MAX};
bool drain_and_exit{false}, respect_lbs{0};
uint64_t endSeqNum{UINT64_MAX};
str_view32 filter;
uint64_t msgs_limit = std::numeric_limits<uint64_t>::max();
auto minFetchSize = defaultMinFetchSize;
uint8_t op_flags = 0;
if (1 == argc) {
goto help_get;
}
optind = 0;
while ((r = getopt(argc, argv, "+SF:hBT:KdE:s:f:l:LZ:P")) != -1) {
switch (r) {
case 'P':
op_flags |= unsigned(ConsumeFlags::prefer_local_node);
break;
case 'Z':
minFetchSize = str_view32::make_with_cstr(optarg).as_uint32();
break;
case 'L':
respect_lbs = true;
break;
case 'l':
msgs_limit = str_view32::make_with_cstr(optarg).as_uint64();
break;
case 'f':
filter.set(optarg, strlen(optarg));
break;
case 'E':
endSeqNum = strwlen32_t::make_with_cstr(optarg).AsUint64();
break;
case 'd':
drain_and_exit = true;
break;
case 'K':
asKV = true;
break;
case 's':
defaultMinFetchSize = strwlen32_t::make_with_cstr(optarg).AsUint64();
if (!defaultMinFetchSize) {
Print("Invalid fetch size value\n");
return 1;
}
break;
case 'T': {
str_view32 spec = str_view32::make_with_cstr(optarg);
const auto [s, e] = TankClient::parse_time_window(spec);
if (0 == s) {
Print("Unexpected time window notation\n");
return 1;
}
time_range.offset = Timings::Seconds::ToMillis(s);
if (e == std::numeric_limits<time_t>::max()) {
time_range.len = std::numeric_limits<uint64_t>::max() - time_range.offset;
} else {
time_range.len = Timings::Seconds::ToMillis(e + 1u /* inclusive */) - time_range.offset;
}
} break;
case 'S':
statsOnly = true;
break;
case 'F':
displayFields = 0;
for (const auto it : strwlen32_t::make_with_cstr(optarg).Split(',')) {
if (it.Eq(_S("ignore"))) {
no_output = true;
break;
} else if (it.Eq(_S("seqnum"))) {
displayFields |= 1u << uint8_t(Fields::SeqNum);
} else if (it.Eq(_S("key"))) {
displayFields |= 1u << uint8_t(Fields::Key);
} else if (it.Eq(_S("content"))) {
displayFields |= 1u << uint8_t(Fields::Content);
} else if (it.Eq(_S("ts"))) {
displayFields |= 1u << uint8_t(Fields::TS);
} else if (it.Eq(_S("size"))) {
displayFields |= 1u << uint8_t(Fields::Size);
} else if (it.Eq(_S("ts_ms"))) {
displayFields |= 1u << uint8_t(Fields::TS_MS);
} else if (it.Eq(_S("time_since"))) {
displayFields |= 1u << uint8_t(Fields::TimeSince);
} else {
Print("Unknown field '", it, "'\n");
return 1;
}
}
break;
case 'h':
help_get:
Print("Usage: ", app, " get [options] <start-spec>\n");
Print(Buffer{}.append(left_aligned(5, "Consumes/retrieves messages from the specified TANK <topic>/<partition>.\n\nBy default, the retrieved messages content will be displayed in stdout, but you can optionally specify a different display format or use the -S option for display of statistics related to the events retrieved.\n\nIt will begin reading starting from <start-spec>\n<start-spec> can be \"EOF\" (so that it will begin reading from the end of the partition, effectively, \"tailing\" the partition), or a sequence number. If the -T option is used, <start-spec> can be ommitted(if it is specified togeher with -T, <start-spec> is ignored)."_s32, 76)), "\n");
Print("\nOptions:\n\n"_s32);
Print(Buffer{}.append(align_to(3), "-F <format>"_s32), "\n");
Print(Buffer{}.append(left_aligned(5, "Specify a comma separated fields to be displayed\nOverrides the default display(only content) and accepts the following valid field names: 'seqnum', 'key', 'content', 'ts'"_s32, 76)), "\n\n");
Print(Buffer{}.append(align_to(3), "-S"_s32), "\n");
Print(Buffer{}.append(left_aligned(5, "Displays statistics about retrieved messages instead of the messages themselves"_s32, 76)), "\n\n");
Print(Buffer{}.append(align_to(3), "-P"_s32), "\n");
Print(Buffer{}.append(left_aligned(5, "Prefers local node for consume requests"_s32, 76)), "\n\n");
Print(Buffer{}.append(align_to(3), "-l <limit>"_s32), "\n");
Print(Buffer{}.append(left_aligned(5, "Limit number of messages output"_s32, 76)), "\n\n");
Print(Buffer{}.append(align_to(3), "-E <sequence number>"_s32), "\n");
Print(Buffer{}.append(left_aligned(5, "When specified, it will stop as soon as it processes a message with seqnumber number >= the specified sequence number"_s32, 76)), "\n\n");
Print(Buffer{}.append(align_to(3), "-d"_s32, "\n"));
Print(Buffer{}.append(left_aligned(5, "When specified, it will stop as soon as the partition has been drained. That is, as soon as a consume request returns no more messages"_s32, 76)), "\n\n");
Print(Buffer{}.append(align_to(3), "-L"_s32, "\n"));
Print(Buffer{}.append(left_aligned(5, "When specified, it will try to output indivisable lines to stdout. This apparently affects some programs like mtail"_s32, 76)), "\n\n");
Print(Buffer{}.append(align_to(3), "-T <spec>"_s32, "\n"));
Print(Buffer{}.append(left_aligned(5, "With this option, you can specify the beginning and optionally the end of the range of messages to consume by time, as opposed to by sequence number.\nThe <spec> supports three different notations:\n <start>\n <start>-<end>\n <start>+<span>\n\nFor <start> and <end> you can either use T[-[N(DHMS)]] to denote the current wall time (optionally offsetting by a specified amount), or you can specify it using [YYYY][[.][MM][[.][DD][[@]HH[:[MM][:SS]]]]] notation.\n<span> can be represented as <countUNIT> where count unit is either (s, h, m, w) for seconds, hours, minutes, weeks.\n\nExamples:\n -T 2018.09.15@20:30: The first message's timestamp shall be >= that specified time\n -T 2018.09.15@20:30-2018.09.20@10:30: The first message's timestamp shall be>= the specified start time and the last message's timestamp shall be <= the specified end time\n -T T-1h+2m: Th first message's timestamp shall be >= 1 hour ago and the last message's timestamp shall be <= 2 minutes past that specified start time\n\nThis tool will use binary search to quickly determine the sequence number of a message that is close to the message specified by the start time and then it will use linear search to advance to the appropriate message."_s32, 76)), "\n\n");
return 0;
default:
return 1;
}
}
argc -= optind;
argv += optind;
if (time_range.offset) {
// not required, we 'll determine it based on binary search triangulation
next = 0;
} else if (argc != 1) {
Print("Expected <sequence-number> with _no additional_arguments_ to begin consuming from. Please see ", app, " consume -h\n");
return 1;
} else {
const auto from = str_view32::make_with_cstr(argv[0]);
if (from.EqNoCase(_S("beginning")) || from.Eq(_S("first")))
next = 0;
else if (from.EqNoCase(_S("end")) || from.EqNoCase(_S("eof")))
next = UINT64_MAX;
else if (!from.IsDigits()) {
Print("Expected either \"beginning\", \"end\" or a sequence number for -f option\n");
return 1;
} else {
next = from.as_uint64();
}
}
size_t totalMsgs{0}, sumBytes{0};
if (const auto seek_ts = time_range.offset) {
enum {
trace = false,
};
const auto before = Timings::Microseconds::Tick();
try {
next = tank_client.sequence_number_by_event_time(topicPartition, seek_ts, 5 * 60 * 100);
} catch (std::exception &e) {
Print("Failed to determine sequence number by timestamp:", e.what(), "\n");
return 1;
}
if (trace) {
SLog("Took ", duration_repr(Timings::Microseconds::Since(before)), " to determine sequence number\n");
}
}
const auto b = Timings::Microseconds::Tick();
std::size_t nwfaults_reries = 0;
for (const auto time_range_end = time_range.offset + time_range.size();;) {
if (0 == pendingResp) {
if (verbose) {
Print("Requesting from ", next, " ", minFetchSize, ", op_flags = ", op_flags, "\n");
}
pendingResp = tank_client.consume_from(topicPartition,
next,
minFetchSize,
drain_and_exit ? 0 : std::numeric_limits<uint32_t>::max(),
0,
op_flags);
if (0 == pendingResp) {
Print("Unable to issue consume request. Will abort\n");
return 1;
}
}
try {
tank_client.poll();
} catch (const std::exception &e) {
tank_client.reset();
Timings::Seconds::Sleep(1);
pendingResp = 0;
continue;
}
if (!tank_client.faults().empty()) {
for (const auto &it : tank_client.faults()) {
consider_fault(it);
if (retry && it.type == TankClient::fault::Type::Network) {
Timings::Milliseconds::Sleep(500);
if (++nwfaults_reries == 4) {
Print("Tried for too long; aborting\n");
return 1;
}
} else if (it.type == TankClient::fault::Type::BoundaryCheck) {
nwfaults_reries = 0;
next = it.adjust_seqnum_by_boundaries(next);
} else {
nwfaults_reries = 0;
tank_client.reset();
return 1;
}
}
pendingResp = 0;
} else {
nwfaults_reries = 0;
}
if (tank_client.consumed().empty()) {
continue;
}
if (verbose) {
SLog("consumed ", tank_client.consumed().size(), "\n");
}
pendingResp = 0;
for (const auto &it : tank_client.consumed()) {
if (verbose) {
SLog("Drained:", it.drained, ", msgs = ", it.msgs.size(), "\n");
}
if (drain_and_exit && it.drained) {
// Drained if we got no message in the response, and if the size we specified
// is <= next.minFetchSize. This is important because we could get no messages
// because the message is so large the minFetchSize we provided for the request was too low
goto out;
}
if (statsOnly) {
if (not filter) {
Print(">> ", dotnotation_repr(it.msgs.size()), " messages\n");
} else {
std::size_t n = 0;
for (const auto m : it.msgs) {
n += static_cast<bool>(m->content.Search(filter.data(), filter.size()));
}
Print(">> ", dotnotation_repr(n), " messages\n");
}
if (time_range.offset) {
bool should_abort{false};
if (verbose) {
for (const auto m : it.msgs) {
if (time_range.Contains(m->ts)) {
if (filter and not m->content.Search(filter.data(), filter.size())) {
continue;
}
Print(m->seqNum, ": ", size_repr(m->content.size()), "\n");
sumBytes += m->content.len + m->key.len + sizeof(uint64_t);
if (++totalMsgs == msgs_limit) {
goto out;
}
} else if (m->ts >= time_range_end) {
should_abort = true;
}
}
} else {
for (const auto m : it.msgs) {
if (time_range.Contains(m->ts)) {
if (filter and not m->content.Search(filter.data(), filter.size())) {
continue;
}
sumBytes += m->content.len + m->key.len + sizeof(uint64_t);
if (++totalMsgs == msgs_limit) {
goto out;
}
} else if (m->ts >= time_range_end) {
should_abort = true;
}
}
}
if (should_abort) {
goto out;
}
} else {
totalMsgs += it.msgs.size();
if (verbose) {
for (const auto m : it.msgs) {
if (filter and not m->content.Search(filter.data(), filter.size())) {
continue;
}
Print(m->seqNum, ": ", size_repr(m->content.size()), "\n");
sumBytes += m->content.len + m->key.len + sizeof(uint64_t);
if (++totalMsgs == msgs_limit) {
goto out;
}
}
} else {
for (const auto m : it.msgs) {
if (filter and not m->content.Search(filter.data(), filter.size())) {
continue;
}
sumBytes += m->content.len + m->key.len + sizeof(uint64_t);
if (++totalMsgs == msgs_limit) {
goto out;
}
}
}
}
} else {
size_t sum{0};
bool should_abort{false};
if (!time_range.offset) {
for (const auto m : it.msgs) {
if (filter && !m->content.Search(filter.data(), filter.size())) {
continue;
}
sum += m->content.size();
}
sum += it.msgs.size() * 2;
} else {
for (const auto m : it.msgs) {
if (time_range.Contains(m->ts)) {
if (filter && !m->content.Search(filter.data(), filter.size())) {
continue;
}
sum += m->content.size();
sum += 2;
}
}
}
buf.clear();
buf.reserve(sum);
for (const auto m : it.msgs) {
if (m->seqNum > endSeqNum or m->ts >= time_range_end) {
should_abort = true;
break;
} else if (time_range.Contains(m->ts)) {
if (filter and not m->content.Search(filter.data(), filter.size())) {
continue;
}
if (no_output) {
//
} else {
if (asKV) {
buf.append(m->seqNum, " [", m->key, "] = [", m->content, "]");
} else if (displayFields) {
if (displayFields & (1u << uint8_t(Fields::TS))) {
buf.append(Date::ts_repr(Timings::Milliseconds::ToSeconds(m->ts)), ':');
}
if (displayFields & (1u << uint8_t(Fields::TS_MS))) {
buf.append(m->ts, ':');
}
if (displayFields & (1u << uint8_t(Fields::SeqNum))) {
buf.append("seq=", m->seqNum, ':');
}
if (displayFields & (1u << uint8_t(Fields::Size))) {
buf.append("size=", m->content.size(), ':');
}
if (displayFields & (1u << unsigned(Fields::Key))) {
buf.append('[', m->key, "]:"_s32);
}
if (displayFields & (1u << uint8_t(Fields::Content))) {
buf.append(m->content);
}
if (displayFields & (1u << uint8_t(Fields::TimeSince))) {
buf.append(duration_repr(Timings::Milliseconds::ToMicros(Timings::Milliseconds::SysTime() - m->ts)));
}
} else {
buf.append(m->content);
}
buf.append('\n');
}
if (++totalMsgs == msgs_limit) {
break;
}
}
}
if (auto s = buf.as_s32()) {
if (respect_lbs) {
// this _may_ be important for some programs
// that may expect to always read termined lines from stdin
// as opposed to input that doesn't terminate in a new line
// see setbuf(), setvbuf()
static constexpr size_t threshold = 8192;
while (s) {
const auto *p = s.data();
const auto e = std::min(s.end(), p + threshold);
const char *upto = e;
for (; p < e; ++p) {
if (*p == '\n') {
upto = p + 1;
}
}
const auto span = std::distance(s.data(), upto);
if (const auto r = write(STDOUT_FILENO, s.data(), span); r != span) {
IMPLEMENT_ME();
}
s.strip_prefix(span);
}
} else {
do {
const auto r = write(STDOUT_FILENO, s.data(), s.size());
if (r == -1) {
Print("(Failed to output data to stdout:", strerror(errno), ". Exiting\n");
}
s.strip_prefix(r);
} while (s);
}
}
if (should_abort || totalMsgs >= msgs_limit) {
goto out;
}
}
// SLog("Current = ", next, " ", it.next.seq_num, " ", minFetchSize, " ", it.next.min_fetch_size, "\n");
minFetchSize = std::max<std::size_t>(it.next.min_fetch_size, minFetchSize);
next = it.next.seq_num;
}
}
out:
if (statsOnly) {
Print(dotnotation_repr(totalMsgs), " messages consumed in ", duration_repr(Timings::Microseconds::Since(b)), ", ", size_repr(sumBytes), " consumed\n");
}
} else if (cmd.Eq(_S("topology"))) {
optind = 0;
for (int r; (r = getopt(argc, argv, "h")) != -1;) {
switch (r) {
case 'h':
Print("Usage ", app, " topology\n");
Print(Buffer{}.append(left_aligned(5, "Display cluster topology"_s32), "\n"));
return 0;
default:
return 1;
}
}
argc -= optind;
argv += optind;
const auto req_id = tank_client.discover_topology();
if (0 == req_id) {
Print("Unable to schedule request\n");
return 0;
}
while (tank_client.should_poll()) {
tank_client.poll();
for (const auto &it : tank_client.faults()) {
consider_fault(it);
}
if (tank_client.discovered_topologies().empty()) {
continue;
}
const auto &res = tank_client.discovered_topologies().front();
if (0 == res.nodes.size) {
Print("Node is operating in stand-alone mode\n");
return 0;
}
Print("Cluster name:", res.cluster_name, "\n");
Print(Buffer{}.append("ID"_s32, align_to(8), "Available"_s32, align_to(20), "Blocked"_s32, align_to(32), "Endpoint"_s32, "\n"));
for (std::size_t i = 0; i < res.nodes.size; ++i) {
const auto &it = res.nodes.data[i];
Print(Buffer{}.append(it.id, align_to(8), it.available ? 'Y' : 'N', align_to(20), it.blocked ? 'Y' : 'N', align_to(32), it.ep, '\n'));
}
}
return 0;
} else if (cmd.Eq(_S("discover_topics"))) {
optind = 0;
for (int r; (r = getopt(argc, argv, "h")) != -1;) {
switch (r) {
case 'h':
Print("Usage ", app, " discover_topics\n");
Print(Buffer{}.append(left_aligned(5, "Enumerates cluster topics"_s32), "\n"));
return 0;
default:
return 1;
}
}
argc -= optind;
argv += optind;
const auto req_id = tank_client.discover_topics();
if (0 == req_id) {
Print("Unable to schedule request\n");
return 1;
}
while (tank_client.should_poll()) {
tank_client.poll();
for (const auto &it : tank_client.faults()) {
consider_fault(it);
}
if (tank_client.discovered_topics().empty()) {
continue;
}
const auto &resp = tank_client.discovered_topics().front();
for (uint32_t i = 0; i < resp.topics.size; ++i) {
const auto &it = resp.topics.data[i];
Print(it.name, " ", it.partitions, " partitions\n");
}
}
return 0;
} else if (cmd.Eq(_S("status"))) {
optind = 0;
while ((r = getopt(argc, argv, "h")) != -1) {
switch (r) {
case 'h':
Print("Usage ", app, " status\n");
Print(Buffer{}.append(left_aligned(5, "Outputs service status"_s32, 76)), "\n");
return 0;
default:
return 1;
}
}
argc -= optind;
argv += optind;
const auto req_id = tank_client.service_status();
if (!req_id) {
Print("Unable to schedule service status request\n");
return 1;
}
while (tank_client.should_poll()) {
tank_client.poll();
for (const auto &it : tank_client.faults()) {
consider_fault(it);
}
for (const auto &it : tank_client.statuses()) {
Print(Buffer{}.append("Topics"_s32, align_to(32), dotnotation_repr(it.counts.topics)), "\n");
Print(Buffer{}.append("Partitions"_s32, align_to(32), dotnotation_repr(it.counts.partitions)), "\n");
Print(Buffer{}.append("Open Partitions"_s32, align_to(32), dotnotation_repr(it.counts.open_partitions)), "\n");
#if 0
Print(Buffer{}.append("Open Partitions Time"_s32, align_to(32), dotnotation_repr(it.metrics.time_open_partitions)), "ms\n");
#else
Print(Buffer{}.append("Open Partitions Time"_s32, align_to(32), duration_repr(Timings::Milliseconds::ToMicros(it.metrics.time_open_partitions))), "\n");
#endif
if (it.cluster_name.len) {
Print(Buffer{}.append("Nodes"_s32, align_to(32), dotnotation_repr(it.counts.nodes)), "\n");
Print(Buffer{}.append("Cluster"_s32, align_to(32), str_view32(it.cluster_name.data, it.cluster_name.len)), "\n");
}
if (const auto v = it.startup_ts) {
Print(Buffer{}.append("Startup"_s32, align_to(32), Date::ts_repr(v)), "\n");
}
if (const auto v = it.version) {
Print(Buffer{}.append("Version"_s32, align_to(32), v / 100, '.', v % 100), "\n");
}
}
}
return 0;