-
Notifications
You must be signed in to change notification settings - Fork 1k
/
cdc_service-int-test.cc
2568 lines (2166 loc) · 102 KB
/
cdc_service-int-test.cc
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
// Copyright (c) YugaByte, Inc.
#include "yb/util/flags.h"
#include "yb/common/wire_protocol.h"
#include "yb/common/wire_protocol-test-util.h"
#include "yb/common/ql_value.h"
#include "yb/consensus/log.h"
#include "yb/consensus/log_reader.h"
#include "yb/cdc/cdc_service.h"
#include "yb/cdc/cdc_service.proxy.h"
#include "yb/cdc/cdc_state_table.h"
#include "yb/client/error.h"
#include "yb/client/schema.h"
#include "yb/client/session.h"
#include "yb/client/table.h"
#include "yb/client/table_handle.h"
#include "yb/client/yb_op.h"
#include "yb/client/yb_table_name.h"
#include "yb/client/client-test-util.h"
#include "yb/dockv/primitive_value.h"
#include "yb/dockv/doc_key.h"
#include "yb/dockv/value_type.h"
#include "yb/docdb/docdb_test_util.h"
#include "yb/gutil/casts.h"
#include "yb/gutil/walltime.h"
#include "yb/integration-tests/cdc_test_util.h"
#include "yb/integration-tests/cluster_itest_util.h"
#include "yb/integration-tests/mini_cluster.h"
#include "yb/integration-tests/yb_mini_cluster_test_base.h"
#include "yb/master/master_cluster.proxy.h"
#include "yb/master/master_defaults.h"
#include "yb/master/mini_master.h"
#include "yb/rpc/messenger.h"
#include "yb/rpc/rpc_controller.h"
#include "yb/tablet/tablet.h"
#include "yb/tablet/tablet_metadata.h"
#include "yb/tablet/tablet_peer.h"
#include "yb/tserver/mini_tablet_server.h"
#include "yb/tserver/tablet_server.h"
#include "yb/tserver/ts_tablet_manager.h"
#include "yb/tserver/tserver_service.proxy.h"
#include "yb/util/backoff_waiter.h"
#include "yb/util/format.h"
#include "yb/util/metrics.h"
#include "yb/util/monotime.h"
#include "yb/util/slice.h"
#include "yb/util/status_format.h"
#include "yb/util/sync_point.h"
#include "yb/util/test_thread_holder.h"
#include "yb/util/tsan_util.h"
#include "yb/yql/cql/ql/util/errcodes.h"
#include "yb/yql/cql/ql/util/statement_result.h"
using namespace std::chrono_literals;
using std::string;
DECLARE_bool(TEST_record_segments_violate_max_time_policy);
DECLARE_bool(TEST_record_segments_violate_min_space_policy);
DECLARE_bool(enable_load_balancing);
DECLARE_bool(enable_log_retention_by_op_idx);
DECLARE_bool(enable_ysql);
DECLARE_double(leader_failure_max_missed_heartbeat_periods);
DECLARE_int32(cdc_min_replicated_index_considered_stale_secs);
DECLARE_int32(cdc_state_checkpoint_update_interval_ms);
DECLARE_uint32(cdc_wal_retention_time_secs);
DECLARE_int32(client_read_write_timeout_ms);
DECLARE_int32(follower_unavailable_considered_failed_sec);
DECLARE_int32(log_max_seconds_to_retain);
DECLARE_int32(log_min_seconds_to_retain);
DECLARE_int32(log_min_segments_to_retain);
DECLARE_int32(min_leader_stepdown_retry_interval_ms);
DECLARE_int32(update_min_cdc_indices_interval_secs);
DECLARE_int64(TEST_simulate_free_space_bytes);
DECLARE_int64(log_stop_retaining_min_disk_mb);
DECLARE_uint64(log_segment_size_bytes);
DECLARE_int32(update_metrics_interval_ms);
DECLARE_bool(enable_collect_cdc_metrics);
DECLARE_bool(get_changes_honor_deadline);
DECLARE_int32(cdc_read_rpc_timeout_ms);
DECLARE_int32(TEST_get_changes_read_loop_delay_ms);
DECLARE_double(cdc_read_safe_deadline_ratio);
DECLARE_bool(TEST_xcluster_simulate_have_more_records);
DECLARE_bool(TEST_xcluster_skip_meta_ops);
DECLARE_bool(TEST_cdc_inject_replication_index_update_failure);
DECLARE_bool(TEST_disable_wal_retention_time);
DECLARE_uint32(cdcsdk_retention_barrier_no_revision_interval_secs);
DECLARE_double(cdc_get_changes_free_rpc_ratio);
DECLARE_int32(rpc_workers_limit);
DECLARE_uint64(transaction_manager_workers_limit);
DECLARE_bool(cdc_populate_end_markers_transactions);
DECLARE_string(vmodule);
METRIC_DECLARE_entity(cdc);
METRIC_DECLARE_gauge_int64(last_read_opid_index);
DECLARE_bool(enable_metacache_partial_refresh);
namespace yb {
namespace log {
class LogReader;
}
namespace cdc {
using client::TableHandle;
using client::YBSessionPtr;
using rpc::RpcController;
const std::string kCDCTestKeyspace = "my_keyspace";
const std::string kCDCTestTableName = "cdc_test_table";
const client::YBTableName kTableName(YQL_DATABASE_CQL, kCDCTestKeyspace, kCDCTestTableName);
CDCServiceImpl* CDCService(tserver::TabletServer* tserver) {
return down_cast<CDCServiceImpl*>(
tserver->rpc_server()->TEST_service_pool("yb.cdc.CDCService")->TEST_get_service().get());
}
class CDCServiceTest : public YBMiniClusterTestBase<MiniCluster> {
protected:
void SetUp() override {
CHECK_OK(SET_FLAG(vmodule, "cdc*=4"));
YBMiniClusterTestBase::SetUp();
MiniClusterOptions opts;
SetAtomicFlag(false, &FLAGS_enable_ysql);
SetAtomicFlag(1000, &FLAGS_update_metrics_interval_ms);
ANNOTATE_UNPROTECTED_WRITE(FLAGS_cdcsdk_retention_barrier_no_revision_interval_secs) = 0;
opts.num_tablet_servers = server_count();
opts.num_masters = 1;
cluster_.reset(new MiniCluster(opts));
ASSERT_OK(cluster_->Start());
client_ = ASSERT_RESULT(cluster_->CreateClient());
cdc_proxy_ = std::make_unique<CDCServiceProxy>(
&client_->proxy_cache(),
HostPort::FromBoundEndpoint(cluster_->mini_tablet_server(0)->bound_rpc_addr()));
CreateTable(tablet_count(), &table_);
}
Status DeleteXClusterStream(const xrepl::StreamId& stream_id) {
return client_->DeleteCDCStream(stream_id, true /*force_delete*/);
}
void DoTearDown() override {
if (stream_id_) {
ASSERT_OK(
client_->DeleteCDCStream(stream_id_, true /*force_delete*/, true /*ignore_errors*/));
// wait for stream to completely finish deleting
}
Result<bool> exist = client_->TableExists(kTableName);
ASSERT_OK(exist);
if (exist.get()) {
ASSERT_OK(client_->DeleteTable(kTableName));
}
client_.reset();
if (cluster_) {
cluster_->Shutdown();
cluster_.reset();
}
YBMiniClusterTestBase::DoTearDown();
}
void CreateTable(int num_tablets, TableHandle* table);
void GetTablets(std::vector<TabletId>* tablet_ids,
const client::YBTableName& table_name = kTableName);
std::string GetTablet(const client::YBTableName& table_name = kTableName);
void GetChanges(
const TabletId& tablet_id, const xrepl::StreamId& stream_id, int64_t term, int64_t index,
bool* has_error = nullptr, ::yb::cdc::CDCErrorPB_Code* code = nullptr);
void GetChangesWithResp(
const TabletId& tablet_id, const xrepl::StreamId& stream_id, int64_t term, int64_t index,
GetChangesResponsePB* change_resp, bool* has_error = nullptr,
::yb::cdc::CDCErrorPB_Code* code = nullptr);
void GetAllChanges(
const TabletId& tablet_id, const xrepl::StreamId& stream_id,
GetChangesResponsePB* change_resp);
void WriteTestRow(
int32_t key, int32_t int_val, const string& string_val, const TabletId& tablet_id,
const std::shared_ptr<tserver::TabletServerServiceProxy>& proxy);
Status WriteToProxyWithRetries(
const std::shared_ptr<tserver::TabletServerServiceProxy>& proxy,
const tserver::WriteRequestPB& req, tserver::WriteResponsePB* resp, RpcController* rpc);
Status GetChangesWithRetries(
const GetChangesRequestPB& change_req, GetChangesResponsePB* change_resp,
int timeout_ms, int max_attempts = 3);
Status GetChangesInitialSchema(GetChangesRequestPB const& change_req,
CDCCheckpointPB* mutable_checkpoint);
tserver::MiniTabletServer* GetLeaderForTablet(const std::string& tablet_id);
virtual int server_count() { return 1; }
virtual int tablet_count() { return 1; }
std::unique_ptr<CDCServiceProxy> cdc_proxy_;
std::unique_ptr<client::YBClient> client_;
xrepl::StreamId stream_id_ = xrepl::StreamId::Nil();
TableHandle table_;
};
void CDCServiceTest::CreateTable(int num_tablets, TableHandle* table) {
ASSERT_OK(client_->CreateNamespaceIfNotExists(kTableName.namespace_name(),
kTableName.namespace_type()));
client::YBSchemaBuilder builder;
builder.AddColumn("key")->Type(DataType::INT32)->HashPrimaryKey()->NotNull();
builder.AddColumn("int_val")->Type(DataType::INT32);
builder.AddColumn("string_val")->Type(DataType::STRING);
TableProperties table_properties;
table_properties.SetTransactional(true);
builder.SetTableProperties(table_properties);
ASSERT_OK(table->Create(kTableName, num_tablets, client_.get(), &builder));
}
Result<QLValuePB> ExtractValue(
const Schema& schema, const cdc::KeyValuePairPB& change, std::string expected_col_name) {
Slice key(change.key().data(), change.key().size());
const auto key_size =
VERIFY_RESULT(dockv::DocKey::EncodedSize(key, dockv::DocKeyPart::kWholeDocKey));
Slice key_column = key.WithoutPrefix(key_size);
dockv::KeyEntryValue column_id;
RETURN_NOT_OK(column_id.DecodeFromKey(&key_column));
SCHECK_EQ(column_id.type(), dockv::KeyEntryType::kColumnId, IllegalState, "UnExpected column id");
dockv::Value decoded_value;
RETURN_NOT_OK(decoded_value.Decode(change.value().binary_value()));
const ColumnSchema& col = VERIFY_RESULT(schema.column_by_id(column_id.GetColumnId()));
SCHECK_EQ(col.name(), expected_col_name, IllegalState, "Unexpected column name");
QLValuePB value;
decoded_value.primitive_value().ToQLValuePB(col.type(), &value);
return value;
}
void AssertChangeRecords(
const Schema& schema, const google::protobuf::RepeatedPtrField<cdc::KeyValuePairPB>& changes,
int32_t expected_int, std::string expected_str) {
ASSERT_EQ(changes.size(), 3);
auto int_val = ASSERT_RESULT(ExtractValue(schema, changes[1], "int_val"));
ASSERT_EQ(int_val.int32_value(), expected_int);
auto str_val = ASSERT_RESULT(ExtractValue(schema, changes[2], "string_val"));
ASSERT_EQ(str_val.string_value(), expected_str);
}
void VerifyCdcStateNotEmpty(client::YBClient* client) {
CDCStateTable cdc_state_table(client);
Status s;
auto table_range = ASSERT_RESULT(
cdc_state_table.GetTableRange(CDCStateTableEntrySelector().IncludeCheckpoint(), &s));
ASSERT_EQ(1, std::distance(table_range.begin(), table_range.end()));
ASSERT_OK(s);
auto row_result = *table_range.begin();
ASSERT_OK(row_result);
auto& row = *row_result;
ASSERT_OK(s);
// Verify that op id index has been advanced and is not 0.
ASSERT_GT(row.checkpoint->index, 0);
}
Status VerifyCdcStateMatches(
client::YBClient* client,
const xrepl::StreamId& stream_id,
const TabletId& tablet_id,
uint64_t term,
uint64_t index) {
LOG(INFO) << Format("Verifying tablet: $0, stream: $1, op_id: $2",
tablet_id, stream_id, OpId(term, index).ToString());
CDCStateTable cdc_state_table(client);
auto row = VERIFY_RESULT(cdc_state_table.TryFetchEntry(
{tablet_id, stream_id}, CDCStateTableEntrySelector().IncludeCheckpoint()));
SCHECK(row, IllegalState, "CDC state row not found");
auto& op_id = *row->checkpoint;
SCHECK_EQ(op_id.term, term, IllegalState, "CDC state row term mismatch");
SCHECK_EQ(op_id.index, index, IllegalState, "CDC state row index mismatch");
return Status::OK();
}
void VerifyStreamDeletedFromCdcState(
client::YBClient* client,
const xrepl::StreamId& stream_id,
const TabletId& tablet_id,
int timeout_secs = 10) {
CDCStateTable cdc_state_table(client);
// The deletion of cdc_state rows for the specified stream happen in an asynchronous thread,
// so even if the request has returned, it doesn't mean that the rows have been deleted yet.
ASSERT_OK(WaitFor(
[&]() -> Result<bool> {
auto row = VERIFY_RESULT(cdc_state_table.TryFetchEntry({tablet_id, stream_id}));
return !row;
},
MonoDelta::FromSeconds(timeout_secs) * kTimeMultiplier,
"Stream rows in cdc_state have been deleted."));
}
void CDCServiceTest::GetTablets(std::vector<TabletId>* tablet_ids,
const client::YBTableName& table_name) {
std::vector<std::string> ranges;
ASSERT_OK(client_->GetTablets(
table_name, 0 /* max_tablets */, tablet_ids, &ranges, nullptr /* locations */,
RequireTabletsRunning::kFalse, master::IncludeInactive::kTrue));
ASSERT_EQ(tablet_ids->size(), tablet_count());
}
std::string CDCServiceTest::GetTablet(const client::YBTableName& table_name) {
std::vector<TabletId> tablet_ids;
GetTablets(&tablet_ids, table_name);
return tablet_ids[0];
}
void CDCServiceTest::GetChangesWithResp(
const TabletId& tablet_id, const xrepl::StreamId& stream_id, int64_t term, int64_t index,
GetChangesResponsePB* change_resp, bool* has_error, ::yb::cdc::CDCErrorPB_Code* code) {
GetChangesRequestPB change_req;
change_req.set_tablet_id(tablet_id);
change_req.set_stream_id(stream_id.ToString());
change_req.mutable_from_checkpoint()->mutable_op_id()->set_term(term);
change_req.mutable_from_checkpoint()->mutable_op_id()->set_index(index);
change_req.set_serve_as_proxy(true);
{
RpcController rpc;
rpc.set_timeout(MonoDelta::FromSeconds(10.0) * kTimeMultiplier);
SCOPED_TRACE(change_req.DebugString());
auto s = cdc_proxy_->GetChanges(change_req, change_resp, &rpc);
if (!has_error) {
ASSERT_OK(s);
ASSERT_FALSE(change_resp->has_error());
} else if (!s.ok() || change_resp->has_error()) {
*has_error = true;
if (code && change_resp->error().has_code()) {
*code = change_resp->error().code();
}
return;
}
}
}
void CDCServiceTest::GetChanges(
const TabletId& tablet_id, const xrepl::StreamId& stream_id, int64_t term, int64_t index,
bool* has_error, ::yb::cdc::CDCErrorPB_Code* code) {
GetChangesResponsePB change_resp;
ASSERT_NO_FATALS(
GetChangesWithResp(tablet_id, stream_id, term, index, &change_resp, has_error, code));
}
void CDCServiceTest::GetAllChanges(
const TabletId& tablet_id, const xrepl::StreamId& stream_id,
GetChangesResponsePB* change_resp) {
int64_t term, index;
// Keep running GetChanges until we've gotten all changes.
do {
term = change_resp->checkpoint().op_id().term();
index = change_resp->checkpoint().op_id().index();
change_resp->Clear();
ASSERT_NO_FATALS(GetChangesWithResp(tablet_id, stream_id, term, index, change_resp));
if (change_resp->has_error()) {
return;
}
} while (term != change_resp->checkpoint().op_id().term() &&
index != change_resp->checkpoint().op_id().index());
}
void CDCServiceTest::WriteTestRow(int32_t key,
int32_t int_val,
const string& string_val,
const TabletId& tablet_id,
const std::shared_ptr<tserver::TabletServerServiceProxy>& proxy) {
tserver::WriteRequestPB write_req;
tserver::WriteResponsePB write_resp;
write_req.set_tablet_id(tablet_id);
RpcController rpc;
AddTestRowInsert(key, int_val, string_val, &write_req);
SCOPED_TRACE(write_req.DebugString());
ASSERT_OK(WriteToProxyWithRetries(proxy, write_req, &write_resp, &rpc));
SCOPED_TRACE(write_resp.DebugString());
ASSERT_FALSE(write_resp.has_error());
}
Status CDCServiceTest::WriteToProxyWithRetries(
const std::shared_ptr<tserver::TabletServerServiceProxy>& proxy,
const tserver::WriteRequestPB& req,
tserver::WriteResponsePB* resp,
RpcController* rpc) {
return LoggedWaitFor(
[&req, resp, rpc, proxy]() -> Result<bool> {
auto s = proxy->Write(req, resp, rpc);
if (s.IsTryAgain() ||
(resp->has_error() && StatusFromPB(resp->error().status()).IsTryAgain())) {
rpc->Reset();
return false;
}
RETURN_NOT_OK(s);
return true;
},
MonoDelta::FromSeconds(10) * kTimeMultiplier, "Write test row");
}
Status CDCServiceTest::GetChangesWithRetries(
const GetChangesRequestPB& req,
GetChangesResponsePB* resp,
int timeout_ms,
int max_attempts) {
// Keep track of number of attempts.
int num_attempts = 0;
auto return_status = LoggedWaitFor(
[&]() -> Result<bool> {
// RpcController needs to be rebuilt every time since the deadline is constant.
RpcController rpc;
rpc.set_timeout(MonoDelta::FromMilliseconds(timeout_ms));
// Update return_status to be the status from the latest attempt.
auto s = cdc_proxy_->GetChanges(req, resp, &rpc);
++num_attempts;
// Exit if we exhausted the number of attempts.
if (num_attempts >= max_attempts) {
return s.ok() ? Status::OK() : STATUS_FORMAT(
TimedOut, "Tried calling GetChanges $0 times with no success.", num_attempts);
}
// Try again if we still have attempts left.
if (!s.ok()) {
return false;
}
return true;
},
MonoDelta::FromSeconds(5) * max_attempts * kTimeMultiplier, "Call GetChanges");
return return_status;
}
Status CDCServiceTest::GetChangesInitialSchema(GetChangesRequestPB const& req_in,
CDCCheckpointPB* mutable_checkpoint) {
GetChangesRequestPB change_req(req_in);
GetChangesResponsePB change_resp;
change_req.set_max_records(1);
// Consume the META_OP that has the original Schema.
{
RpcController rpc;
SCOPED_TRACE(change_req.DebugString());
RETURN_NOT_OK(cdc_proxy_->GetChanges(change_req, &change_resp, &rpc));
SCHECK(!change_resp.has_error(), IllegalState,
Format("Response Error: $0", change_resp.error().DebugString()));
SCHECK_EQ(change_resp.records_size(), 1, IllegalState, "Expected only 1 record");
SCHECK_EQ(change_resp.records(0).operation(), CDCRecordPB::CHANGE_METADATA,
IllegalState, "Expected the CHANGE_METADATA related to the initial schema");
mutable_checkpoint->CopyFrom(change_resp.checkpoint());
}
return Status::OK();
}
tserver::MiniTabletServer* CDCServiceTest::GetLeaderForTablet(const std::string& tablet_id) {
return ::yb::GetLeaderForTablet(cluster_.get(), tablet_id);
}
TEST_F(CDCServiceTest, TestCompoundKey) {
// Create a table with a compound primary key.
static const std::string kCDCTestTableCompoundKeyName = "cdc_test_table_compound_key";
static const client::YBTableName kTableNameCompoundKey(
YQL_DATABASE_CQL, kCDCTestKeyspace, kCDCTestTableCompoundKeyName);
client::YBSchemaBuilder builder;
builder.AddColumn("hash_key")->Type(DataType::STRING)->HashPrimaryKey()->NotNull();
builder.AddColumn("range_key")->Type(DataType::STRING)->PrimaryKey()->NotNull();
builder.AddColumn("val")->Type(DataType::INT32);
TableProperties table_properties;
table_properties.SetTransactional(true);
builder.SetTableProperties(table_properties);
TableHandle table;
ASSERT_OK(table.Create(kTableNameCompoundKey, tablet_count(), client_.get(), &builder));
// Create a stream on the table
stream_id_ = ASSERT_RESULT(CreateCDCStream(cdc_proxy_, table.table()->id()));
std::string tablet_id = GetTablet(table.name());
const auto& tserver = cluster_->mini_tablet_server(0)->server();
auto schema =
ASSERT_RESULT(tserver->tablet_manager()->GetTablet(tablet_id))->shared_tablet()->schema();
GetChangesRequestPB change_req;
GetChangesResponsePB change_resp;
change_req.set_tablet_id(tablet_id);
change_req.set_stream_id(stream_id_.ToString());
// Consume the META_OP that has the initial table Schema.
ASSERT_OK(GetChangesInitialSchema(change_req, change_req.mutable_from_checkpoint()));
// Now apply two ops with same hash key but different range key in a batch.
auto session = client_->NewSession(15s);
for (int i = 0; i < 2; i++) {
const auto op = table.NewUpdateOp();
auto* const req = op->mutable_request();
QLAddStringHashValue(req, "hk");
QLAddStringRangeValue(req, Format("rk_$0", i));
table.AddInt32ColumnValue(req, "val", i);
session->Apply(op);
}
ASSERT_OK(session->TEST_Flush());
// Get CDC changes.
{
RpcController rpc;
SCOPED_TRACE(change_req.DebugString());
ASSERT_OK(cdc_proxy_->GetChanges(change_req, &change_resp, &rpc));
ASSERT_FALSE(change_resp.has_error());
ASSERT_EQ(change_resp.records_size(), 2);
}
// Verify the results.
for (int i = 0; i < change_resp.records_size(); i++) {
ASSERT_EQ(change_resp.records(i).operation(), CDCRecordPB::WRITE);
ASSERT_EQ(change_resp.records(i).key_size(), 1);
// Check the key.
auto key1 = ASSERT_RESULT(ExtractKey(
*schema, change_resp.records(i).key(0), "hash_key", /*col_loc=*/0,
/*range_col=*/false));
ASSERT_EQ(key1.string_value(), "hk");
auto key2 = ASSERT_RESULT(
ExtractKey(*schema, change_resp.records(i).key(0), "range_key", /*col_loc=*/0,
/*range_col=*/true));
ASSERT_EQ(key2.string_value(), Format("rk_$0", i));
ASSERT_EQ(change_resp.records(i).changes_size(), 1);
auto value = ASSERT_RESULT(ExtractValue(*schema, change_resp.records(i).changes(0), "val"));
ASSERT_EQ(value.int32_value(), i);
}
}
TEST_F(CDCServiceTest, TestCreateCDCStream) {
stream_id_ = ASSERT_RESULT(CreateCDCStream(cdc_proxy_, table_.table()->id()));
NamespaceId ns_id;
std::vector<TableId> table_ids;
std::unordered_map<std::string, std::string> options;
StreamModeTransactional transactional(false);
ASSERT_OK(client_->GetCDCStream(stream_id_, &ns_id, &table_ids, &options, &transactional));
ASSERT_EQ(table_ids.front(), table_.table()->id());
}
TEST_F(CDCServiceTest, TestCreateCDCStreamWithDefaultRententionTime) {
// Set default WAL retention time to 10 hours.
ANNOTATE_UNPROTECTED_WRITE(FLAGS_cdc_wal_retention_time_secs) = 36000;
stream_id_ = ASSERT_RESULT(CreateCDCStream(cdc_proxy_, table_.table()->id()));
NamespaceId ns_id;
std::vector<TableId> table_ids;
std::unordered_map<std::string, std::string> options;
StreamModeTransactional transactional(false);
ASSERT_OK(client_->GetCDCStream(stream_id_, &ns_id, &table_ids, &options, &transactional));
// Verify that the wal retention time was set at the tablet level.
VerifyWalRetentionTime(cluster_.get(), kCDCTestTableName, FLAGS_cdc_wal_retention_time_secs);
}
TEST_F(CDCServiceTest, TestDeleteCDCStream) {
ANNOTATE_UNPROTECTED_WRITE(FLAGS_cdc_state_checkpoint_update_interval_ms) = 0;
stream_id_ = ASSERT_RESULT(CreateCDCStream(cdc_proxy_, table_.table()->id()));
NamespaceId ns_id;
std::vector<TableId> table_ids;
std::unordered_map<std::string, std::string> options;
StreamModeTransactional transactional(false);
ASSERT_OK(client_->GetCDCStream(stream_id_, &ns_id, &table_ids, &options, &transactional));
ASSERT_EQ(table_ids.front(), table_.table()->id());
std::vector<std::string> tablet_ids;
std::vector<std::string> ranges;
ASSERT_OK(client_->GetTablets(table_.table()->name(), 0 /* max_tablets */, &tablet_ids, &ranges));
for (const auto& tablet_id : tablet_ids) {
ASSERT_OK(VerifyCdcStateMatches(client_.get(), stream_id_, tablet_id, 0, 0));
}
{
const auto& tserver = cluster_->mini_tablet_server(0)->server();
std::string tablet_id = GetTablet(table_.name());
ASSERT_NO_FATALS(WriteTestRow(0, 10, "key0", tablet_id, tserver->proxy()));
}
ASSERT_OK(DeleteXClusterStream(stream_id_));
// Check that the stream still no longer exists.
ns_id.clear();
table_ids.clear();
options.clear();
Status s = client_->GetCDCStream(stream_id_, &ns_id, &table_ids, &options, &transactional);
ASSERT_TRUE(s.IsNotFound());
for (const auto& tablet_id : tablet_ids) {
VerifyStreamDeletedFromCdcState(client_.get(), stream_id_, tablet_id);
}
// Once the CatalogManager has cleaned up cdc_state, make sure a subsequent call to GetChanges
// doesn't re-populate cdc_state with cleaned up entries. UpdateCheckpoint will be called since
// this is the first time we're calling GetChanges.
bool get_changes_error = false;
for (const auto& tablet_id : tablet_ids) {
GetChanges(tablet_id, stream_id_, 0, 0, &get_changes_error);
ASSERT_TRUE(get_changes_error);
}
for (const auto& tablet_id : tablet_ids) {
VerifyStreamDeletedFromCdcState(client_.get(), stream_id_, tablet_id);
}
}
TEST_F(CDCServiceTest, TestSafeTime) {
docdb::DisableYcqlPackedRow();
stream_id_ = ASSERT_RESULT(CreateCDCStream(cdc_proxy_, table_.table()->id()));
ANNOTATE_UNPROTECTED_WRITE(FLAGS_enable_collect_cdc_metrics) = true;
std::string tablet_id = GetTablet();
auto leader_tserver = GetLeaderForTablet(tablet_id)->server();
auto tablet_peer = ASSERT_RESULT(leader_tserver->tablet_manager()->GetServingTablet(tablet_id));
GetChangesRequestPB change_req;
GetChangesResponsePB change_resp;
change_req.set_tablet_id(tablet_id);
change_req.set_stream_id(stream_id_.ToString());
// Consume the META_OP that has the original Schema.
ASSERT_OK(GetChangesInitialSchema(change_req, change_req.mutable_from_checkpoint()));
auto ht_0 = ASSERT_RESULT(tablet_peer->LeaderSafeTime()).ToUint64();
ASSERT_NO_FATALS(WriteTestRow(0, 10, "key0", tablet_id, leader_tserver->proxy()));
ASSERT_NO_FATALS(WriteTestRow(1, 11, "key0", tablet_id, leader_tserver->proxy()));
auto ht_1 = ASSERT_RESULT(tablet_peer->LeaderSafeTime()).ToUint64();
// Get CDC changes.
ANNOTATE_UNPROTECTED_WRITE(FLAGS_TEST_xcluster_simulate_have_more_records) = true;
{
RpcController rpc;
SCOPED_TRACE(change_req.DebugString());
ASSERT_OK(cdc_proxy_->GetChanges(change_req, &change_resp, &rpc));
ASSERT_FALSE(change_resp.has_error());
ASSERT_TRUE(change_resp.has_safe_hybrid_time());
uint64_t safe_hybrid_time = change_resp.safe_hybrid_time();
ASSERT_TRUE(ht_0 < safe_hybrid_time && safe_hybrid_time < ht_1);
}
ANNOTATE_UNPROTECTED_WRITE(FLAGS_TEST_xcluster_simulate_have_more_records) = false;
{
auto pre_get_changes_time = ASSERT_RESULT(tablet_peer->LeaderSafeTime()).ToUint64();;
RpcController rpc;
SCOPED_TRACE(change_req.DebugString());
ASSERT_OK(cdc_proxy_->GetChanges(change_req, &change_resp, &rpc));
ASSERT_FALSE(change_resp.has_error());
ASSERT_TRUE(change_resp.has_safe_hybrid_time());
uint64_t safe_hybrid_time = change_resp.safe_hybrid_time();
auto post_get_changes_time = ASSERT_RESULT(tablet_peer->LeaderSafeTime()).ToUint64();
ASSERT_TRUE(pre_get_changes_time <= safe_hybrid_time &&
safe_hybrid_time <= post_get_changes_time);
}
ASSERT_OK(DeleteXClusterStream(stream_id_));
}
TEST_F(CDCServiceTest, TestMetricsOnDeletedReplication) {
stream_id_ = ASSERT_RESULT(CreateCDCStream(cdc_proxy_, table_.table()->id()));
ANNOTATE_UNPROTECTED_WRITE(FLAGS_enable_collect_cdc_metrics) = true;
std::string tablet_id = GetTablet();
const auto& tserver = cluster_->mini_tablet_server(0)->server();
// Use proxy for to most accurately simulate normal requests.
const auto& proxy = tserver->proxy();
GetChangesRequestPB change_req;
GetChangesResponsePB change_resp;
change_req.set_tablet_id(tablet_id);
change_req.set_stream_id(stream_id_.ToString());
change_req.mutable_from_checkpoint()->mutable_op_id()->set_index(0);
change_req.mutable_from_checkpoint()->mutable_op_id()->set_term(0);
{
RpcController rpc;
SCOPED_TRACE(change_req.DebugString());
ASSERT_OK(cdc_proxy_->GetChanges(change_req, &change_resp, &rpc));
}
// Insert test rows, one at a time so they have different hybrid times.
tserver::WriteRequestPB write_req;
tserver::WriteResponsePB write_resp;
write_req.set_tablet_id(tablet_id);
{
RpcController rpc;
AddTestRowInsert(1, 11, "key1", &write_req);
AddTestRowInsert(2, 22, "key2", &write_req);
SCOPED_TRACE(write_req.DebugString());
ASSERT_OK(WriteToProxyWithRetries(proxy, write_req, &write_resp, &rpc));
SCOPED_TRACE(write_resp.DebugString());
ASSERT_FALSE(write_resp.has_error());
}
auto cdc_service = CDCService(tserver);
auto metrics = ASSERT_RESULT(GetXClusterTabletMetrics(*cdc_service, tablet_id, stream_id_));
// Assert that leader lag > 0.
ASSERT_OK(WaitFor(
[&]() -> Result<bool> {
return metrics->async_replication_sent_lag_micros->value() > 0 &&
metrics->async_replication_committed_lag_micros->value() > 0;
},
MonoDelta::FromSeconds(10) * kTimeMultiplier, "Wait for Lag > 0"));
// Now, delete the replication stream and assert that lag is 0.
ASSERT_OK(DeleteXClusterStream(stream_id_));
ASSERT_OK(WaitFor(
[&]() -> Result<bool> {
return metrics->async_replication_sent_lag_micros->value() == 0 &&
metrics->async_replication_committed_lag_micros->value() == 0;
},
MonoDelta::FromSeconds(10) * kTimeMultiplier, "Wait for Lag = 0"));
// Now check that UpdateLagMetrics deletes the metric.
cdc_service->UpdateMetrics();
auto metrics_result = GetXClusterTabletMetrics(
*cdc_service, tablet_id, stream_id_, CreateMetricsEntityIfNotFound::kFalse);
ASSERT_NOK(metrics_result) << metrics_result;
}
TEST_F(CDCServiceTest, TestWALPrematureGCErrorCode) {
stream_id_ = ASSERT_RESULT(CreateCDCStream(cdc_proxy_, table_.table()->id()));
std::string tablet_id = GetTablet();
auto tablet_peer = ASSERT_RESULT(
cluster_->mini_tablet_server(0)->server()->tablet_manager()->GetTablet(tablet_id));
ASSERT_OK(tablet_peer->log()->AllocateSegmentAndRollOver());
ANNOTATE_UNPROTECTED_WRITE(FLAGS_TEST_disable_wal_retention_time) = true;
ANNOTATE_UNPROTECTED_WRITE(FLAGS_enable_log_retention_by_op_idx) = false;
ANNOTATE_UNPROTECTED_WRITE(FLAGS_log_min_segments_to_retain) = 0;
int num_gced;
ASSERT_OK(tablet_peer->log()->GC(std::numeric_limits<int64_t>::max(), &num_gced));
ASSERT_EQ(1, num_gced);
bool has_error;
::yb::cdc::CDCErrorPB_Code code;
GetChanges(tablet_id, stream_id_, /* term */ 0, /* index */ 1, &has_error, &code);
ASSERT_TRUE(has_error);
ASSERT_EQ(cdc::CDCErrorPB::CHECKPOINT_TOO_OLD, code);
}
TEST_F(CDCServiceTest, TestGetChanges) {
docdb::DisableYcqlPackedRow();
stream_id_ = ASSERT_RESULT(CreateCDCStream(cdc_proxy_, table_.table()->id()));
ANNOTATE_UNPROTECTED_WRITE(FLAGS_enable_collect_cdc_metrics) = true;
std::string tablet_id = GetTablet();
const auto& tserver = cluster_->mini_tablet_server(0)->server();
auto schema =
ASSERT_RESULT(tserver->tablet_manager()->GetTablet(tablet_id))->shared_tablet()->schema();
// Use proxy for to most accurately simulate normal requests.
const auto& proxy = tserver->proxy();
// Insert test rows, one at a time so they have different hybrid times.
tserver::WriteRequestPB write_req;
tserver::WriteResponsePB write_resp;
write_req.set_tablet_id(tablet_id);
{
RpcController rpc;
AddTestRowInsert(1, 11, "key1", &write_req);
AddTestRowInsert(2, 22, "key2", &write_req);
SCOPED_TRACE(write_req.DebugString());
ASSERT_OK(WriteToProxyWithRetries(proxy, write_req, &write_resp, &rpc));
SCOPED_TRACE(write_resp.DebugString());
ASSERT_FALSE(write_resp.has_error());
}
// Get CDC changes.
GetChangesRequestPB change_req;
GetChangesResponsePB change_resp;
change_req.set_tablet_id(tablet_id);
change_req.set_stream_id(stream_id_.ToString());
// Consume the META_OP that has the initial table Schema.
ASSERT_OK(GetChangesInitialSchema(change_req, change_req.mutable_from_checkpoint()));
{
RpcController rpc;
SCOPED_TRACE(change_req.DebugString());
ASSERT_OK(cdc_proxy_->GetChanges(change_req, &change_resp, &rpc));
SCOPED_TRACE(change_resp.DebugString());
ASSERT_FALSE(change_resp.has_error());
ASSERT_EQ(change_resp.records_size(), 2);
std::pair<int, std::string> expected_results[2] =
{std::make_pair(11, "key1"), std::make_pair(22, "key2")};
for (int i = 0; i < change_resp.records_size(); i++) {
ASSERT_EQ(change_resp.records(i).operation(), CDCRecordPB::WRITE);
// Check the key.
ASSERT_NO_FATALS(AssertIntKey(*schema, change_resp.records(i).key(), i + 1));
// Check the change records.
ASSERT_NO_FATALS(AssertChangeRecords(
*schema, change_resp.records(i).changes(), expected_results[i].first,
expected_results[i].second));
}
// Verify the CDC Service-level metrics match what we just did.
auto cdc_service = CDCService(tserver);
auto metrics = ASSERT_RESULT(GetXClusterTabletMetrics(*cdc_service, tablet_id, stream_id_));
ASSERT_EQ(metrics->last_read_opid_index->value(), metrics->last_readable_opid_index->value());
ASSERT_EQ(metrics->last_read_opid_index->value(), change_resp.records_size() + 1 /* checkpt */);
ASSERT_EQ(metrics->rpc_payload_bytes_responded->TotalCount(), 2);
}
// Insert another row.
{
write_req.Clear();
write_req.set_tablet_id(tablet_id);
AddTestRowInsert(3, 33, "key3", &write_req);
RpcController rpc;
SCOPED_TRACE(write_req.DebugString());
ASSERT_OK(WriteToProxyWithRetries(proxy, write_req, &write_resp, &rpc));
SCOPED_TRACE(write_resp.DebugString());
ASSERT_FALSE(write_resp.has_error());
}
// Get next set of changes.
// Copy checkpoint received from previous GetChanges CDC request.
change_req.mutable_from_checkpoint()->CopyFrom(change_resp.checkpoint());
change_resp.Clear();
{
RpcController rpc;
SCOPED_TRACE(change_req.DebugString());
ASSERT_OK(cdc_proxy_->GetChanges(change_req, &change_resp, &rpc));
SCOPED_TRACE(change_resp.DebugString());
ASSERT_FALSE(change_resp.has_error());
ASSERT_EQ(change_resp.records_size(), 1);
ASSERT_EQ(change_resp.records(0).operation(), CDCRecordPB_OperationType_WRITE);
// Check the key.
ASSERT_NO_FATALS(AssertIntKey(*schema, change_resp.records(0).key(), 3));
// Check the change records.
ASSERT_NO_FATALS(AssertChangeRecords(*schema, change_resp.records(0).changes(), 33, "key3"));
}
// Delete a row.
{
write_req.Clear();
write_req.set_tablet_id(tablet_id);
AddTestRowDelete(1, &write_req);
RpcController rpc;
SCOPED_TRACE(write_req.DebugString());
ASSERT_OK(WriteToProxyWithRetries(proxy, write_req, &write_resp, &rpc));
SCOPED_TRACE(write_resp.DebugString());
ASSERT_FALSE(write_resp.has_error());
}
// Get next set of changes.
// Copy checkpoint received from previous GetChanges CDC request.
change_req.mutable_from_checkpoint()->CopyFrom(change_resp.checkpoint());
change_resp.Clear();
{
RpcController rpc;
SCOPED_TRACE(change_req.DebugString());
ASSERT_OK(cdc_proxy_->GetChanges(change_req, &change_resp, &rpc));
SCOPED_TRACE(change_resp.DebugString());
ASSERT_FALSE(change_resp.has_error());
ASSERT_EQ(change_resp.records_size(), 1);
ASSERT_EQ(change_resp.records(0).operation(), CDCRecordPB_OperationType_DELETE);
// Check the key deleted.
ASSERT_NO_FATALS(AssertIntKey(*schema, change_resp.records(0).key(), 1));
}
// Cleanup stream before shutdown.
ASSERT_OK(DeleteXClusterStream(stream_id_));
VerifyStreamDeletedFromCdcState(client_.get(), stream_id_, tablet_id);
}
TEST_F(CDCServiceTest, TestGetChangesWithDeadline) {
ANNOTATE_UNPROTECTED_WRITE(FLAGS_cdc_populate_end_markers_transactions) = false;
docdb::DisableYcqlPackedRow();
stream_id_ = ASSERT_RESULT(CreateCDCStream(cdc_proxy_, table_.table()->id()));
ANNOTATE_UNPROTECTED_WRITE(FLAGS_log_segment_size_bytes) = 100;
ANNOTATE_UNPROTECTED_WRITE(FLAGS_get_changes_honor_deadline) = true;
ANNOTATE_UNPROTECTED_WRITE(FLAGS_cdc_read_safe_deadline_ratio) = 0.30;
// Skip the META_OP that has the initial table Schema. This method avoids LogCache.
ANNOTATE_UNPROTECTED_WRITE(FLAGS_TEST_xcluster_skip_meta_ops) = true;
std::string tablet_id = GetTablet();
GetChangesRequestPB change_req;
GetChangesResponsePB change_resp;
change_req.set_tablet_id(tablet_id);
change_req.set_stream_id(stream_id_.ToString());
const auto& tserver = cluster_->mini_tablet_server(0)->server();
// Use proxy for to most accurately simulate normal requests.
const auto& proxy = tserver->proxy();
// Insert <num_records> test rows.
const int num_records = 500;
for (int i = 0; i < num_records; i++) {
WriteTestRow(i, i, Format("key$0", i), tablet_id, proxy);
}
change_req.set_max_records(num_records);
SCOPED_TRACE(change_req.DebugString());
{
// Get CDC changes. Note that the timeout value and read delay
// should ensure that some, but not all records are read.
ANNOTATE_UNPROTECTED_WRITE(FLAGS_TEST_get_changes_read_loop_delay_ms) = 10 * kTimeMultiplier;
ANNOTATE_UNPROTECTED_WRITE(FLAGS_cdc_read_rpc_timeout_ms) = 50 * kTimeMultiplier;
ASSERT_OK(GetChangesWithRetries(change_req, &change_resp,
FLAGS_cdc_read_rpc_timeout_ms));
SCOPED_TRACE(change_resp.DebugString());
ASSERT_FALSE(change_resp.has_error());
// Ensure that partial results are returned
ASSERT_GT(change_resp.records_size(), 0);
ASSERT_LT(change_resp.records_size(), num_records);
}
{
// Try again, but use a timeout value large enough such that
// all records should be read before timeout.
ANNOTATE_UNPROTECTED_WRITE(FLAGS_TEST_get_changes_read_loop_delay_ms) = 0;
ANNOTATE_UNPROTECTED_WRITE(FLAGS_cdc_read_rpc_timeout_ms) = 30 * 1000 * kTimeMultiplier;
ASSERT_OK(GetChangesWithRetries(change_req, &change_resp,
FLAGS_cdc_read_rpc_timeout_ms));
SCOPED_TRACE(change_resp.DebugString());
ASSERT_FALSE(change_resp.has_error());
// This time, we expect all records to be read.
ASSERT_EQ(change_resp.records_size(), num_records);
}
// Cleanup stream before shutdown.
ASSERT_OK(DeleteXClusterStream(stream_id_));
VerifyStreamDeletedFromCdcState(client_.get(), stream_id_, tablet_id);
}
TEST_F(CDCServiceTest, TestGetChangesInvalidStream) {
std::string tablet_id = GetTablet();
// Get CDC changes for non-existent stream.
GetChangesRequestPB change_req;
GetChangesResponsePB change_resp;
change_req.set_tablet_id(tablet_id);
change_req.set_stream_id("InvalidStreamId");
change_req.mutable_from_checkpoint()->mutable_op_id()->set_index(0);
change_req.mutable_from_checkpoint()->mutable_op_id()->set_term(0);
RpcController rpc;
ASSERT_OK(cdc_proxy_->GetChanges(change_req, &change_resp, &rpc));
ASSERT_TRUE(change_resp.has_error());
}
TEST_F(CDCServiceTest, TestGetCheckpoint) {
stream_id_ = ASSERT_RESULT(CreateCDCStream(cdc_proxy_, table_.table()->id()));
std::string tablet_id = GetTablet();