-
Notifications
You must be signed in to change notification settings - Fork 1k
/
meta_cache.cc
2477 lines (2171 loc) · 91.3 KB
/
meta_cache.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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//
// The following only applies to changes made to this file as part of YugaByte development.
//
// Portions 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/client/meta_cache.h"
#include <stdint.h>
#include <atomic>
#include <list>
#include <memory>
#include <shared_mutex>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <boost/optional/optional_io.hpp>
#include "yb/client/client.h"
#include "yb/client/client_error.h"
#include "yb/client/client_master_rpc.h"
#include "yb/client/client-internal.h"
#include "yb/client/schema.h"
#include "yb/client/table.h"
#include "yb/client/yb_table_name.h"
#include "yb/common/common_consensus_util.h"
#include "yb/common/wire_protocol.h"
#include "yb/gutil/map-util.h"
#include "yb/gutil/ref_counted.h"
#include "yb/gutil/strings/substitute.h"
#include "yb/master/master_client.proxy.h"
#include "yb/rpc/rpc_fwd.h"
#include "yb/tserver/local_tablet_server.h"
#include "yb/tserver/tserver_service.proxy.h"
#include "yb/util/async_util.h"
#include "yb/util/atomic.h"
#include "yb/util/callsite_profiling.h"
#include "yb/util/flags.h"
#include "yb/util/locks.h"
#include "yb/util/logging.h"
#include "yb/util/metrics.h"
#include "yb/util/monotime.h"
#include "yb/util/net/dns_resolver.h"
#include "yb/util/net/net_util.h"
#include "yb/util/net/sockaddr.h"
#include "yb/util/random_util.h"
#include "yb/util/result.h"
#include "yb/util/scope_exit.h"
#include "yb/util/shared_lock.h"
#include "yb/util/status_format.h"
#include "yb/util/unique_lock.h"
using std::map;
using std::shared_ptr;
using std::string;
using strings::Substitute;
using namespace std::literals;
using namespace std::placeholders;
DEFINE_UNKNOWN_int32(max_concurrent_master_lookups, 500,
"Maximum number of concurrent tablet location lookups from YB client to master");
DEFINE_test_flag(bool, verify_all_replicas_alive, false,
"If set, when a RemoteTablet object is destroyed, we will verify that all its "
"replicas are not marked as failed");
DEFINE_UNKNOWN_int32(retry_failed_replica_ms, 3600 * 1000,
"Time in milliseconds to wait for before retrying a failed replica");
DEFINE_UNKNOWN_int64(meta_cache_lookup_throttling_step_ms, 5,
"Step to increment delay between calls during lookup throttling.");
DEFINE_UNKNOWN_int64(meta_cache_lookup_throttling_max_delay_ms, 1000,
"Max delay between calls during lookup throttling.");
DEFINE_test_flag(bool, force_master_lookup_all_tablets, false,
"If set, force the client to go to the master for all tablet lookup "
"instead of reading from cache.");
DEFINE_test_flag(double, simulate_lookup_timeout_probability, 0,
"If set, mark an RPC as failed and force retry on the first attempt.");
DEFINE_test_flag(double, simulate_lookup_partition_list_mismatch_probability, 0,
"Probability for simulating the partition list mismatch error on tablet lookup.");
METRIC_DEFINE_event_stats(
server, dns_resolve_latency_during_init_proxy,
"yb.client.MetaCache.InitProxy DNS Resolve",
yb::MetricUnit::kMicroseconds,
"Microseconds spent resolving DNS requests during MetaCache::InitProxy");
DECLARE_string(placement_cloud);
DECLARE_string(placement_region);
DECLARE_bool(TEST_always_return_consensus_info_for_succeeded_rpc);
namespace yb {
using master::GetTableLocationsRequestPB;
using master::GetTableLocationsResponsePB;
using master::TabletLocationsPB;
using master::TabletLocationsPB_ReplicaPB;
using tablet::RaftGroupStatePB;
using tserver::LocalTabletServer;
using tserver::TabletServerServiceProxy;
namespace client {
namespace internal {
namespace {
// We join tablet partitions to groups, so tablet state info in one group requested with single
// RPC call to master.
// kPartitionGroupSize defines size of this group.
#ifdef NDEBUG
const size_t kPartitionGroupSize = 64;
#else
const size_t kPartitionGroupSize = 4;
#endif
std::atomic<int64_t> lookup_serial_{1};
} // namespace
int64_t TEST_GetLookupSerial() {
return lookup_serial_.load(std::memory_order_acquire);
}
////////////////////////////////////////////////////////////
RemoteTabletServer::RemoteTabletServer(const master::TSInfoPB& pb)
: uuid_(pb.permanent_uuid()) {
Update(pb);
}
RemoteTabletServer::RemoteTabletServer(const consensus::RaftPeerPB& raft_peer)
: uuid_(raft_peer.permanent_uuid()) {
UpdateFromRaftPeer(raft_peer);
}
RemoteTabletServer::RemoteTabletServer(const string& uuid,
const shared_ptr<TabletServerServiceProxy>& proxy,
const LocalTabletServer* local_tserver)
: uuid_(uuid),
proxy_(proxy),
local_tserver_(local_tserver) {
LOG_IF(DFATAL, proxy && !IsLocal()) << "Local tserver has non-local proxy";
}
RemoteTabletServer::~RemoteTabletServer() = default;
Status RemoteTabletServer::InitProxy(YBClient* client) {
{
SharedLock lock(mutex_);
if (proxy_) {
// Already have a proxy created.
return Status::OK();
}
}
std::lock_guard lock(mutex_);
if (proxy_) {
// Already have a proxy created.
return Status::OK();
}
if (!dns_resolve_stats_) {
auto metric_entity = client->metric_entity();
if (metric_entity) {
dns_resolve_stats_ = METRIC_dns_resolve_latency_during_init_proxy.Instantiate(
metric_entity);
}
}
// TODO: if the TS advertises multiple host/ports, pick the right one
// based on some kind of policy. For now just use the first always.
auto hostport = HostPortFromPB(yb::DesiredHostPort(
public_rpc_hostports_, private_rpc_hostports_, cloud_info_pb_,
client->data_->cloud_info_pb_));
CHECK(!hostport.host().empty());
ScopedDnsTracker dns_tracker(dns_resolve_stats_.get());
proxy_.reset(new TabletServerServiceProxy(client->data_->proxy_cache_.get(), hostport));
proxy_endpoint_ = hostport;
return Status::OK();
}
void RemoteTabletServer::Update(const master::TSInfoPB& pb) {
CHECK_EQ(pb.permanent_uuid(), uuid_);
std::lock_guard lock(mutex_);
private_rpc_hostports_ = pb.private_rpc_addresses();
public_rpc_hostports_ = pb.broadcast_addresses();
cloud_info_pb_ = pb.cloud_info();
}
void RemoteTabletServer::UpdateFromRaftPeer(const consensus::RaftPeerPB& raft_peer) {
if (raft_peer.permanent_uuid() != uuid_) {
VLOG(1) << "RemoteTabletServer " << raft_peer.permanent_uuid()
<< " cannot be updated because the raft_peer has a wrong permanent_uuid";
return;
}
std::lock_guard lock(mutex_);
private_rpc_hostports_ = raft_peer.last_known_private_addr();
public_rpc_hostports_ = raft_peer.last_known_broadcast_addr();
cloud_info_pb_ = raft_peer.cloud_info();
}
bool RemoteTabletServer::IsLocal() const {
return local_tserver_ != nullptr;
}
const std::string& RemoteTabletServer::permanent_uuid() const {
return uuid_;
}
shared_ptr<TabletServerServiceProxy> RemoteTabletServer::proxy() const {
SharedLock lock(mutex_);
return proxy_;
}
::yb::HostPort RemoteTabletServer::ProxyEndpoint() const {
SharedLock lock(mutex_);
return proxy_endpoint_;
}
string RemoteTabletServer::ToString() const {
string ret = "{ uuid: " + uuid_;
SharedLock lock(mutex_);
if (!private_rpc_hostports_.empty()) {
ret += Format(" private: $0", private_rpc_hostports_);
}
if (!public_rpc_hostports_.empty()) {
ret += Format(" public: $0", public_rpc_hostports_);
}
ret += Format(" cloud_info: $0", cloud_info_pb_);
return ret;
}
bool RemoteTabletServer::HasHostFrom(const std::unordered_set<std::string>& hosts) const {
SharedLock lock(mutex_);
for (const auto& hp : private_rpc_hostports_) {
if (hosts.count(hp.host())) {
return true;
}
}
for (const auto& hp : public_rpc_hostports_) {
if (hosts.count(hp.host())) {
return true;
}
}
return false;
}
bool RemoteTabletServer::IsLocalRegion() const {
SharedLock lock(mutex_);
return cloud_info_pb_.placement_cloud() == FLAGS_placement_cloud &&
cloud_info_pb_.placement_region() == FLAGS_placement_region;
}
LocalityLevel RemoteTabletServer::LocalityLevelWith(const CloudInfoPB& cloud_info) const {
SharedLock lock(mutex_);
return PlacementInfoConverter::GetLocalityLevel(cloud_info_pb_, cloud_info);
}
HostPortPB RemoteTabletServer::DesiredHostPort(const CloudInfoPB& cloud_info) const {
SharedLock lock(mutex_);
return yb::DesiredHostPort(
public_rpc_hostports_, private_rpc_hostports_, cloud_info_pb_, cloud_info);
}
std::string RemoteTabletServer::TEST_PlacementZone() const {
SharedLock lock(mutex_);
return cloud_info_pb_.placement_zone();
}
std::string ReplicasCount::ToString() {
return Format(
" live replicas $0, read replicas $1, expected live replicas $2, expected read replicas $3",
num_alive_live_replicas, num_alive_read_replicas,
expected_live_replicas, expected_read_replicas);
}
////////////////////////////////////////////////////////////
RemoteTablet::RemoteTablet(std::string tablet_id,
dockv::Partition partition,
boost::optional<PartitionListVersion> partition_list_version,
uint64 split_depth,
const TabletId& split_parent_tablet_id,
int64_t raft_config_opid_index)
: tablet_id_(std::move(tablet_id)),
log_prefix_(Format("T $0: ", tablet_id_)),
partition_(std::move(partition)),
partition_list_version_(partition_list_version),
split_depth_(split_depth),
split_parent_tablet_id_(split_parent_tablet_id),
stale_(false),
raft_config_opid_index_(raft_config_opid_index) {
}
RemoteTablet::~RemoteTablet() {
if (PREDICT_FALSE(FLAGS_TEST_verify_all_replicas_alive)) {
// Let's verify that none of the replicas are marked as failed. The test should always wait
// enough time so that the lookup cache can be refreshed after force_lookup_cache_refresh_secs.
for (const auto& replica : replicas_) {
if (replica->Failed()) {
LOG_WITH_PREFIX(FATAL) << "Remote tablet server " << replica->ts->ToString()
<< " with role " << PeerRole_Name(replica->role)
<< " is marked as failed";
}
}
}
}
Status RemoteTablet::RefreshFromRaftConfig(
const TabletServerMap& tservers, const consensus::RaftConfigPB& raft_config,
const consensus::ConsensusStatePB& consensus_state) {
std::lock_guard lock(mutex_);
std::vector<std::shared_ptr<RemoteReplica>> new_replicas;
std::string leader_uuid = "";
for (const auto& peer : raft_config.peers()) {
auto tserver = FindPtrOrNull(tservers, peer.permanent_uuid());
SCHECK(tserver, NotFound, Format("TServer with ID $0 not found.", peer.permanent_uuid()));
auto role = GetConsensusRole(peer.permanent_uuid(), consensus_state);
if (role == PeerRole::LEADER) {
leader_uuid = peer.permanent_uuid();
}
new_replicas.emplace_back(std::make_shared<RemoteReplica>(tserver.get(), role));
}
replicas_ = std::move(new_replicas);
raft_config_opid_index_ = consensus_state.config().opid_index();
VLOG(1) << "Raft config refresh succeeded with opid_index: " << raft_config_opid_index_
<< " for tablet: " << tablet_id_
<< ", replicas are now: " << ReplicasAsStringUnlocked();
current_leader_uuid_ = leader_uuid;
return Status::OK();
// Note that we do not update the stale_ variable here: because this is a partial refresh -- we
// are not updating the partition information, in particular -- it is not safe to mark us as
// no longer stale.
}
void RemoteTablet::Refresh(
const TabletServerMap& tservers,
const google::protobuf::RepeatedPtrField<TabletLocationsPB_ReplicaPB>& replicas) {
// Adopt the data from the successful response.
std::lock_guard lock(mutex_);
std::vector<std::string> old_uuids;
old_uuids.reserve(replicas_.size());
for (const auto& replica : replicas_) {
old_uuids.push_back(replica->ts->permanent_uuid());
}
std::sort(old_uuids.begin(), old_uuids.end());
replicas_.clear();
bool has_new_replica = false;
current_leader_uuid_ = "";
for (const TabletLocationsPB_ReplicaPB& r : replicas) {
auto it = tservers.find(r.ts_info().permanent_uuid());
CHECK(it != tservers.end());
replicas_.emplace_back(std::make_shared<RemoteReplica>(it->second.get(), r.role()));
if(r.role() == PeerRole::LEADER) {
current_leader_uuid_ = r.ts_info().permanent_uuid();
}
has_new_replica =
has_new_replica ||
!std::binary_search(old_uuids.begin(), old_uuids.end(), r.ts_info().permanent_uuid());
}
if (has_new_replica) {
lookups_without_new_replicas_ = 0;
} else {
++lookups_without_new_replicas_;
}
stale_ = false;
full_refresh_time_.store(MonoTime::Now(), std::memory_order_release);
}
void RemoteTablet::MarkStale() {
std::lock_guard lock(mutex_);
stale_ = true;
}
bool RemoteTablet::stale() const {
SharedLock lock(mutex_);
return stale_;
}
void RemoteTablet::MarkAsSplit() {
std::lock_guard lock(mutex_);
is_split_ = true;
}
bool RemoteTablet::is_split() const {
SharedLock lock(mutex_);
return is_split_;
}
bool RemoteTablet::MarkReplicaFailed(RemoteTabletServer *ts, const Status& status) {
std::lock_guard lock(mutex_);
VLOG_WITH_PREFIX(2) << "Current remote replicas in meta cache: "
<< ReplicasAsStringUnlocked() << ". Replica " << ts->ToString()
<< " has failed: " << status.ToString();
for (auto& rep : replicas_) {
if (rep->ts == ts) {
rep->MarkFailed();
return true;
}
}
return false;
}
int RemoteTablet::GetNumFailedReplicas() const {
int failed = 0;
SharedLock lock(mutex_);
for (const auto& rep : replicas_) {
if (rep->Failed()) {
failed++;
}
}
return failed;
}
bool RemoteTablet::IsReplicasCountConsistent() const {
return replicas_count_.load(std::memory_order_acquire).IsReplicasCountConsistent();
}
string RemoteTablet::ReplicasCountToString() const {
return replicas_count_.load(std::memory_order_acquire).ToString();
}
void RemoteTablet::SetExpectedReplicas(int expected_live_replicas, int expected_read_replicas) {
ReplicasCount old_replicas_count = replicas_count_.load(std::memory_order_acquire);
for (;;) {
ReplicasCount new_replicas_count = old_replicas_count;
new_replicas_count.SetExpectedReplicas(expected_live_replicas, expected_read_replicas);
if (replicas_count_.compare_exchange_weak(
old_replicas_count, new_replicas_count, std::memory_order_acq_rel)) {
break;
}
}
}
void RemoteTablet::SetAliveReplicas(int alive_live_replicas, int alive_read_replicas) {
ReplicasCount old_replicas_count = replicas_count_.load(std::memory_order_acquire);
for (;;) {
ReplicasCount new_replicas_count = old_replicas_count;
new_replicas_count.SetAliveReplicas(alive_live_replicas, alive_read_replicas);
if (replicas_count_.compare_exchange_weak(
old_replicas_count, new_replicas_count, std::memory_order_acq_rel)) {
break;
}
}
}
void RemoteTablet::SetRaftConfigOpIdIndex(int64_t raft_config_opid_index) {
std::lock_guard lock(mutex_);
raft_config_opid_index_ = raft_config_opid_index;
}
RemoteTabletServer* RemoteTablet::LeaderTServer() const {
SharedLock lock(mutex_);
for (const auto& replica : replicas_) {
if (!replica->Failed() && replica->role == PeerRole::LEADER) {
return replica->ts;
}
}
return nullptr;
}
bool RemoteTablet::HasLeader() const {
return LeaderTServer() != nullptr;
}
void RemoteTablet::GetRemoteTabletServers(
std::vector<RemoteTabletServer*>* servers, IncludeFailedReplicas include_failed_replicas) {
DCHECK(servers->empty());
struct ReplicaUpdate {
std::shared_ptr<RemoteReplica> replica;
tablet::RaftGroupStatePB new_state;
bool clear_failed;
};
std::vector<ReplicaUpdate> replica_updates;
{
SharedLock lock(mutex_);
int num_alive_live_replicas = 0;
int num_alive_read_replicas = 0;
for (auto& replica : replicas_) {
if (replica->Failed()) {
if (include_failed_replicas) {
servers->push_back(replica->ts);
continue;
}
ReplicaUpdate replica_update = {replica, RaftGroupStatePB::UNKNOWN, false};
VLOG_WITH_PREFIX(4)
<< "Replica " << replica->ts->ToString()
<< " failed, state: " << RaftGroupStatePB_Name(replica->state)
<< ", is local: " << replica->ts->IsLocal()
<< ", time since failure: " << (MonoTime::Now() - replica->last_failed_time);
switch (replica->state) {
case RaftGroupStatePB::UNKNOWN: FALLTHROUGH_INTENDED;
case RaftGroupStatePB::NOT_STARTED: FALLTHROUGH_INTENDED;
case RaftGroupStatePB::BOOTSTRAPPING: FALLTHROUGH_INTENDED;
case RaftGroupStatePB::RUNNING:
// These are non-terminal states that may retry. Check and update failed local replica's
// current state. For remote replica, just wait for some time before retrying.
if (replica->ts->IsLocal()) {
tserver::GetTabletStatusRequestPB req;
tserver::GetTabletStatusResponsePB resp;
req.set_tablet_id(tablet_id_);
const Status status =
CHECK_NOTNULL(replica->ts->local_tserver())->GetTabletStatus(&req, &resp);
if (!status.ok() || resp.has_error()) {
LOG_WITH_PREFIX(ERROR)
<< "Received error from GetTabletStatus: "
<< (!status.ok() ? status : StatusFromPB(resp.error().status()));
continue;
}
if (resp.tablet_status().is_hidden()) {
// Should continue here because otherwise failed state will be cleared.
VLOG_WITH_PREFIX(3) << "Tablet is hidden";
continue;
}
DCHECK_EQ(resp.tablet_status().tablet_id(), tablet_id_);
VLOG_WITH_PREFIX(3) << "GetTabletStatus returned status: "
<< tablet::RaftGroupStatePB_Name(resp.tablet_status().state())
<< " for replica " << replica->ts->ToString();
replica_update.new_state = resp.tablet_status().state();
if (replica_update.new_state != tablet::RaftGroupStatePB::RUNNING) {
if (replica_update.new_state != replica->state) {
// Cannot update replica here directly because holding only shared lock on mutex.
replica_updates.push_back(replica_update); // Update only state
}
continue;
}
if (!replica->ts->local_tserver()->LeaderAndReady(
tablet_id_, /* allow_stale */ true)) {
// Should continue here because otherwise failed state will be cleared.
continue;
}
} else if ((MonoTime::Now() - replica->last_failed_time) <
FLAGS_retry_failed_replica_ms * 1ms) {
continue;
}
break;
case RaftGroupStatePB::FAILED: FALLTHROUGH_INTENDED;
case RaftGroupStatePB::QUIESCING: FALLTHROUGH_INTENDED;
case RaftGroupStatePB::SHUTDOWN:
// These are terminal states, so we won't retry.
continue;
}
VLOG_WITH_PREFIX(3) << "Changing state of replica " << replica->ts->ToString()
<< " from failed to not failed";
replica_update.clear_failed = true;
// Cannot update replica here directly because holding only shared lock on mutex.
replica_updates.push_back(replica_update);
} else {
if (replica->role == PeerRole::READ_REPLICA) {
num_alive_read_replicas++;
} else if (replica->role == PeerRole::FOLLOWER || replica->role == PeerRole::LEADER) {
num_alive_live_replicas++;
}
}
servers->push_back(replica->ts);
}
SetAliveReplicas(num_alive_live_replicas, num_alive_read_replicas);
}
if (!replica_updates.empty()) {
std::lock_guard lock(mutex_);
for (const auto& update : replica_updates) {
if (update.new_state != RaftGroupStatePB::UNKNOWN) {
update.replica->state = update.new_state;
}
if (update.clear_failed) {
update.replica->ClearFailed();
}
}
}
}
bool RemoteTablet::IsLocalRegion() {
auto tservers = GetRemoteTabletServers(internal::IncludeFailedReplicas::kTrue);
for (const auto &tserver : tservers) {
if (!tserver->IsLocalRegion()) {
return false;
}
}
return true;
}
bool RemoteTablet::MarkTServerAsLeader(const RemoteTabletServer* server) {
bool found = false;
std::lock_guard lock(mutex_);
for (auto& replica : replicas_) {
if (replica->ts == server) {
replica->role = PeerRole::LEADER;
found = true;
} else if (replica->role == PeerRole::LEADER) {
replica->role = PeerRole::FOLLOWER;
}
}
VLOG_WITH_PREFIX(3) << "Latest replicas: " << ReplicasAsStringUnlocked();
VLOG_IF_WITH_PREFIX(3, !found) << "Specified server not found: " << server->ToString()
<< ". Replicas: " << ReplicasAsStringUnlocked();
return found;
}
void RemoteTablet::MarkTServerAsFollower(const RemoteTabletServer* server) {
bool found = false;
std::lock_guard lock(mutex_);
for (auto& replica : replicas_) {
if (replica->ts == server) {
replica->role = PeerRole::FOLLOWER;
found = true;
}
}
VLOG_WITH_PREFIX(3) << "Latest replicas: " << ReplicasAsStringUnlocked();
DCHECK(found) << "Tablet " << tablet_id_ << ": Specified server not found: "
<< server->ToString() << ". Replicas: " << ReplicasAsStringUnlocked();
}
std::string RemoteTablet::current_leader_uuid() const {
SharedLock lock(mutex_);
return current_leader_uuid_;
}
std::string RemoteTablet::ReplicasAsString() const {
SharedLock lock(mutex_);
return ReplicasAsStringUnlocked();
}
std::string RemoteTablet::ReplicasAsStringUnlocked() const {
DCHECK(mutex_.is_locked());
string replicas_str;
for (const auto& rep : replicas_) {
if (!replicas_str.empty()) replicas_str += ", ";
replicas_str += rep->ToString();
}
return replicas_str;
}
std::string RemoteTablet::ToString() const {
return YB_CLASS_TO_STRING(tablet_id, partition, partition_list_version, split_depth);
}
PartitionListVersion RemoteTablet::GetLastKnownPartitionListVersion() const {
SharedLock lock(mutex_);
return last_known_partition_list_version_;
}
void RemoteTablet::MakeLastKnownPartitionListVersionAtLeast(
PartitionListVersion partition_list_version) {
std::lock_guard lock(mutex_);
last_known_partition_list_version_ =
std::max(last_known_partition_list_version_, partition_list_version);
}
void RemoteTablet::AddReplicasAsJson(JsonWriter* writer) const {
writer->StartObject();
writer->String("tablet_id");
writer->String(tablet_id());
writer->String("raft_config_opid_index");
writer->Int64(raft_config_opid_index());
writer->String("replicas");
writer->StartArray();
SharedLock lock(mutex_);
for (const auto& replica : replicas_) {
writer->StartObject();
writer->String("permanent_uuid");
writer->String(replica->ts->permanent_uuid());
writer->String("peer_role");
writer->String(PeerRole_Name(replica->role));
writer->String("failure_status");
writer->String(replica->Failed() ? "FAILED" : "OK");
writer->String("last_failed_time");
writer->String(replica->last_failed_time.ToFormattedString());
writer->String("last_failed_time_in_ns");
writer->Uint64(replica->last_failed_time.ToUint64());
writer->EndObject();
}
writer->EndArray();
writer->EndObject();
}
void LookupCallbackVisitor::operator()(const LookupTabletCallback& tablet_callback) const {
if (error_status_) {
tablet_callback(*error_status_);
return;
}
auto remote_tablet = boost::get<RemoteTabletPtr>(param_);
if (remote_tablet == nullptr) {
static const Status error_status = STATUS(
TryAgain, "Tablet for requested partition is not yet running",
ClientError(ClientErrorCode::kTabletNotYetRunning));
tablet_callback(error_status);
return;
}
tablet_callback(remote_tablet);
}
void LookupCallbackVisitor::operator()(
const LookupTabletRangeCallback& tablet_range_callback) const {
if (error_status_) {
tablet_range_callback(*error_status_);
return;
}
auto result = boost::get<std::vector<RemoteTabletPtr>>(param_);
tablet_range_callback(result);
}
////////////////////////////////////////////////////////////
MetaCache::MetaCache(YBClient* client)
: client_(client),
master_lookup_sem_(FLAGS_max_concurrent_master_lookups),
log_prefix_(Format("MetaCache($0)(client_id: $1): ", static_cast<void*>(this), client_->id())) {
}
MetaCache::~MetaCache() {
}
void MetaCache::SetLocalTabletServer(const string& permanent_uuid,
const shared_ptr<TabletServerServiceProxy>& proxy,
const LocalTabletServer* local_tserver) {
const auto entry = ts_cache_.emplace(permanent_uuid,
std::make_shared<RemoteTabletServer>(permanent_uuid,
proxy,
local_tserver));
CHECK(entry.second);
local_tserver_ = entry.first->second.get();
}
void MetaCache::UpdateTabletServerUnlocked(const master::TSInfoPB& pb) {
const std::string& permanent_uuid = pb.permanent_uuid();
auto it = ts_cache_.find(permanent_uuid);
if (it != ts_cache_.end()) {
it->second->Update(pb);
return;
}
VLOG_WITH_PREFIX(1) << "Client caching new TabletServer from Master TSInfo " << permanent_uuid;
CHECK(ts_cache_.emplace(permanent_uuid, std::make_shared<RemoteTabletServer>(pb)).second);
}
Status MetaCache::UpdateTabletServerWithRaftPeerUnlocked(const consensus::RaftPeerPB& pb) {
const std::string& permanent_uuid = pb.permanent_uuid();
auto it = ts_cache_.find(permanent_uuid);
if (it != ts_cache_.end()) {
it->second->UpdateFromRaftPeer(pb);
return Status::OK();
}
VLOG_WITH_PREFIX(1) << "Client caching new TabletServer from Raft Peer " << permanent_uuid;
SCHECK(
ts_cache_.emplace(permanent_uuid, std::make_shared<RemoteTabletServer>(pb)).second,
IllegalState, "Failed to emplace a remote tablet server into tablet server cache");
return Status::OK();
}
// A (table, partition_key) --> tablet lookup. May be in-flight to a master, or
// may be handled locally.
//
// Keeps a reference on the owning metacache while alive.
class LookupRpc : public internal::ClientMasterRpcBase, public RequestCleanup {
public:
LookupRpc(const scoped_refptr<MetaCache>& meta_cache,
const std::shared_ptr<const YBTable>& table,
int64_t request_no,
CoarseTimePoint deadline);
virtual ~LookupRpc();
void SendRpc() override;
MetaCache* meta_cache() { return meta_cache_.get(); }
YBClient* client() const { return meta_cache_->client_; }
virtual void NotifyFailure(const Status& status) = 0;
template <class Response>
void DoProcessResponse(const Status& status, const Response& resp);
// Subclasses can override VerifyResponse for implementing additional response checks. Called
// from Finished if there are no errors passed in response.
virtual Status VerifyResponse() { return Status::OK(); }
int64_t request_no() const {
return request_no_;
}
const std::shared_ptr<const YBTable>& table() const {
return table_;
}
// When we receive a response for a key lookup or full table rpc, add callbacks to be fired off
// to the to_notify set corresponding to the rpc type. Modify tables pointer by removing lookups
// as we add to the to_notify set.
virtual void AddCallbacksToBeNotified(
const ProcessedTablesMap& processed_tables,
std::unordered_map<TableId, TableData>* tables,
std::vector<std::pair<LookupCallback, LookupCallbackVisitor>>* to_notify) = 0;
// When looking up by key or full table, update the processe table with the returned location.
virtual void UpdateProcessedTable(const TabletLocationsPB& loc,
RemoteTabletPtr remote,
ProcessedTablesMap::mapped_type* processed_table) = 0;
private:
virtual Status ProcessTabletLocations(
const google::protobuf::RepeatedPtrField<master::TabletLocationsPB>& locations,
boost::optional<PartitionListVersion> table_partition_list_version) = 0;
const int64_t request_no_;
// Pointer back to the tablet cache. Populated with location information
// if the lookup finishes successfully.
//
// When the RPC is destroyed, a master lookup permit is returned to the
// cache if one was acquired in the first place.
scoped_refptr<MetaCache> meta_cache_;
// Table to lookup. Optional in case lookup by ID, but if specified used to check if table
// partitions are stale.
const std::shared_ptr<const YBTable> table_;
// Whether this lookup has acquired a master lookup permit.
bool has_permit_ = false;
};
LookupRpc::LookupRpc(const scoped_refptr<MetaCache>& meta_cache,
const std::shared_ptr<const YBTable>& table,
int64_t request_no,
CoarseTimePoint deadline)
: ClientMasterRpcBase(meta_cache->client_, deadline),
request_no_(request_no),
meta_cache_(meta_cache),
table_(table) {
DCHECK(deadline != CoarseTimePoint());
}
LookupRpc::~LookupRpc() {
if (has_permit_) {
meta_cache_->ReleaseMasterLookupPermit();
}
}
void LookupRpc::SendRpc() {
if (!has_permit_) {
has_permit_ = meta_cache_->AcquireMasterLookupPermit();
}
if (!has_permit_) {
// Couldn't get a permit, try again in a little while.
ScheduleRetry(STATUS(TryAgain, "Client has too many outstanding requests to the master"));
return;
}
// See YBClient::Data::SyncLeaderMasterRpc().
auto now = CoarseMonoClock::Now();
if (retrier().deadline() < now) {
Finished(STATUS_FORMAT(TimedOut, "Timed out after deadline expired, passed: $0",
MonoDelta(now - retrier().start())));
return;
}
mutable_retrier()->PrepareController();
ClientMasterRpcBase::SendRpc();
}
namespace {
Status GetFirstErrorForTabletById(const master::GetTabletLocationsResponsePB& resp) {
return resp.errors_size() > 0 ? StatusFromPB(resp.errors(0).status()) : Status::OK();
}
Status GetFirstErrorForTabletById(const master::GetTableLocationsResponsePB& resp) {
// There are no per-tablet lookup errors inside GetTableLocationsResponsePB.
return Status::OK();
}
template <class Response>
boost::optional<PartitionListVersion> GetPartitionListVersion(const Response& resp) {
return resp.has_partition_list_version()
? boost::make_optional<PartitionListVersion>(resp.partition_list_version())
: boost::none;
}
} // namespace
template <class Response>
void LookupRpc::DoProcessResponse(const Status& status, const Response& resp) {
auto new_status = status;
if (new_status.ok()) {
new_status = VerifyResponse();
}
// Prefer response failures over no tablets found.
if (new_status.ok()) {
new_status = GetFirstErrorForTabletById(resp);
}
if (new_status.ok() && resp.tablet_locations_size() == 0) {
new_status = STATUS(NotFound, "No such tablet found");
}
if (new_status.ok()) {
if (RandomActWithProbability(FLAGS_TEST_simulate_lookup_timeout_probability)) {
const auto s = STATUS(TimedOut, "Simulate timeout for test.");
NotifyFailure(s);
return;
}
new_status = ProcessTabletLocations(resp.tablet_locations(), GetPartitionListVersion(resp));
}
if (!new_status.ok()) {
YB_LOG_WITH_PREFIX_EVERY_N_SECS(WARNING, 1) << new_status;
new_status = new_status.CloneAndPrepend(Substitute("$0 failed", ToString()));
NotifyFailure(new_status);
}
}
namespace {
Status CheckTabletLocations(
const google::protobuf::RepeatedPtrField<master::TabletLocationsPB>& locations,
AllowSplitTablet allow_split_tablets) {
const std::string* prev_partition_end = nullptr;
for (const TabletLocationsPB& loc : locations) {
LOG_IF(DFATAL, !allow_split_tablets && loc.split_tablet_ids().size() > 0)
<< "Processing remote tablet location with split children id set: "
<< loc.ShortDebugString() << " when allow_split_tablets was set to false.";
if (prev_partition_end && *prev_partition_end > loc.partition().partition_key_start()) {
LOG(DFATAL) << "There should be no overlaps in tablet partitions and they should be sorted "
<< "by partition_key_start. Prev partition end: "
<< Slice(*prev_partition_end).ToDebugHexString() << ", current partition start: "
<< Slice(loc.partition().partition_key_start()).ToDebugHexString()
<< ". Tablet locations: " << [&locations] {
std::string result;
for (auto& loc : locations) {
result += "\n " + AsString(loc);
}
return result;
}();
return STATUS(IllegalState, "Wrong order or overlaps in partitions");
}
prev_partition_end = &loc.partition().partition_key_end();
}
return Status::OK();
}
class TabletIdLookup : public ToStringable {
public:
explicit TabletIdLookup(const TabletId& tablet_id) : tablet_id_(tablet_id) {}
std::string ToString() const override {
return Format("Tablet: $0", tablet_id_);
}
private:
const TabletId& tablet_id_;
};
class TablePartitionLookup : public ToStringable {
public:
explicit TablePartitionLookup(
const TableId& table_id, const VersionedPartitionGroupStartKey& partition_group_start)
: table_id_(table_id), partition_group_start_(partition_group_start) {}