-
Notifications
You must be signed in to change notification settings - Fork 1k
/
async_rpc_tasks.cc
1656 lines (1440 loc) · 63.5 KB
/
async_rpc_tasks.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/master/async_rpc_tasks.h"
#include "yb/common/common_types.pb.h"
#include "yb/common/wire_protocol.h"
#include "yb/consensus/consensus.proxy.h"
#include "yb/consensus/consensus_meta.h"
#include "yb/gutil/map-util.h"
#include "yb/master/catalog_entity_info.h"
#include "yb/master/catalog_manager_if.h"
#include "yb/master/master.h"
#include "yb/master/sys_catalog.h"
#include "yb/master/ts_descriptor.h"
#include "yb/master/ts_manager.h"
#include "yb/rpc/messenger.h"
#include "yb/tserver/backup.proxy.h"
#include "yb/tserver/tserver_admin.proxy.h"
#include "yb/tserver/tserver_service.proxy.h"
#include "yb/util/atomic.h"
#include "yb/util/flags.h"
#include "yb/util/metrics.h"
#include "yb/util/source_location.h"
#include "yb/util/status_format.h"
#include "yb/util/status_log.h"
#include "yb/util/thread_restrictions.h"
#include "yb/util/threadpool.h"
using namespace std::literals;
DEFINE_UNKNOWN_int32(unresponsive_ts_rpc_timeout_ms, 15 * 60 * 1000, // 15 minutes
"After this amount of time (or after we have retried unresponsive_ts_rpc_retry_limit "
"times, whichever happens first), the master will stop attempting to contact a tablet "
"server in order to perform operations such as deleting a tablet.");
TAG_FLAG(unresponsive_ts_rpc_timeout_ms, advanced);
DEFINE_UNKNOWN_int32(unresponsive_ts_rpc_retry_limit, 20,
"After this number of retries (or unresponsive_ts_rpc_timeout_ms expires, whichever "
"happens first), the master will stop attempting to contact a tablet server in order "
"to perform operations such as deleting a tablet.");
TAG_FLAG(unresponsive_ts_rpc_retry_limit, advanced);
DEFINE_UNKNOWN_int32(retrying_ts_rpc_max_delay_ms, 60 * 1000,
"Maximum delay between successive attempts to contact an unresponsive tablet server");
TAG_FLAG(retrying_ts_rpc_max_delay_ms, advanced);
DEFINE_test_flag(int32, slowdown_master_async_rpc_tasks_by_ms, 0,
"For testing purposes, slow down the run method to take longer.");
DEFINE_test_flag(bool, stuck_add_tablet_to_table_task_enabled, false, "description");
// The flags are defined in catalog_manager.cc.
DECLARE_int32(master_ts_rpc_timeout_ms);
DECLARE_int32(tablet_creation_timeout_ms);
DECLARE_int32(TEST_slowdown_alter_table_rpcs_ms);
namespace yb {
namespace master {
using namespace std::placeholders;
using std::string;
using std::shared_ptr;
using strings::Substitute;
using consensus::RaftPeerPB;
using server::MonitoredTaskState;
using server::MonitoredTaskType;
using tserver::TabletServerErrorPB;
void RetryingTSRpcTask::UpdateMetrics(scoped_refptr<Histogram> metric, MonoTime start_time,
const std::string& metric_name,
const std::string& metric_type) {
metric->Increment(MonoTime::Now().GetDeltaSince(start_time).ToMicroseconds());
}
// ============================================================================
// Class PickSpecificUUID.
// ============================================================================
Status PickSpecificUUID::PickReplica(TSDescriptor** ts_desc) {
shared_ptr<TSDescriptor> ts;
if (!master_->ts_manager()->LookupTSByUUID(ts_uuid_, &ts)) {
return STATUS(NotFound, "unknown tablet server id", ts_uuid_);
}
*ts_desc = ts.get();
return Status::OK();
}
string ReplicaMapToString(const TabletReplicaMap& replicas) {
string ret = "";
for (const auto& r : replicas) {
if (!ret.empty()) {
ret += ", ";
} else {
ret += "(";
}
ret += r.second.ts_desc->permanent_uuid();
}
ret += ")";
return ret;
}
// ============================================================================
// Class PickLeaderReplica.
// ============================================================================
PickLeaderReplica::PickLeaderReplica(const scoped_refptr<TabletInfo>& tablet)
: tablet_(tablet) {
}
Status PickLeaderReplica::PickReplica(TSDescriptor** ts_desc) {
*ts_desc = VERIFY_RESULT(tablet_->GetLeader());
return Status::OK();
}
// ============================================================================
// Class RetryingTSRpcTask.
// ============================================================================
// Constructor. The 'async_task_throttler' parameter is optional and may be null if the task does
// not throttle.
RetryingTSRpcTask::RetryingTSRpcTask(
Master *master,
ThreadPool* callback_pool,
std::unique_ptr<TSPicker> replica_picker,
const scoped_refptr<TableInfo>& table,
AsyncTaskThrottlerBase* async_task_throttler)
: master_(master),
callback_pool_(callback_pool),
replica_picker_(std::move(replica_picker)),
table_(table),
async_task_throttler_(async_task_throttler),
start_ts_(MonoTime::Now()),
deadline_(start_ts_ + FLAGS_unresponsive_ts_rpc_timeout_ms * 1ms) {
}
RetryingTSRpcTask::~RetryingTSRpcTask() {
auto state = state_.load(std::memory_order_acquire);
LOG_IF(DFATAL, !IsStateTerminal(state))
<< "Destroying " << this << " task in a wrong state: " << AsString(state);
VLOG_WITH_FUNC(1) << "Destroying " << this << " in " << AsString(state);
}
std::string RetryingTSRpcTask::LogPrefix() const {
return Format("$0 (task=$1, state=$2): ", description(), static_cast<const void*>(this), state());
}
std::string RetryingTSRpcTask::table_name() const {
return !table_ ? "" : table_->ToString();
}
// Send the subclass RPC request.
Status RetryingTSRpcTask::Run() {
VLOG_WITH_PREFIX(1) << "Start Running";
attempt_start_ts_ = MonoTime::Now();
++attempt_;
VLOG_WITH_PREFIX(1) << "Start Running, attempt: " << attempt_;
for (;;) {
auto task_state = state();
if (task_state == MonitoredTaskState::kAborted) {
return STATUS(IllegalState, "Unable to run task because it has been aborted");
}
if (task_state == MonitoredTaskState::kWaiting) {
break;
}
LOG_IF_WITH_PREFIX(DFATAL, task_state != MonitoredTaskState::kScheduling)
<< "Expected task to be in kScheduling state but found: " << AsString(task_state);
// We expect this case to be very rare, since we switching to waiting state right after
// scheduling task on messenger. So just busy wait.
std::this_thread::yield();
}
auto s = replica_picker_->PickReplica(&target_ts_desc_);
if (!s.ok()) {
auto opt_transition = HandleReplicaLookupFailure(s);
if (opt_transition) {
TransitionToTerminalState(
MonitoredTaskState::kWaiting, opt_transition->first, opt_transition->second);
UnregisterAsyncTask();
return opt_transition->second;
}
} else {
s = ResetTSProxy();
}
if (!s.ok()) {
s = s.CloneAndPrepend("Failed to reset TS proxy");
LOG_WITH_PREFIX(INFO) << s;
if (s.IsExpired()) {
TransitionToTerminalState(MonitoredTaskState::kWaiting, MonitoredTaskState::kFailed, s);
UnregisterAsyncTask();
return s;
}
if (RescheduleWithBackoffDelay()) {
return Status::OK();
}
auto state = this->state();
UnregisterAsyncTask(); // May delete this.
if (state == MonitoredTaskState::kFailed) {
return s;
}
if (state == MonitoredTaskState::kAborted) {
return STATUS(IllegalState, "Unable to run task because it has been aborted");
}
LOG_WITH_PREFIX(FATAL) << "Failed to change task to MonitoredTaskState::kFailed state from "
<< state;
} else {
rpc_.Reset();
}
// Calculate and set the timeout deadline.
const MonoTime deadline = ComputeDeadline();
rpc_.set_deadline(deadline);
if (!PerformStateTransition(MonitoredTaskState::kWaiting, MonitoredTaskState::kRunning)) {
if (state() == MonitoredTaskState::kAborted) {
return STATUS(Aborted, "Unable to run task because it has been aborted");
}
LOG_WITH_PREFIX(DFATAL) <<
"Task transition MonitoredTaskState::kWaiting -> MonitoredTaskState::kRunning failed";
return Failed(STATUS_FORMAT(IllegalState, "Task in invalid state $0", state()));
}
auto slowdown_flag_val = GetAtomicFlag(&FLAGS_TEST_slowdown_master_async_rpc_tasks_by_ms);
if (PREDICT_FALSE(slowdown_flag_val> 0)) {
VLOG_WITH_PREFIX(1) << "Slowing down by " << slowdown_flag_val << " ms.";
bool old_thread_restriction = ThreadRestrictions::SetWaitAllowed(true);
SleepFor(MonoDelta::FromMilliseconds(slowdown_flag_val));
ThreadRestrictions::SetWaitAllowed(old_thread_restriction);
VLOG_WITH_PREFIX(2) << "Slowing down done. Resuming.";
}
bool sent_request = false;
if (async_task_throttler_ == nullptr || !async_task_throttler_->Throttle()) {
sent_request = SendRequest(attempt_);
// If the request failed to send, remove the task that was added in
// async_task_throttler_->Throttle().
if (async_task_throttler_ != nullptr && !sent_request) {
async_task_throttler_->RemoveOutstandingTask();
}
} else {
VLOG_WITH_PREFIX(2) << "Throttled request";
}
if (!sent_request && !RescheduleWithBackoffDelay()) {
UnregisterAsyncTask(); // May call 'delete this'.
}
return Status::OK();
}
MonoTime RetryingTSRpcTask::ComputeDeadline() {
MonoTime timeout = MonoTime::Now();
timeout.AddDelta(MonoDelta::FromMilliseconds(FLAGS_master_ts_rpc_timeout_ms));
return MonoTime::Earliest(timeout, deadline_);
}
// Abort this task and return its value before it was successfully aborted. If the task entered
// a different terminal state before we were able to abort it, return that state.
MonitoredTaskState RetryingTSRpcTask::AbortAndReturnPrevState(const Status& status) {
auto prev_state = state();
while (!IsStateTerminal(prev_state)) {
auto expected = prev_state;
if (state_.compare_exchange_weak(expected, MonitoredTaskState::kAborted)) {
VLOG_WITH_PREFIX_AND_FUNC(1)
<< "Aborted with: " << status << ", prev state: " << AsString(prev_state);
AbortIfScheduled();
Finished(status);
UnregisterAsyncTask();
return prev_state;
}
prev_state = state();
}
VLOG_WITH_PREFIX_AND_FUNC(1)
<< "Already terminated, prev state: " << AsString(prev_state);
UnregisterAsyncTask();
return prev_state;
}
void RetryingTSRpcTask::AbortTask(const Status& status) {
AbortAndReturnPrevState(status);
}
void RetryingTSRpcTask::RpcCallback() {
if (async_task_throttler_ != nullptr) {
async_task_throttler_->RemoveOutstandingTask();
}
// Defer the actual work of the callback off of the reactor thread.
// This is necessary because our callbacks often do synchronous writes to
// the catalog table, and we can't do synchronous IO on the reactor.
//
// Note: This can fail on shutdown, so just print a warning for it.
Status s = callback_pool_->SubmitFunc(
std::bind(&RetryingTSRpcTask::DoRpcCallback, shared_from(this)));
VLOG_WITH_PREFIX_AND_FUNC(3) << "Submit status: " << s;
if (!s.ok()) {
WARN_NOT_OK(s, "Could not submit to queue, probably shutting down");
AbortTask(s);
}
}
// Handle the actual work of the RPC callback. This is run on the master's worker
// pool, rather than a reactor thread, so it may do blocking IO operations.
void RetryingTSRpcTask::DoRpcCallback() {
VLOG_WITH_PREFIX_AND_FUNC(3) << "Rpc status: " << rpc_.status();
if (!rpc_.status().ok()) {
LOG_WITH_PREFIX(WARNING) << "TS " << target_ts_desc_->permanent_uuid() << ": "
<< type_name() << " RPC failed for tablet "
<< tablet_id() << ": " << rpc_.status().ToString();
if (!target_ts_desc_->IsLive()) {
switch (type()) {
case MonitoredTaskType::kBackendsCatalogVersionTs:
// A similar check is done in BackendsCatalogVersionTS::HandleResponse. This check is hit
// when this RPC failed and tserver is dead. That check is hit when this RPC succeeded
// and tserver is dead.
LOG_WITH_PREFIX(WARNING)
<< "TS " << target_ts_desc_->permanent_uuid() << "is DEAD. Assume backends on that TS"
<< " will be resolved to sufficient catalog version";
TransitionToCompleteState();
break;
case MonitoredTaskType::kDeleteReplica:
LOG_WITH_PREFIX(WARNING)
<< "TS " << target_ts_desc_->permanent_uuid() << ": delete failed for tablet "
<< tablet_id() << ". TS is DEAD. No further retry.";
TransitionToCompleteState();
break;
default:
break;
}
}
} else if (state() != MonitoredTaskState::kAborted) {
HandleResponse(attempt_); // Modifies state_.
}
UpdateMetrics(master_->GetMetric(type_name(), Master::AttemptMetric, description()),
attempt_start_ts_, type_name(), "attempt metric");
// Schedule a retry if the RPC call was not successful.
if (RescheduleWithBackoffDelay()) {
return;
}
UnregisterAsyncTask(); // May call 'delete this'.
}
int RetryingTSRpcTask::num_max_retries() { return FLAGS_unresponsive_ts_rpc_retry_limit; }
int RetryingTSRpcTask::max_delay_ms() {
return FLAGS_retrying_ts_rpc_max_delay_ms;
}
bool RetryingTSRpcTask::RescheduleWithBackoffDelay() {
auto task_state = state();
if (task_state != MonitoredTaskState::kRunning &&
// Allow kWaiting for task(s) that have never successfully ResetTSProxy().
task_state != MonitoredTaskState::kWaiting) {
if (task_state != MonitoredTaskState::kComplete) {
LOG_WITH_PREFIX(INFO) << "No reschedule for this task: " << AsString(task_state);
}
return false;
}
int attempt_threshold = std::numeric_limits<int>::max();
if (NoRetryTaskType()) {
attempt_threshold = 0;
} else if (RetryLimitTaskType()) {
attempt_threshold = num_max_retries();
}
if (attempt_ > attempt_threshold) {
auto status = STATUS_FORMAT(
Aborted, "Reached maximum number of retries ($0)", attempt_threshold);
LOG_WITH_PREFIX(WARNING)
<< status << " for request " << description()
<< ", task=" << this << " state=" << state();
TransitionToFailedState(task_state, status);
return false;
}
MonoTime now = MonoTime::Now();
// We assume it might take 10ms to process the request in the best case,
// fail if we have less than that amount of time remaining.
int64_t millis_remaining = deadline_.GetDeltaSince(now).ToMilliseconds() - 10;
// Exponential backoff with jitter.
int64_t base_delay_ms;
if (attempt_ <= 12) {
// 1st retry delayed 2^4 ms, 2nd 2^5, etc.
base_delay_ms = std::min(1 << (attempt_ + 3), max_delay_ms());
} else {
base_delay_ms = max_delay_ms();
}
// Normal rand is seeded by default with 1. Using the same for rand_r seed.
unsigned int seed = 1;
int64_t jitter_ms = rand_r(&seed) % 50; // Add up to 50ms of additional random delay.
int64_t delay_millis = std::min<int64_t>(base_delay_ms + jitter_ms, millis_remaining);
if (delay_millis <= 0) {
auto status = STATUS(TimedOut, "Request timed out");
LOG_WITH_PREFIX(WARNING) << status;
TransitionToFailedState(task_state, status);
return false;
}
LOG_WITH_PREFIX(INFO) << "Scheduling retry with a delay of " << delay_millis
<< "ms (attempt = " << attempt_ << " / " << attempt_threshold << ")...";
if (!PerformStateTransition(task_state, MonitoredTaskState::kScheduling)) {
LOG_WITH_PREFIX(WARNING) << "Unable to mark this task as MonitoredTaskState::kScheduling";
return false;
}
auto task_id_result = master_->messenger()->ScheduleOnReactor(
std::bind(&RetryingTSRpcTask::RunDelayedTask, shared_from(this), _1),
MonoDelta::FromMilliseconds(delay_millis), SOURCE_LOCATION());
if (!task_id_result.ok()) {
AbortTask(task_id_result.status());
UnregisterAsyncTask();
return false;
}
auto task_id = *task_id_result;
VLOG_WITH_PREFIX_AND_FUNC(4) << "Task id: " << task_id;
reactor_task_id_.store(task_id, std::memory_order_release);
return TransitionToWaitingState(MonitoredTaskState::kScheduling);
}
void RetryingTSRpcTask::RunDelayedTask(const Status& status) {
if (state() == MonitoredTaskState::kAborted) {
UnregisterAsyncTask(); // May delete this.
return;
}
if (!status.ok()) {
LOG_WITH_PREFIX(WARNING) << "Async tablet task failed or was cancelled: " << status;
if (status.IsAborted() || status.IsServiceUnavailable()) {
AbortTask(status);
}
UnregisterAsyncTask(); // May delete this.
return;
}
auto log_prefix = LogPrefix(); // Save in case we need to log after deletion.
Status s = Run(); // May delete this.
if (!s.ok()) {
LOG(WARNING) << log_prefix << "Async tablet task failed: " << s;
}
}
void RetryingTSRpcTask::UnregisterAsyncTaskCallback() {}
Status RetryingTSRpcTask::Failed(const Status& status) {
LOG_WITH_PREFIX(WARNING) << "Async task failed: " << status;
Finished(status);
UnregisterAsyncTask();
return status;
}
void RetryingTSRpcTask::UnregisterAsyncTask() {
// Retain a reference to the object, in case RemoveTask would have removed the last one.
auto self = shared_from_this();
std::unique_lock<decltype(unregister_mutex_)> lock(unregister_mutex_);
UpdateMetrics(master_->GetMetric(type_name(), Master::TaskMetric, description()), start_ts_,
type_name(), "task metric");
auto s = state();
if (!IsStateTerminal(s)) {
LOG_WITH_PREFIX(FATAL) << "Invalid task state " << s;
}
end_ts_ = MonoTime::Now();
if (table_ != nullptr && table_->RemoveTask(self)) {
// We don't delete table while it have running tasks, so should check whether it was last task,
// even it is not delete table task.
master_->catalog_manager()->CheckTableDeleted(table_);
}
// Make sure to run the callbacks last, in case they rely on the task no longer being tracked
// by the table.
UnregisterAsyncTaskCallback();
}
void RetryingTSRpcTask::AbortIfScheduled() {
auto reactor_task_id = reactor_task_id_.load(std::memory_order_acquire);
VLOG_WITH_PREFIX_AND_FUNC(1) << "Reactor task id: " << reactor_task_id;
if (reactor_task_id != rpc::kInvalidTaskId) {
master_->messenger()->AbortOnReactor(reactor_task_id);
}
}
Status RetryingTSRpcTask::ResetTSProxy() {
shared_ptr<tserver::TabletServerServiceProxy> ts_proxy;
shared_ptr<tserver::TabletServerAdminServiceProxy> ts_admin_proxy;
shared_ptr<consensus::ConsensusServiceProxy> consensus_proxy;
shared_ptr<tserver::TabletServerBackupServiceProxy> ts_backup_proxy;
RETURN_NOT_OK(target_ts_desc_->GetProxy(&ts_proxy));
RETURN_NOT_OK(target_ts_desc_->GetProxy(&ts_admin_proxy));
RETURN_NOT_OK(target_ts_desc_->GetProxy(&consensus_proxy));
RETURN_NOT_OK(target_ts_desc_->GetProxy(&ts_backup_proxy));
ts_proxy_.swap(ts_proxy);
ts_admin_proxy_.swap(ts_admin_proxy);
consensus_proxy_.swap(consensus_proxy);
ts_backup_proxy_.swap(ts_backup_proxy);
return Status::OK();
}
void RetryingTSRpcTask::TransitionToTerminalState(MonitoredTaskState expected,
MonitoredTaskState terminal_state,
const Status& status) {
if (!PerformStateTransition(expected, terminal_state)) {
if (terminal_state != MonitoredTaskState::kAborted && state() == MonitoredTaskState::kAborted) {
LOG_WITH_PREFIX(WARNING) << "Unable to perform transition " << expected << " -> "
<< terminal_state << ". Task has been aborted";
} else {
LOG_WITH_PREFIX(DFATAL) << "State transition " << expected << " -> "
<< terminal_state << " failed. Current task is in an invalid state: "
<< state();
}
return;
}
Finished(status);
}
void RetryingTSRpcTask::TransitionToFailedState(server::MonitoredTaskState expected,
const yb::Status& status) {
TransitionToTerminalState(expected, MonitoredTaskState::kFailed, status);
}
void RetryingTSRpcTask::TransitionToCompleteState() {
TransitionToTerminalState(
MonitoredTaskState::kRunning, MonitoredTaskState::kComplete, Status::OK());
}
bool RetryingTSRpcTask::TransitionToWaitingState(MonitoredTaskState expected) {
if (!PerformStateTransition(expected, MonitoredTaskState::kWaiting)) {
// The only valid reason for state not being MonitoredTaskState is because the task got
// aborted.
if (state() != MonitoredTaskState::kAborted) {
LOG_WITH_PREFIX(FATAL) << "Unable to mark task as MonitoredTaskState::kWaiting";
}
AbortIfScheduled();
return false;
} else {
return true;
}
}
// ============================================================================
// Class AsyncTabletLeaderTask.
// ============================================================================
AsyncTabletLeaderTask::AsyncTabletLeaderTask(
Master* master, ThreadPool* callback_pool, const scoped_refptr<TabletInfo>& tablet)
: RetryingTSRpcTask(
master, callback_pool, std::unique_ptr<TSPicker>(new PickLeaderReplica(tablet)),
tablet->table().get(), /* async_task_throttler */ nullptr),
tablet_(tablet) {
}
AsyncTabletLeaderTask::AsyncTabletLeaderTask(
Master* master, ThreadPool* callback_pool, const scoped_refptr<TabletInfo>& tablet,
const scoped_refptr<TableInfo>& table)
: RetryingTSRpcTask(
master, callback_pool, std::unique_ptr<TSPicker>(new PickLeaderReplica(tablet)), table,
/* async_task_throttler */ nullptr),
tablet_(tablet) {
}
AsyncTabletLeaderTask::~AsyncTabletLeaderTask() = default;
std::string AsyncTabletLeaderTask::description() const {
return Format("$0 RPC for tablet $1 ($2)", type_name(), tablet_, table_name());
}
TabletId AsyncTabletLeaderTask::tablet_id() const {
return tablet_->tablet_id();
}
TabletServerId AsyncTabletLeaderTask::permanent_uuid() const {
return target_ts_desc_ != nullptr ? target_ts_desc_->permanent_uuid() : "";
}
// ============================================================================
// Class AsyncCreateReplica.
// ============================================================================
AsyncCreateReplica::AsyncCreateReplica(Master *master,
ThreadPool *callback_pool,
const string& permanent_uuid,
const scoped_refptr<TabletInfo>& tablet,
const std::vector<SnapshotScheduleId>& snapshot_schedules)
: RetrySpecificTSRpcTask(master, callback_pool, permanent_uuid, tablet->table().get(),
/* async_task_throttler */ nullptr),
tablet_id_(tablet->tablet_id()) {
deadline_ = start_ts_;
deadline_.AddDelta(MonoDelta::FromMilliseconds(FLAGS_tablet_creation_timeout_ms));
auto table_lock = tablet->table()->LockForRead();
const SysTabletsEntryPB& tablet_pb = tablet->metadata().dirty().pb;
req_.set_dest_uuid(permanent_uuid);
req_.set_table_id(tablet->table()->id());
req_.set_tablet_id(tablet->tablet_id());
req_.set_table_type(tablet->table()->metadata().state().pb.table_type());
req_.mutable_partition()->CopyFrom(tablet_pb.partition());
req_.set_namespace_id(table_lock->pb.namespace_id());
req_.set_namespace_name(table_lock->pb.namespace_name());
req_.set_table_name(table_lock->pb.name());
req_.mutable_schema()->CopyFrom(table_lock->pb.schema());
req_.mutable_partition_schema()->CopyFrom(table_lock->pb.partition_schema());
req_.mutable_config()->CopyFrom(tablet_pb.committed_consensus_state().config());
req_.set_colocated(tablet_pb.colocated());
if (table_lock->pb.has_index_info()) {
req_.mutable_index_info()->CopyFrom(table_lock->pb.index_info());
}
auto& req_schedules = *req_.mutable_snapshot_schedules();
req_schedules.Reserve(narrow_cast<int>(snapshot_schedules.size()));
for (const auto& id : snapshot_schedules) {
req_schedules.Add()->assign(id.AsSlice().cdata(), id.size());
}
req_.mutable_hosted_stateful_services()->CopyFrom(table_lock->pb.hosted_stateful_services());
}
std::string AsyncCreateReplica::description() const {
return Format("CreateTablet RPC for tablet $0 ($1) on TS=$2",
tablet_id_, table_name(), permanent_uuid_);
}
void AsyncCreateReplica::HandleResponse(int attempt) {
if (resp_.has_error()) {
Status s = StatusFromPB(resp_.error().status());
if (s.IsAlreadyPresent()) {
LOG_WITH_PREFIX(INFO) << "CreateTablet RPC for tablet " << tablet_id_
<< " on TS " << permanent_uuid_ << " returned already present: "
<< s;
TransitionToCompleteState();
} else {
LOG_WITH_PREFIX(WARNING) << "CreateTablet RPC for tablet " << tablet_id_
<< " on TS " << permanent_uuid_ << " failed: " << s;
}
return;
}
TransitionToCompleteState();
VLOG_WITH_PREFIX(1) << "TS " << permanent_uuid_ << ": complete on tablet " << tablet_id_;
}
bool AsyncCreateReplica::SendRequest(int attempt) {
ts_admin_proxy_->CreateTabletAsync(req_, &resp_, &rpc_, BindRpcCallback());
VLOG_WITH_PREFIX(1) << "Send create tablet request to " << permanent_uuid_ << ":\n"
<< " (attempt " << attempt << "):\n"
<< req_.DebugString();
return true;
}
// ============================================================================
// Class AsyncStartElection.
// ============================================================================
AsyncStartElection::AsyncStartElection(Master *master,
ThreadPool *callback_pool,
const string& permanent_uuid,
const scoped_refptr<TabletInfo>& tablet,
bool initial_election)
: RetrySpecificTSRpcTask(master, callback_pool, permanent_uuid, tablet->table().get(),
/* async_task_throttler */ nullptr),
tablet_id_(tablet->tablet_id()) {
deadline_ = start_ts_;
deadline_.AddDelta(MonoDelta::FromMilliseconds(FLAGS_tablet_creation_timeout_ms));
req_.set_dest_uuid(permanent_uuid_);
req_.set_tablet_id(tablet_id_);
req_.set_initial_election(initial_election);
}
void AsyncStartElection::HandleResponse(int attempt) {
if (resp_.has_error()) {
Status s = StatusFromPB(resp_.error().status());
if (!s.ok()) {
LOG_WITH_PREFIX(WARNING) << "RunLeaderElection RPC for tablet " << tablet_id_
<< " on TS " << permanent_uuid_ << " failed: " << s;
}
return;
}
TransitionToCompleteState();
}
std::string AsyncStartElection::description() const {
return Format("RunLeaderElection RPC for tablet $0 ($1) on TS=$2",
tablet_id_, table_name(), permanent_uuid_);
}
bool AsyncStartElection::SendRequest(int attempt) {
LOG_WITH_PREFIX(INFO) << Format(
"Hinted Leader start election at $0 for tablet $1, attempt $2",
permanent_uuid_, tablet_id_, attempt);
consensus_proxy_->RunLeaderElectionAsync(req_, &resp_, &rpc_, BindRpcCallback());
return true;
}
// ============================================================================
// Class AsyncPrepareDeleteTransactionTablet.
// ============================================================================
AsyncPrepareDeleteTransactionTablet::AsyncPrepareDeleteTransactionTablet(
Master* master, ThreadPool* callback_pool, const std::string& permanent_uuid,
const scoped_refptr<TableInfo>& table, const scoped_refptr<TabletInfo>& tablet,
const std::string& msg, HideOnly hide_only)
: RetrySpecificTSRpcTask(master, callback_pool, permanent_uuid, table,
/* async_task_throttler */ nullptr),
tablet_(tablet), msg_(msg), hide_only_(hide_only) {}
void AsyncPrepareDeleteTransactionTablet::HandleResponse(int attempt) {
if (resp_.has_error()) {
Status status = StatusFromPB(resp_.error().status());
// Do not retry on a fatal error
TabletServerErrorPB::Code code = resp_.error().code();
switch (code) {
case TabletServerErrorPB::TABLET_NOT_FOUND:
LOG_WITH_PREFIX(WARNING)
<< "TS " << permanent_uuid_ << ": prepare delete failed for tablet "
<< tablet_id() << " because the tablet was not found. No further retry: "
<< status.ToString();
TransitionToCompleteState();
break;
case TabletServerErrorPB::WRONG_SERVER_UUID:
LOG_WITH_PREFIX(WARNING)
<< "TS " << permanent_uuid_ << ": prepare delete failed for tablet "
<< tablet_id() << " due to an incorrect UUID. No further retry: "
<< status.ToString();
TransitionToCompleteState();
break;
default:
LOG_WITH_PREFIX(WARNING)
<< "TS " << permanent_uuid_ << ": prepare delete failed for tablet "
<< tablet_id() << " with error code " << TabletServerErrorPB::Code_Name(code)
<< ": " << status.ToString();
break;
}
} else {
if (table_) {
LOG_WITH_PREFIX(INFO)
<< "TS " << permanent_uuid_ << ": tablet " << tablet_id()
<< " (table " << table_->ToString() << ") successfully done";
} else {
LOG_WITH_PREFIX(WARNING)
<< "TS " << permanent_uuid_ << ": tablet " << tablet_id()
<< " did not belong to a known table, but was prepared for deletion";
}
TransitionToCompleteState();
VLOG_WITH_PREFIX(1) << "TS " << permanent_uuid_ << ": complete on tablet " << tablet_id();
}
}
std::string AsyncPrepareDeleteTransactionTablet::description() const {
return Format("PrepareDeleteTransactionTablet RPC for tablet $0 ($1) on TS=$2",
tablet_id(), table_name(), permanent_uuid_);
}
TabletId AsyncPrepareDeleteTransactionTablet::tablet_id() const {
return tablet_->tablet_id();
}
bool AsyncPrepareDeleteTransactionTablet::SendRequest(int attempt) {
tserver::PrepareDeleteTransactionTabletRequestPB req;
req.set_dest_uuid(permanent_uuid_);
req.set_tablet_id(tablet_id());
ts_admin_proxy_->PrepareDeleteTransactionTabletAsync(req, &resp_, &rpc_, BindRpcCallback());
VLOG_WITH_PREFIX(1) << "Send prepare delete transaction tablet request for "
<< tablet_id() << " to " << permanent_uuid_
<< " (attempt " << attempt << "):\n"
<< req.DebugString();
return true;
}
void AsyncPrepareDeleteTransactionTablet::UnregisterAsyncTaskCallback() {
// Only notify if we are in a success state.
if (state() == MonitoredTaskState::kComplete) {
master_->catalog_manager()->NotifyPrepareDeleteTransactionTabletFinished(
tablet_, msg_, hide_only_);
}
}
// ============================================================================
// Class AsyncDeleteReplica.
// ============================================================================
void AsyncDeleteReplica::HandleResponse(int attempt) {
if (resp_.has_error()) {
Status status = StatusFromPB(resp_.error().status());
// Do not retry on a fatal error
TabletServerErrorPB::Code code = resp_.error().code();
switch (code) {
case TabletServerErrorPB::TABLET_NOT_FOUND:
LOG_WITH_PREFIX(WARNING)
<< "TS " << permanent_uuid_ << ": delete failed for tablet " << tablet_id_
<< " because the tablet was not found. No further retry: "
<< status.ToString();
TransitionToCompleteState();
break;
case TabletServerErrorPB::CAS_FAILED:
LOG_WITH_PREFIX(WARNING)
<< "TS " << permanent_uuid_ << ": delete failed for tablet " << tablet_id_
<< " due to a CAS failure. No further retry: " << status.ToString();
TransitionToCompleteState();
break;
case TabletServerErrorPB::WRONG_SERVER_UUID:
LOG_WITH_PREFIX(WARNING)
<< "TS " << permanent_uuid_ << ": delete failed for tablet " << tablet_id_
<< " due to an incorrect UUID. No further retry: " << status.ToString();
TransitionToCompleteState();
break;
default:
LOG_WITH_PREFIX(WARNING)
<< "TS " << permanent_uuid_ << ": delete failed for tablet " << tablet_id_
<< " with error code " << TabletServerErrorPB::Code_Name(code)
<< ": " << status.ToString();
break;
}
} else {
if (table_) {
LOG_WITH_PREFIX(INFO)
<< "TS " << permanent_uuid_ << ": tablet " << tablet_id_
<< " (table " << table_->ToString() << ") successfully done";
} else {
LOG_WITH_PREFIX(WARNING)
<< "TS " << permanent_uuid_ << ": tablet " << tablet_id_
<< " did not belong to a known table, but was successfully deleted";
}
TransitionToCompleteState();
VLOG_WITH_PREFIX(1) << "TS " << permanent_uuid_ << ": complete on tablet " << tablet_id_;
}
}
std::string AsyncDeleteReplica::description() const {
return Format("$0Tablet RPC for tablet $1 ($2) on TS=$3",
hide_only_ ? "Hide" : "Delete", tablet_id_, table_name(), permanent_uuid_);
}
bool AsyncDeleteReplica::SendRequest(int attempt) {
tserver::DeleteTabletRequestPB req;
req.set_dest_uuid(permanent_uuid_);
req.set_tablet_id(tablet_id_);
req.set_reason(reason_);
req.set_delete_type(delete_type_);
if (hide_only_) {
req.set_hide_only(hide_only_);
}
if (keep_data_) {
req.set_keep_data(keep_data_);
}
if (cas_config_opid_index_less_or_equal_) {
req.set_cas_config_opid_index_less_or_equal(*cas_config_opid_index_less_or_equal_);
}
bool should_abort_active_txns = !table() ||
table()->LockForRead()->started_deleting();
req.set_should_abort_active_txns(should_abort_active_txns);
ts_admin_proxy_->DeleteTabletAsync(req, &resp_, &rpc_, BindRpcCallback());
VLOG_WITH_PREFIX(1) << "Send delete tablet request to " << permanent_uuid_
<< " (attempt " << attempt << "):\n"
<< req.DebugString();
return true;
}
void AsyncDeleteReplica::UnregisterAsyncTaskCallback() {
// Only notify if we are in a success state.
if (state() == MonitoredTaskState::kComplete) {
master_->catalog_manager()->NotifyTabletDeleteFinished(permanent_uuid_, tablet_id_, table());
}
}
// ============================================================================
// Class AsyncAlterTable.
// ============================================================================
void AsyncAlterTable::HandleResponse(int attempt) {
if (PREDICT_FALSE(FLAGS_TEST_slowdown_alter_table_rpcs_ms > 0)) {
VLOG_WITH_PREFIX(1) << "Sleeping for " << tablet_->tablet_id()
<< FLAGS_TEST_slowdown_alter_table_rpcs_ms
<< "ms before returning response in async alter table request handler";
SleepFor(MonoDelta::FromMilliseconds(FLAGS_TEST_slowdown_alter_table_rpcs_ms));
}
if (resp_.has_error()) {
Status status = StatusFromPB(resp_.error().status());
LOG_WITH_PREFIX(WARNING) << "TS " << permanent_uuid() << " failed: "
<< status << " for version " << schema_version_;
// Do not retry on a fatal error
switch (resp_.error().code()) {
case TabletServerErrorPB::TABLET_NOT_FOUND:
case TabletServerErrorPB::MISMATCHED_SCHEMA:
case TabletServerErrorPB::TABLET_HAS_A_NEWER_SCHEMA:
TransitionToCompleteState();
break;
default:
break;
}
} else {
TransitionToCompleteState();
VLOG_WITH_PREFIX(1)
<< "TS " << permanent_uuid() << " completed: for version " << schema_version_;
}
server::UpdateClock(resp_, master_->clock());
if (state() == MonitoredTaskState::kComplete) {
// TODO: proper error handling here. Not critical, since TSHeartbeat will retry on failure.
WARN_NOT_OK(
master_->catalog_manager()->HandleTabletSchemaVersionReport(
tablet_.get(), schema_version_, table()),
Format(
"$0 failed while running AsyncAlterTable::HandleResponse. Response $1",
description(), resp_.ShortDebugString()));
} else {
VLOG_WITH_PREFIX(1) << "Task is not completed " << tablet_->ToString() << " for version "
<< schema_version_;
}
}
TableType AsyncAlterTable::table_type() const {
return tablet_->table()->GetTableType();
}
bool AsyncAlterTable::SendRequest(int attempt) {
VLOG_WITH_PREFIX(1) << "Send alter table request to " << permanent_uuid() << " for "
<< tablet_->tablet_id() << " waiting for a read lock.";
tablet::ChangeMetadataRequestPB req;
{
auto l = table_->LockForRead();
VLOG_WITH_PREFIX(1) << "Send alter table request to " << permanent_uuid() << " for "
<< tablet_->tablet_id() << " obtained the read lock.";
req.set_schema_version(l->pb.version());
req.set_dest_uuid(permanent_uuid());
req.set_tablet_id(tablet_->tablet_id());
req.set_alter_table_id(table_->id());
if (l->pb.has_wal_retention_secs()) {
req.set_wal_retention_secs(l->pb.wal_retention_secs());
}
req.mutable_schema()->CopyFrom(l->pb.schema());
req.set_new_table_name(l->pb.name());
req.mutable_indexes()->CopyFrom(l->pb.indexes());
req.set_propagated_hybrid_time(master_->clock()->Now().ToUint64());
if (table_type() == TableType::PGSQL_TABLE_TYPE && !transaction_id_.IsNil()) {
VLOG_WITH_PREFIX(1) << "Transaction ID is provided for tablet " << tablet_->tablet_id()
<< " with ID " << transaction_id_.ToString() << " for ALTER TABLE operation";
req.set_should_abort_active_txns(true);
req.set_transaction_id(transaction_id_.ToString());
}
schema_version_ = l->pb.version();
}
ts_admin_proxy_->AlterSchemaAsync(req, &resp_, &rpc_, BindRpcCallback());
VLOG_WITH_PREFIX(1)
<< "Send alter table request to " << permanent_uuid() << " for " << tablet_->tablet_id()
<< " (attempt " << attempt << "):\n" << req.DebugString();
return true;
}
bool AsyncBackfillDone::SendRequest(int attempt) {
VLOG_WITH_PREFIX(1)
<< "Send alter table request to " << permanent_uuid() << " for " << tablet_->tablet_id()
<< " version " << schema_version_ << " waiting for a read lock.";
tablet::ChangeMetadataRequestPB req;
{