-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathcdc_service.cc
5403 lines (4647 loc) · 218 KB
/
cdc_service.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.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
#include "yb/cdc/cdc_service.h"
#include <algorithm>
#include <chrono>
#include <memory>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index_container.hpp>
#include "yb/cdc/cdc_error.h"
#include "yb/cdc/cdc_producer.h"
#include "yb/cdc/cdc_service.pb.h"
#include "yb/cdc/cdc_util.h"
#include "yb/cdc/xcluster_rpc.h"
#include "yb/cdc/cdc_service.proxy.h"
#include "yb/cdc/cdc_service_context.h"
#include "yb/cdc/cdc_state_table.h"
#include "yb/cdc/cdc_types.h"
#include "yb/cdc/cdcsdk_virtual_wal.h"
#include "yb/cdc/xcluster_producer_bootstrap.h"
#include "yb/cdc/xrepl_stream_metadata.h"
#include "yb/cdc/xrepl_stream_stats.h"
#include "yb/client/client.h"
#include "yb/client/meta_cache.h"
#include "yb/client/schema.h"
#include "yb/client/table.h"
#include "yb/client/table_handle.h"
#include "yb/client/yb_table_name.h"
#include "yb/common/colocated_util.h"
#include "yb/common/pg_system_attr.h"
#include "yb/common/schema.h"
#include "yb/common/wire_protocol.h"
#include "yb/common/xcluster_util.h"
#include "yb/consensus/log.h"
#include "yb/consensus/log_reader.h"
#include "yb/consensus/raft_consensus.h"
#include "yb/consensus/replicate_msgs_holder.h"
#include "yb/gutil/map-util.h"
#include "yb/gutil/strings/join.h"
#include "yb/master/master_client.pb.h"
#include "yb/master/master_ddl.pb.h"
#include "yb/rocksdb/rate_limiter.h"
#include "yb/rpc/rpc_context.h"
#include "yb/rpc/rpc_controller.h"
#include "yb/server/async_client_initializer.h"
#include "yb/tablet/tablet_metadata.h"
#include "yb/tablet/tablet_peer.h"
#include "yb/tablet/transaction_participant.h"
#include "yb/tserver/service_util.h"
#include "yb/util/flags.h"
#include "yb/util/format.h"
#include "yb/util/logging.h"
#include "yb/util/metrics.h"
#include "yb/util/monotime.h"
#include "yb/util/scope_exit.h"
#include "yb/util/service_util.h"
#include "yb/util/shared_lock.h"
#include "yb/util/status.h"
#include "yb/util/status_format.h"
#include "yb/util/status_log.h"
#include "yb/util/stopwatch.h"
#include "yb/util/sync_point.h"
#include "yb/util/thread.h"
#include "yb/util/trace.h"
using std::max;
using std::min;
using std::pair;
using std::string;
using std::vector;
constexpr uint32_t kUpdateIntervalMs = 15 * 1000;
DECLARE_int32(cdc_read_rpc_timeout_ms);
DEFINE_NON_RUNTIME_int32(cdc_write_rpc_timeout_ms, 30 * 1000,
"Timeout used for CDC write rpc calls. Writes normally occur intra-cluster.");
TAG_FLAG(cdc_write_rpc_timeout_ms, advanced);
DEPRECATE_FLAG(int32, cdc_ybclient_reactor_threads, "09_2023");
DEFINE_RUNTIME_int32(cdc_state_checkpoint_update_interval_ms, kUpdateIntervalMs,
"Rate at which CDC state's checkpoint is updated.");
DEFINE_RUNTIME_int32(update_min_cdc_indices_interval_secs, 60,
"How often to read cdc_state table to get the minimum applied index for each tablet "
"across all streams. This information is used to correctly keep log files that "
"contain unapplied entries. This is also the rate at which a tablet's minimum "
"replicated index across all streams is sent to the other peers in the configuration. "
"If flag enable_log_retention_by_op_idx is disabled, this flag has no effect.");
DEFINE_RUNTIME_int32(update_metrics_interval_ms, kUpdateIntervalMs,
"How often to update xDC cluster metrics.");
// enable_cdc_client_tablet_caching is disabled because cdc code does notify the meta cache when
// requests to the peers fail. Also, meta cache does not handle addition of peers, which can cause
// issues with cdc checkpoint updates.
DEFINE_RUNTIME_bool(enable_cdc_client_tablet_caching, false,
"Enable caching the tablets found by client.");
DEFINE_RUNTIME_bool(enable_collect_cdc_metrics, true,
"Enable collecting cdc and xcluster metrics.");
DEFINE_RUNTIME_double(cdc_read_safe_deadline_ratio, .10,
"When the heartbeat deadline has this percentage of time remaining, "
"the master should halt tablet report processing so it can respond in time.");
DEFINE_NON_RUNTIME_double(cdc_get_changes_free_rpc_ratio, .10,
"When the TServer only has this percentage of RPCs remaining because the rest are "
"GetChanges, reject additional requests to throttle/backoff and prevent deadlocks.");
DEFINE_RUNTIME_bool(enable_update_local_peer_min_index, true,
"Enable each local peer to update its own log checkpoint instead of the leader "
"updating all peers.");
DEPRECATE_FLAG(bool, parallelize_bootstrap_producer, "08_2023");
DEFINE_test_flag(uint64, cdc_log_init_failure_timeout_seconds, 0,
"Timeout in seconds for CDCServiceImpl::SetCDCCheckpoint to return log init failure");
DEFINE_RUNTIME_int32(wait_replication_drain_tserver_max_retry, 3,
"Maximum number of retry that a tserver will poll its tablets until the tablets"
"are all caught-up in the replication, before responding to the caller.");
DEFINE_RUNTIME_int32(wait_replication_drain_tserver_retry_interval_ms, 100,
"Time in microseconds that a tserver will sleep between each iteration of polling "
"its tablets until the tablets are all caught-up in the replication.");
DEFINE_test_flag(bool, block_get_changes, false,
"For testing only. When set to true, GetChanges will not send any new changes "
"to the consumer.");
DEFINE_test_flag(bool, force_get_checkpoint_from_cdc_state, false,
"Always bypass the cache and fetch the checkpoint from the cdc state table");
DEFINE_RUNTIME_int32(xcluster_get_changes_max_send_rate_mbps, 100,
"Server-wide max send rate in megabytes per second for GetChanges response "
"traffic. Throttles xcluster but not cdc traffic.");
DEFINE_RUNTIME_bool(enable_xcluster_stat_collection, true,
"When enabled, stats are collected from xcluster streams for reporting purposes.");
DEFINE_RUNTIME_uint32(cdcsdk_tablet_not_of_interest_timeout_secs, 4 * 60 * 60,
"Timeout after which it can be inferred that tablet is not of interest "
"for the stream");
DEFINE_test_flag(bool, cdc_force_destroy_virtual_wal_failure, false,
"For testing only. When set to true, DestroyVirtualWal RPC will return RPC "
"failure response.");
DEFINE_RUNTIME_PREVIEW_bool(enable_cdcsdk_setting_get_changes_response_byte_limit, false,
"When enabled, we'll consider the proto field getchanges_resp_max_size_bytes in "
"GetChangesRequestPB to limit the size of GetChanges response.");
DEFINE_test_flag(bool, cdcsdk_skip_stream_active_check, false,
"When enabled, GetChanges will skip checking if stream is active as well as skip "
"updating the active time.");
DEFINE_RUNTIME_uint32(xcluster_checkpoint_max_staleness_secs, 300,
"The maximum interval in seconds that the xcluster checkpoint map can go without being "
"refreshed. If the map is not refreshed within this interval, it is considered stale, "
"and all WAL segments will be retained until the next refresh. "
"Setting to 0 will disable Opid-based and time-based WAL segment retention for XCluster.");
DEFINE_RUNTIME_int32(
cdcsdk_max_expired_tables_to_clean_per_run, 1,
"This flag determines the maximum number of tables to be cleaned up per run of "
"UpdatePeersAndMetrics. Since a lot of tables can become not of interest at the same time, "
"this flag is used to prevent storming of cleanup requests to master. When the flag value is "
"1, the number of cleanup requests sent will be min(num_tables_to_cleanup, num_of_nodes)");
DEFINE_RUNTIME_AUTO_bool(
cdcsdk_enable_cleanup_of_expired_table_entries, kLocalPersisted, false, true,
"When enabled, Update Peers and Metrics will look for entries in the state table that have "
"either become not of interest or have expired for a stream. The cleanup logic will then "
"update these entries in cdc_state table and also move the corresponding table's entry to "
"unqualified tables list in stream metadata.");
DEFINE_RUNTIME_bool(cdc_enable_implicit_checkpointing, false,
"When enabled, users will be able to create a CDC stream having IMPLICIT checkpointing.");
DEFINE_RUNTIME_uint32(cdc_max_virtual_wal_per_tserver, 5,
"Maximum VirtualWAL instances that can be present on a tserver at any time.");
DECLARE_int32(log_min_seconds_to_retain);
static bool ValidateMaxRefreshInterval(const char* flag_name, uint32 value) {
// This validation depends on the value of other flag(s):
// log_min_seconds_to_retain, update_min_cdc_indices_interval_secs.
DELAY_FLAG_VALIDATION_ON_STARTUP(flag_name);
uint32 min_allowed = FLAGS_log_min_seconds_to_retain + FLAGS_update_min_cdc_indices_interval_secs;
if (value == 0 || value < min_allowed) {
return true;
}
LOG_FLAG_VALIDATION_ERROR(flag_name, value)
<< "Must be less than the sum of log_min_seconds_to_retain and "
<< "update_min_cdc_indices_interval_secs. Minimum value allowed: " << min_allowed;
return false;
}
DEFINE_validator(xcluster_checkpoint_max_staleness_secs, &ValidateMaxRefreshInterval);
DECLARE_bool(enable_log_retention_by_op_idx);
DECLARE_int32(cdc_checkpoint_opid_interval_ms);
DECLARE_int32(rpc_workers_limit);
DECLARE_uint64(cdc_intent_retention_ms);
DECLARE_bool(ysql_yb_enable_replication_commands);
DECLARE_bool(enable_xcluster_auto_flag_validation);
DECLARE_bool(ysql_yb_enable_replication_slot_consumption);
DECLARE_bool(ysql_yb_enable_replica_identity);
DEFINE_RUNTIME_bool(enable_cdcsdk_lag_collection, false,
"When enabled, vlog containing the lag for the getchanges call as well as last commit record "
"in response will be printed.");
DECLARE_bool(cdcsdk_enable_dynamic_table_addition_with_table_cleanup);
DECLARE_bool(ysql_yb_enable_consistent_replication_from_hash_range);
METRIC_DEFINE_entity(xcluster);
METRIC_DEFINE_entity(cdcsdk);
#define VERIFY_STRING_TO_STREAM_ID(stream_id_str) \
VERIFY_RESULT_OR_SET_CODE( \
xrepl::StreamId::FromString(stream_id_str), CDCError(CDCErrorPB::INVALID_REQUEST))
#define RPC_VERIFY_STRING_TO_STREAM_ID(stream_id_str) \
RPC_VERIFY_RESULT( \
xrepl::StreamId::FromString(stream_id_str), resp->mutable_error(), \
CDCErrorPB::INVALID_REQUEST, context)
using namespace std::literals;
using namespace std::placeholders;
namespace yb {
namespace cdc {
using client::internal::RemoteTabletServer;
using rpc::RpcContext;
constexpr int kMaxDurationForTabletLookup = 50;
MonoTime test_expire_time_cdc_log_init_failure = MonoTime::kUninitialized;
namespace {
// These are guarded by lock_.
// Map of checkpoints that have been sent to CDC consumer and stored in cdc_state.
struct TabletCheckpointInfo {
public:
TabletStreamInfo producer_tablet_info;
mutable TabletCheckpoint cdc_state_checkpoint;
mutable TabletCheckpoint sent_checkpoint;
mutable MemTrackerPtr mem_tracker;
const TabletId& tablet_id() const { return producer_tablet_info.tablet_id; }
const xrepl::StreamId& stream_id() const { return producer_tablet_info.stream_id; }
};
struct CDCStateMetadataInfo {
TabletStreamInfo producer_tablet_info;
mutable uint64_t commit_timestamp;
mutable OpId last_streamed_op_id;
mutable SchemaDetailsMap schema_details_map;
std::shared_ptr<MemTracker> mem_tracker;
const TableId& tablet_id() const { return producer_tablet_info.tablet_id; }
const xrepl::StreamId& stream_id() const { return producer_tablet_info.stream_id; }
};
class TabletTag;
class StreamTag;
using TabletCheckpoints = boost::multi_index_container<
TabletCheckpointInfo,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<boost::multi_index::member<
TabletCheckpointInfo, TabletStreamInfo, &TabletCheckpointInfo::producer_tablet_info>>,
boost::multi_index::hashed_non_unique<
boost::multi_index::tag<TabletTag>,
boost::multi_index::const_mem_fun<
TabletCheckpointInfo, const TabletId&, &TabletCheckpointInfo::tablet_id>>,
boost::multi_index::hashed_non_unique<
boost::multi_index::tag<StreamTag>,
boost::multi_index::const_mem_fun<
TabletCheckpointInfo, const xrepl::StreamId&, &TabletCheckpointInfo::stream_id>>>>;
using CDCStateMetadata = boost::multi_index_container<
CDCStateMetadataInfo,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<boost::multi_index::member<
CDCStateMetadataInfo, TabletStreamInfo, &CDCStateMetadataInfo::producer_tablet_info>>,
boost::multi_index::hashed_non_unique<
boost::multi_index::tag<TabletTag>,
boost::multi_index::const_mem_fun<
CDCStateMetadataInfo, const TabletId&, &CDCStateMetadataInfo::tablet_id>>,
boost::multi_index::hashed_non_unique<
boost::multi_index::tag<StreamTag>,
boost::multi_index::const_mem_fun<
CDCStateMetadataInfo, const xrepl::StreamId&, &CDCStateMetadataInfo::stream_id>>>>;
bool RecordHasValidOp(const CDCSDKProtoRecordPB& record) {
return record.row_message().op() == RowMessage_Op_INSERT ||
record.row_message().op() == RowMessage_Op_UPDATE ||
record.row_message().op() == RowMessage_Op_DELETE ||
record.row_message().op() == RowMessage_Op_SAFEPOINT ||
record.row_message().op() == RowMessage_Op_READ;
}
// Find the right-most proto record from the cdc_sdk_proto_records
// having valid commit_time, which will be used to calculate
// CDCSDK lag metrics cdcsdk_sent_lag_micros.
std::optional<MicrosTime> GetCDCSDKLastSendRecordTime(const GetChangesResponsePB& resp) {
int cur_idx = resp.cdc_sdk_proto_records_size() - 1;
while (cur_idx >= 0) {
auto& each_record = resp.cdc_sdk_proto_records(cur_idx);
if (RecordHasValidOp(each_record)) {
return HybridTime(each_record.row_message().commit_time()).GetPhysicalValueMicros();
}
cur_idx -= 1;
}
return std::nullopt;
}
const std::string GetXreplMetricsKey(const xrepl::StreamId& stream_id) {
return Format("XreplMetrics::$0", stream_id);
}
template <typename T>
Result<std::shared_ptr<T>> GetOrCreateXreplTabletMetrics(
const tablet::TabletPeer& tablet_peer, const xrepl::StreamId& stream_id,
CDCRequestSource source_type, MetricRegistry* metric_registry,
CreateMetricsEntityIfNotFound create,
const std::optional<std::string>& slot_name = std::nullopt) {
const auto tablet_id = tablet_peer.tablet_id();
auto tablet = tablet_peer.shared_tablet();
SCHECK(tablet, IllegalState, Format("Tablet id $0 not found", tablet_id));
const auto key = GetXreplMetricsKey(stream_id);
auto metrics_raw = tablet->GetAdditionalMetadata(key);
if (!metrics_raw && create) {
MetricEntity::AttributeMap attrs;
{
auto raft_group_metadata = tablet->metadata();
attrs["table_id"] = raft_group_metadata->table_id();
attrs["namespace_name"] = raft_group_metadata->namespace_name();
attrs["table_name"] = raft_group_metadata->table_name();
attrs["table_type"] = TableType_Name(raft_group_metadata->table_type());
attrs["stream_id"] = stream_id.ToString();
if (slot_name.has_value()) {
attrs["slot_name"] = slot_name.value();
}
}
const std::string metric_id = Format("$0:$1", stream_id, tablet_id);
scoped_refptr<MetricEntity> entity;
if (source_type == XCLUSTER) {
entity = METRIC_ENTITY_xcluster.Instantiate(
metric_registry, metric_id, attrs);
} else {
entity = METRIC_ENTITY_cdcsdk.Instantiate(
metric_registry, metric_id, attrs);
}
metrics_raw = tablet->AddAdditionalMetadata(key, std::make_shared<T>(entity));
}
SCHECK(
metrics_raw, NotFound, Format("Xrepl Tablet Metric not found for Tablet id $0", tablet_id));
return std::static_pointer_cast<T>(metrics_raw);
}
} // namespace
class CDCServiceImpl::Impl {
public:
explicit Impl(CDCServiceContext* context, rw_spinlock* mutex) : mutex_(*mutex) {}
void UpdateCDCStateMetadata(
const TabletStreamInfo& producer_tablet, const uint64_t& timestamp,
const SchemaDetailsMap& schema_details, const OpId& op_id) {
std::lock_guard l(mutex_);
auto it = cdc_state_metadata_.find(producer_tablet);
if (it == cdc_state_metadata_.end()) {
LOG(DFATAL) << "Failed to update the cdc state metadata for tablet id: "
<< producer_tablet.tablet_id;
return;
}
it->commit_timestamp = timestamp;
it->last_streamed_op_id = op_id;
it->schema_details_map = std::move(schema_details);
}
SchemaDetailsMap GetOrAddSchema(
const TabletStreamInfo& producer_tablet, const bool need_schema_info) {
std::lock_guard l(mutex_);
auto it = cdc_state_metadata_.find(producer_tablet);
if (it != cdc_state_metadata_.end()) {
if (need_schema_info) {
it->schema_details_map.clear();
}
return it->schema_details_map;
}
CDCStateMetadataInfo info = CDCStateMetadataInfo{
.producer_tablet_info = producer_tablet,
.commit_timestamp = {},
.last_streamed_op_id = OpId::Invalid(),
.schema_details_map = {},
.mem_tracker = nullptr};
cdc_state_metadata_.emplace(info);
it = cdc_state_metadata_.find(producer_tablet);
return it->schema_details_map;
}
boost::optional<OpId> GetLastStreamedOpId(const TabletStreamInfo& producer_tablet) {
SharedLock<rw_spinlock> lock(mutex_);
auto it = cdc_state_metadata_.find(producer_tablet);
if (it != cdc_state_metadata_.end()) {
return it->last_streamed_op_id;
}
return boost::none;
}
void AddTabletCheckpoint(
OpId op_id, const xrepl::StreamId& stream_id, const TabletId& tablet_id) {
TabletStreamInfo producer_tablet{.stream_id = stream_id, .tablet_id = tablet_id};
CoarseTimePoint time = CoarseMonoClock::Now();
int64_t active_time = GetCurrentTimeMicros();
std::lock_guard l(mutex_);
if (!tablet_checkpoints_.count(producer_tablet)) {
tablet_checkpoints_.emplace(TabletCheckpointInfo{
.producer_tablet_info = producer_tablet,
.cdc_state_checkpoint = {op_id, time, active_time},
.sent_checkpoint = {op_id, time, active_time},
.mem_tracker = nullptr});
}
}
void EraseStreams(
const std::vector<TabletStreamInfo>& producer_entries_modified,
bool erase_cdc_states) NO_THREAD_SAFETY_ANALYSIS {
for (const auto& entry : producer_entries_modified) {
tablet_checkpoints_.get<StreamTag>().erase(entry.stream_id);
if (erase_cdc_states) {
cdc_state_metadata_.get<StreamTag>().erase(entry.stream_id);
}
}
}
boost::optional<int64_t> GetLastActiveTime(const TabletStreamInfo& producer_tablet) {
SharedLock<rw_spinlock> lock(mutex_);
auto it = tablet_checkpoints_.find(producer_tablet);
if (it != tablet_checkpoints_.end()) {
// Use last_active_time from cache only if it is current.
if (it->cdc_state_checkpoint.last_active_time > 0) {
if (!it->cdc_state_checkpoint.ExpiredAt(
FLAGS_cdc_state_checkpoint_update_interval_ms * 1ms, CoarseMonoClock::Now())) {
VLOG(2) << "Found recent entry in cache with active time: "
<< it->cdc_state_checkpoint.last_active_time
<< ", for tablet: " << producer_tablet.tablet_id
<< ", and stream: " << producer_tablet.stream_id;
return it->cdc_state_checkpoint.last_active_time;
} else {
VLOG(2) << "Found stale entry in cache with active time: "
<< it->cdc_state_checkpoint.last_active_time
<< ", for tablet: " << producer_tablet.tablet_id
<< ", and stream: " << producer_tablet.stream_id
<< ". We will read from the cdc_state table";
}
}
} else {
VLOG(1) << "Did not find entry in 'tablet_checkpoints_' cache for tablet: "
<< producer_tablet.tablet_id << ", stream: " << producer_tablet.stream_id;
}
return boost::none;
}
Status EraseTabletAndStreamEntry(const TabletStreamInfo& info) {
std::lock_guard l(mutex_);
// Here we just remove the entries of the tablet from the in-memory caches. The deletion from
// the 'cdc_state' table will happen when the hidden parent tablet will be deleted
// asynchronously.
tablet_checkpoints_.erase(info);
cdc_state_metadata_.erase(info);
return Status::OK();
}
boost::optional<OpId> GetLastCheckpoint(const TabletStreamInfo& producer_tablet) {
SharedLock<rw_spinlock> lock(mutex_);
auto it = tablet_checkpoints_.find(producer_tablet);
if (it != tablet_checkpoints_.end()) {
// Use checkpoint from cache only if it is current.
if (it->cdc_state_checkpoint.op_id.index > 0 &&
!it->cdc_state_checkpoint.ExpiredAt(
FLAGS_cdc_state_checkpoint_update_interval_ms * 1ms, CoarseMonoClock::Now())) {
return it->cdc_state_checkpoint.op_id;
}
}
return boost::none;
}
bool UpdateCheckpoint(
const TabletStreamInfo& producer_tablet, const OpId& sent_op_id, const OpId& commit_op_id) {
VLOG(1) << "T " << producer_tablet.tablet_id << " going to update the checkpoint with "
<< commit_op_id;
auto now = CoarseMonoClock::Now();
auto active_time = GetCurrentTimeMicros();
TabletCheckpoint sent_checkpoint = {
.op_id = sent_op_id,
.last_update_time = now,
.last_active_time = active_time,
};
TabletCheckpoint commit_checkpoint = {
.op_id = commit_op_id,
.last_update_time = now,
.last_active_time = active_time,
};
std::lock_guard l(mutex_);
auto it = tablet_checkpoints_.find(producer_tablet);
if (it != tablet_checkpoints_.end()) {
it->sent_checkpoint = sent_checkpoint;
if (commit_op_id.index >= 0) {
it->cdc_state_checkpoint.op_id = commit_op_id;
}
// Check if we need to update cdc_state table.
if (!it->cdc_state_checkpoint.ExpiredAt(
FLAGS_cdc_state_checkpoint_update_interval_ms * 1ms, now)) {
return false;
}
it->cdc_state_checkpoint.last_update_time = now;
} else {
tablet_checkpoints_.emplace(TabletCheckpointInfo{
.producer_tablet_info = producer_tablet,
.cdc_state_checkpoint = commit_checkpoint,
.sent_checkpoint = sent_checkpoint,
.mem_tracker = nullptr,
});
}
return true;
}
OpId GetMinSentCheckpointForTablet(const TabletId& tablet_id) {
OpId min_op_id = OpId::Max();
SharedLock<rw_spinlock> l(mutex_);
auto it_range = tablet_checkpoints_.get<TabletTag>().equal_range(tablet_id);
if (it_range.first == it_range.second) {
LOG(WARNING) << "Tablet ID not found in stream_tablets map: " << tablet_id;
return min_op_id;
}
auto cdc_checkpoint_opid_interval = FLAGS_cdc_checkpoint_opid_interval_ms * 1ms;
for (auto it = it_range.first; it != it_range.second; ++it) {
// We don't want to include streams that are not being actively polled.
// So, if the stream has not been polled in the last x seconds,
// then we ignore that stream while calculating min op ID.
if (!it->sent_checkpoint.ExpiredAt(cdc_checkpoint_opid_interval, CoarseMonoClock::Now()) &&
it->sent_checkpoint.op_id.index < min_op_id.index) {
min_op_id = it->sent_checkpoint.op_id;
}
}
return min_op_id;
}
MemTrackerPtr GetMemTracker(
const std::shared_ptr<tablet::TabletPeer>& tablet_peer,
const TabletStreamInfo& producer_info) {
{
SharedLock<rw_spinlock> l(mutex_);
auto it = tablet_checkpoints_.find(producer_info);
if (it == tablet_checkpoints_.end()) {
return nullptr;
}
if (it->mem_tracker) {
return it->mem_tracker;
}
}
std::lock_guard l(mutex_);
auto it = tablet_checkpoints_.find(producer_info);
if (it == tablet_checkpoints_.end()) {
return nullptr;
}
if (it->mem_tracker) {
return it->mem_tracker;
}
auto tablet_ptr = tablet_peer->shared_tablet();
if (!tablet_ptr) {
return nullptr;
}
auto cdc_mem_tracker = MemTracker::FindOrCreateTracker(
"CDC", tablet_ptr->mem_tracker());
it->mem_tracker =
MemTracker::FindOrCreateTracker(producer_info.stream_id.ToString(), cdc_mem_tracker);
return it->mem_tracker;
}
Result<bool> PreCheckTabletValidForStream(const TabletStreamInfo& info) {
SharedLock<rw_spinlock> l(mutex_);
if (tablet_checkpoints_.count(info) != 0) {
return true;
}
if (tablet_checkpoints_.get<StreamTag>().count(info.stream_id) != 0) {
// Did not find matching tablet ID.
LOG(INFO) << "Tablet ID " << info.tablet_id << " is not part of stream ID " << info.stream_id
<< ". Repopulating tablet list for this stream.";
}
return false;
}
Status AddEntriesForChildrenTabletsOnSplitOp(
const TabletStreamInfo& info, const std::array<TabletId, 2>& tablets,
const OpId& children_op_id) {
std::lock_guard l(mutex_);
for (const auto& tablet : tablets) {
TabletStreamInfo producer_info{info.stream_id, tablet};
tablet_checkpoints_.emplace(TabletCheckpointInfo{
.producer_tablet_info = producer_info,
.cdc_state_checkpoint =
TabletCheckpoint{
.op_id = children_op_id, .last_update_time = {}, .last_active_time = {}},
.sent_checkpoint =
TabletCheckpoint{
.op_id = children_op_id, .last_update_time = {}, .last_active_time = {}},
.mem_tracker = nullptr,
});
cdc_state_metadata_.emplace(CDCStateMetadataInfo{
.producer_tablet_info = producer_info,
.commit_timestamp = {},
.last_streamed_op_id = children_op_id,
.schema_details_map = {},
.mem_tracker = nullptr,
});
}
return Status::OK();
}
Status CheckTabletValidForStream(
const TabletStreamInfo& info,
const google::protobuf::RepeatedPtrField<master::TabletLocationsPB>& tablets) {
bool found = false;
{
std::lock_guard l(mutex_);
for (const auto& tablet : tablets) {
// Add every tablet in the stream.
TabletStreamInfo producer_info{info.stream_id, tablet.tablet_id()};
tablet_checkpoints_.emplace(TabletCheckpointInfo{
.producer_tablet_info = producer_info,
.cdc_state_checkpoint =
TabletCheckpoint{.op_id = {}, .last_update_time = {}, .last_active_time = {}},
.sent_checkpoint =
TabletCheckpoint{.op_id = {}, .last_update_time = {}, .last_active_time = {}},
.mem_tracker = nullptr,
});
cdc_state_metadata_.emplace(CDCStateMetadataInfo{
.producer_tablet_info = producer_info,
.commit_timestamp = {},
.last_streamed_op_id = OpId::Invalid(),
.schema_details_map = {},
.mem_tracker = nullptr,
});
// If this is the tablet that the user requested.
if (tablet.tablet_id() == info.tablet_id) {
found = true;
}
}
}
return found ? Status::OK()
: STATUS_FORMAT(
InvalidArgument, "Tablet ID $0 is not part of stream ID $1", info.tablet_id,
info.stream_id);
}
boost::optional<OpId> MinOpId(const TabletId& tablet_id) {
boost::optional<OpId> result;
SharedLock<rw_spinlock> l(mutex_);
// right => multimap where keys are tablet_ids and values are stream_ids.
// left => multimap where keys are stream_ids and values are tablet_ids.
auto it_range = tablet_checkpoints_.get<TabletTag>().equal_range(tablet_id);
if (it_range.first != it_range.second) {
// Iterate over all the streams for this tablet.
for (auto it = it_range.first; it != it_range.second; ++it) {
if (!result || it->cdc_state_checkpoint.op_id.index < result->index) {
result = it->cdc_state_checkpoint.op_id;
}
}
} else {
VLOG(2) << "Didn't find any streams for tablet " << tablet_id;
}
return result;
}
TabletCheckpoints TabletCheckpointsCopy() {
SharedLock<rw_spinlock> lock(mutex_);
return tablet_checkpoints_;
}
Result<TabletCheckpoint> TEST_GetTabletInfoFromCache(const TabletStreamInfo& producer_tablet) {
SharedLock<rw_spinlock> l(mutex_);
auto it = tablet_checkpoints_.find(producer_tablet);
if (it != tablet_checkpoints_.end()) {
return it->cdc_state_checkpoint;
}
return STATUS_FORMAT(
InternalError, "Tablet info: $0 not found in cache.", producer_tablet.ToString());
}
void UpdateActiveTime(const TabletStreamInfo& producer_tablet) {
SharedLock<rw_spinlock> l(mutex_);
auto it = tablet_checkpoints_.find(producer_tablet);
if (it != tablet_checkpoints_.end()) {
auto active_time = GetCurrentTimeMicros();
VLOG(2) << "Updating active time for tablet: " << producer_tablet.tablet_id
<< ", stream: " << producer_tablet.stream_id << ", as: " << active_time
<< ", previous value: " << it->cdc_state_checkpoint.last_active_time;
it->cdc_state_checkpoint.last_active_time = active_time;
}
}
void ForceCdcStateUpdate(const TabletStreamInfo& producer_tablet) {
std::lock_guard l(mutex_);
auto it = tablet_checkpoints_.find(producer_tablet);
if (it != tablet_checkpoints_.end()) {
// Setting the timestamp to min will result in ExpiredAt saying it is expired.
it->cdc_state_checkpoint.last_update_time = CoarseTimePoint::min();
}
}
void ClearCaches() {
std::lock_guard l(mutex_);
tablet_checkpoints_.clear();
cdc_state_metadata_.clear();
}
// this will be used for the std::call_once call while caching the client
std::once_flag is_client_cached_;
private:
rw_spinlock& mutex_;
TabletCheckpoints tablet_checkpoints_ GUARDED_BY(mutex_);
CDCStateMetadata cdc_state_metadata_ GUARDED_BY(mutex_);
};
CDCServiceImpl::CDCServiceImpl(
std::unique_ptr<CDCServiceContext> context,
const scoped_refptr<MetricEntity>& metric_entity_server, MetricRegistry* metric_registry,
const std::shared_future<client::YBClient*>& client_future)
: CDCServiceIf(metric_entity_server),
context_(std::move(context)),
metric_registry_(metric_registry),
server_metrics_(std::make_shared<xrepl::CDCServerMetrics>(metric_entity_server)),
get_changes_rpc_sem_(std::max(
1.0, floor(FLAGS_rpc_workers_limit * (1 - FLAGS_cdc_get_changes_free_rpc_ratio)))),
rate_limiter_(std::unique_ptr<rocksdb::RateLimiter>(rocksdb::NewGenericRateLimiter(
GetAtomicFlag(&FLAGS_xcluster_get_changes_max_send_rate_mbps) * 1_MB))),
impl_(new Impl(context_.get(), &mutex_)),
client_future_(client_future) {
cdc_state_table_ = std::make_unique<cdc::CDCStateTable>(client_future);
CHECK_OK(Thread::Create(
"cdc_service", "update_peers_and_metrics", &CDCServiceImpl::UpdatePeersAndMetrics, this,
&update_peers_and_metrics_thread_));
rate_limiter_->EnableLoggingWithDescription("CDC Service");
LOG_IF(WARNING, get_changes_rpc_sem_.GetValue() == 1) << "only 1 thread available for GetChanges";
}
CDCServiceImpl::~CDCServiceImpl() { Shutdown(); }
client::YBClient* CDCServiceImpl::client() { return client_future_.get(); }
namespace {
std::unordered_map<std::string, std::string> GetCreateCDCStreamOptions(
const CreateCDCStreamRequestPB* req) {
std::unordered_map<std::string, std::string> options;
if (req->has_namespace_name()) {
options.reserve(5);
} else {
options.reserve(4);
}
options.emplace(kRecordType, CDCRecordType_Name(req->record_type()));
options.emplace(kRecordFormat, CDCRecordFormat_Name(req->record_format()));
options.emplace(kSourceType, CDCRequestSource_Name(req->source_type()));
options.emplace(kCheckpointType, CDCCheckpointType_Name(req->checkpoint_type()));
if (req->has_namespace_name()) {
options.emplace(kIdType, kNamespaceId);
}
return options;
}
Status DoUpdateCDCConsumerOpId(
const std::shared_ptr<tablet::TabletPeer>& tablet_peer,
const OpId& checkpoint,
const TabletId& tablet_id) {
VERIFY_RESULT(tablet_peer->GetConsensus())->UpdateCDCConsumerOpId(checkpoint);
return Status::OK();
}
bool UpdateCheckpointRequired(
const StreamMetadata& record, const CDCSDKCheckpointPB& cdc_sdk_op_id, bool* is_snapshot) {
*is_snapshot = false;
switch (record.GetSourceType()) {
case XCLUSTER:
return true;
case CDCSDK:
if (cdc_sdk_op_id.write_id() == 0) {
return true;
}
if (CDCServiceImpl::IsCDCSDKSnapshotRequest(cdc_sdk_op_id)) {
*is_snapshot = true;
// CDC should update the stream active time in cdc_state table, during snapshot operation to
// avoid stream expiry.
return true;
}
break;
default:
return false;
}
return false;
}
bool GetExplicitOpIdAndSafeTime(
const GetChangesRequestPB* req, OpId* op_id, CDCSDKCheckpointPB* cdc_sdk_explicit_op_id,
uint64_t* cdc_sdk_explicit_safe_time) {
if (req->has_explicit_cdc_sdk_checkpoint()) {
*cdc_sdk_explicit_op_id = req->explicit_cdc_sdk_checkpoint();
*op_id = OpId::FromPB(*cdc_sdk_explicit_op_id);
if (!req->explicit_cdc_sdk_checkpoint().has_snapshot_time()) {
*cdc_sdk_explicit_safe_time = 0;
} else {
*cdc_sdk_explicit_safe_time = req->explicit_cdc_sdk_checkpoint().snapshot_time();
}
return true;
}
return false;
}
bool GetFromOpId(const GetChangesRequestPB* req, OpId* op_id, CDCSDKCheckpointPB* cdc_sdk_op_id) {
if (req->has_from_checkpoint()) {
*op_id = OpId::FromPB(req->from_checkpoint().op_id());
} else if (req->has_from_cdc_sdk_checkpoint()) {
*cdc_sdk_op_id = req->from_cdc_sdk_checkpoint();
*op_id = OpId::FromPB(*cdc_sdk_op_id);
} else {
return false;
}
return true;
}
CoarseTimePoint GetDeadline(const RpcContext& context, client::YBClient* client) {
CoarseTimePoint deadline = context.GetClientDeadline();
if (deadline == CoarseTimePoint::max()) { // Not specified by user.
deadline = CoarseMonoClock::now() + client->default_rpc_timeout();
}
return deadline;
}
Status VerifyArg(const SetCDCCheckpointRequestPB& req) {
if (!req.has_checkpoint() && !req.has_bootstrap()) {
return STATUS(InvalidArgument, "OpId is required to set checkpoint");
}
if (!req.has_tablet_id()) {
return STATUS(InvalidArgument, "Tablet ID is required to set checkpoint");
}
if (!req.has_stream_id()) {
return STATUS(InvalidArgument, "Stream ID is required to set checkpoint");
}
if (req.has_checkpoint()) {
OpId op_id = OpId::FromPB(req.checkpoint().op_id());
if (op_id.term < OpId::Invalid().term || op_id.index < OpId::Invalid().index) {
LOG(WARNING) << "Received Invalid OpId " << op_id;
return STATUS_FORMAT(InvalidArgument, "Valid OpId is required to set checkpoint : $0", op_id);
}
}
return Status::OK();
}
} // namespace
template <class ReqType, class RespType>
bool CDCServiceImpl::CheckOnline(const ReqType* req, RespType* resp, rpc::RpcContext* rpc) {
TRACE("Received RPC $0: $1", rpc->ToString(), req->DebugString());
if (PREDICT_FALSE(!context_)) {
SetupErrorAndRespond(
resp->mutable_error(),
STATUS(ServiceUnavailable, "Tablet Server is not running"),
CDCErrorPB::NOT_RUNNING,
rpc);
return false;
}
return true;
}
void CDCServiceImpl::InitNewTabletStreamEntry(
const xrepl::StreamId& stream_id, const TabletId& tablet_id,
std::vector<TabletStreamInfo>* producer_entries_modified,
std::vector<CDCStateTableEntry>* entries_to_insert) {
// For CDCSDK the initial checkpoint for each tablet will be maintained
// in cdc_state table as -1.-1(Invalid), which is the default value of 'op_id'. Checkpoint will be
// updated when client call setCDCCheckpoint.
const auto op_id = OpId::Invalid();
CDCStateTableEntry entry(tablet_id, stream_id);
entry.checkpoint = op_id;
entry.active_time = 0;
entry.cdc_sdk_safe_time = 0;
entries_to_insert->push_back(std::move(entry));
producer_entries_modified->push_back({.stream_id = stream_id, .tablet_id = tablet_id});
impl_->AddTabletCheckpoint(op_id, stream_id, tablet_id);
}
Result<NamespaceId> CDCServiceImpl::GetNamespaceId(
const std::string& ns_name, YQLDatabase db_type) {
master::GetNamespaceInfoResponsePB namespace_info_resp;
RETURN_NOT_OK(
client()->GetNamespaceInfo(std::string(), ns_name, db_type, &namespace_info_resp));
return namespace_info_resp.namespace_().id();
}
Result<EnumOidLabelMap> CDCServiceImpl::GetEnumMapFromCache(
const NamespaceName& ns_name, bool cql_namespace) {
{
yb::SharedLock<decltype(mutex_)> l(mutex_);
if (enumlabel_cache_.find(ns_name) != enumlabel_cache_.end()) {
return enumlabel_cache_.at(ns_name);
}
}
return UpdateEnumCacheAndGetMap(ns_name, cql_namespace);
}
Result<EnumOidLabelMap> CDCServiceImpl::UpdateEnumCacheAndGetMap(
const NamespaceName& ns_name, bool cql_namespace) {
std::lock_guard l(mutex_);