-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathpd.rs
More file actions
2488 lines (2297 loc) · 89.4 KB
/
pd.rs
File metadata and controls
2488 lines (2297 loc) · 89.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use std::{
cmp,
cmp::Ordering as CmpOrdering,
fmt::{self, Display, Formatter},
io, mem,
sync::{
atomic::Ordering,
mpsc::{self, Receiver, Sender},
Arc,
},
thread::{Builder, JoinHandle},
time::{Duration, Instant},
};
use collections::{HashMap, HashSet};
use concurrency_manager::ConcurrencyManager;
use engine_traits::{KvEngine, RaftEngine};
#[cfg(feature = "failpoints")]
use fail::fail_point;
use futures::{compat::Future01CompatExt, FutureExt};
use grpcio_health::{HealthService, ServingStatus};
use kvproto::{
kvrpcpb::DiskFullOpt,
metapb, pdpb,
raft_cmdpb::{
AdminCmdType, AdminRequest, ChangePeerRequest, ChangePeerV2Request, RaftCmdRequest,
SplitRequest,
},
raft_serverpb::RaftMessage,
replication_modepb::{RegionReplicationStatus, StoreDrAutoSyncStatus},
};
use ordered_float::OrderedFloat;
use pd_client::{merge_bucket_stats, metrics::*, BucketStat, Error, PdClient, RegionStat};
use prometheus::local::LocalHistogram;
use raft::eraftpb::ConfChangeType;
use resource_metering::{Collector, CollectorGuard, CollectorRegHandle, RawRecords};
use tikv_util::{
box_err, debug, error, info,
metrics::ThreadInfoStatistics,
thd_name,
time::{Instant as TiInstant, UnixSecs},
timer::GLOBAL_TIMER_HANDLE,
topn::TopN,
warn,
worker::{Runnable, RunnableWithTimer, ScheduleError, Scheduler},
};
use yatp::Remote;
use crate::store::{
cmd_resp::new_error,
metrics::*,
peer::{UnsafeRecoveryExecutePlanSyncer, UnsafeRecoveryForceLeaderSyncer},
transport::SignificantRouter,
util::{is_epoch_stale, KeysInfoFormatter, LatencyInspector, RaftstoreDuration},
worker::{
query_stats::QueryStats,
split_controller::{SplitInfo, TOP_N},
AutoSplitController, ReadStats, WriteStats,
},
Callback, CasualMessage, Config, PeerMsg, RaftCmdExtraOpts, RaftCommand, RaftRouter,
RegionReadProgressRegistry, SignificantMsg, SnapManager, StoreInfo, StoreMsg, TxnExt,
};
type RecordPairVec = Vec<pdpb::RecordPair>;
#[derive(Default, Debug, Clone)]
pub struct FlowStatistics {
pub read_keys: usize,
pub read_bytes: usize,
}
impl FlowStatistics {
pub fn add(&mut self, other: &Self) {
self.read_bytes = self.read_bytes.saturating_add(other.read_bytes);
self.read_keys = self.read_keys.saturating_add(other.read_keys);
}
}
// Reports flow statistics to outside.
pub trait FlowStatsReporter: Send + Clone + Sync + 'static {
// TODO: maybe we need to return a Result later?
fn report_read_stats(&self, read_stats: ReadStats);
fn report_write_stats(&self, write_stats: WriteStats);
}
impl<EK, ER> FlowStatsReporter for Scheduler<Task<EK, ER>>
where
EK: KvEngine,
ER: RaftEngine,
{
fn report_read_stats(&self, read_stats: ReadStats) {
if let Err(e) = self.schedule(Task::ReadStats { read_stats }) {
error!("Failed to send read flow statistics"; "err" => ?e);
}
}
fn report_write_stats(&self, write_stats: WriteStats) {
if let Err(e) = self.schedule(Task::WriteStats { write_stats }) {
error!("Failed to send write flow statistics"; "err" => ?e);
}
}
}
pub struct HeartbeatTask {
pub term: u64,
pub region: metapb::Region,
pub peer: metapb::Peer,
pub down_peers: Vec<pdpb::PeerStats>,
pub pending_peers: Vec<metapb::Peer>,
pub written_bytes: u64,
pub written_keys: u64,
pub approximate_size: Option<u64>,
pub approximate_keys: Option<u64>,
pub replication_status: Option<RegionReplicationStatus>,
}
/// Uses an asynchronous thread to tell PD something.
pub enum Task<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
AskSplit {
region: metapb::Region,
split_key: Vec<u8>,
peer: metapb::Peer,
// If true, right Region derives origin region_id.
right_derive: bool,
callback: Callback<EK::Snapshot>,
},
AskBatchSplit {
region: metapb::Region,
split_keys: Vec<Vec<u8>>,
peer: metapb::Peer,
// If true, right Region derives origin region_id.
right_derive: bool,
callback: Callback<EK::Snapshot>,
},
AutoSplit {
split_infos: Vec<SplitInfo>,
},
Heartbeat(HeartbeatTask),
StoreHeartbeat {
stats: pdpb::StoreStats,
store_info: StoreInfo<EK, ER>,
report: Option<pdpb::StoreReport>,
dr_autosync_status: Option<StoreDrAutoSyncStatus>,
},
ReportBatchSplit {
regions: Vec<metapb::Region>,
},
ValidatePeer {
region: metapb::Region,
peer: metapb::Peer,
},
ReadStats {
read_stats: ReadStats,
},
WriteStats {
write_stats: WriteStats,
},
DestroyPeer {
region_id: u64,
},
StoreInfos {
cpu_usages: RecordPairVec,
read_io_rates: RecordPairVec,
write_io_rates: RecordPairVec,
},
UpdateMaxTimestamp {
region_id: u64,
initial_status: u64,
txn_ext: Arc<TxnExt>,
},
QueryRegionLeader {
region_id: u64,
},
UpdateSlowScore {
id: u64,
duration: RaftstoreDuration,
},
RegionCPURecords(Arc<RawRecords>),
ReportMinResolvedTS {
store_id: u64,
min_resolved_ts: u64,
},
ReportBuckets(BucketStat),
}
pub struct StoreStat {
pub engine_total_bytes_read: u64,
pub engine_total_keys_read: u64,
pub engine_total_query_num: QueryStats,
pub engine_last_total_bytes_read: u64,
pub engine_last_total_keys_read: u64,
pub engine_last_query_num: QueryStats,
pub last_report_ts: UnixSecs,
pub region_bytes_read: LocalHistogram,
pub region_keys_read: LocalHistogram,
pub region_bytes_written: LocalHistogram,
pub region_keys_written: LocalHistogram,
pub store_cpu_usages: RecordPairVec,
pub store_read_io_rates: RecordPairVec,
pub store_write_io_rates: RecordPairVec,
}
impl Default for StoreStat {
fn default() -> StoreStat {
StoreStat {
region_bytes_read: REGION_READ_BYTES_HISTOGRAM.local(),
region_keys_read: REGION_READ_KEYS_HISTOGRAM.local(),
region_bytes_written: REGION_WRITTEN_BYTES_HISTOGRAM.local(),
region_keys_written: REGION_WRITTEN_KEYS_HISTOGRAM.local(),
last_report_ts: UnixSecs::zero(),
engine_total_bytes_read: 0,
engine_total_keys_read: 0,
engine_last_total_bytes_read: 0,
engine_last_total_keys_read: 0,
engine_total_query_num: QueryStats::default(),
engine_last_query_num: QueryStats::default(),
store_cpu_usages: RecordPairVec::default(),
store_read_io_rates: RecordPairVec::default(),
store_write_io_rates: RecordPairVec::default(),
}
}
}
#[derive(Default)]
pub struct PeerStat {
pub read_bytes: u64,
pub read_keys: u64,
pub query_stats: QueryStats,
// last_region_report_attributes records the state of the last region heartbeat
pub last_region_report_read_bytes: u64,
pub last_region_report_read_keys: u64,
pub last_region_report_query_stats: QueryStats,
pub last_region_report_written_bytes: u64,
pub last_region_report_written_keys: u64,
pub last_region_report_ts: UnixSecs,
// last_store_report_attributes records the state of the last store heartbeat
pub last_store_report_read_bytes: u64,
pub last_store_report_read_keys: u64,
pub last_store_report_query_stats: QueryStats,
pub approximate_keys: u64,
pub approximate_size: u64,
}
#[derive(Default)]
pub struct ReportBucket {
current_stat: BucketStat,
last_report_stat: Option<BucketStat>,
last_report_ts: UnixSecs,
}
impl ReportBucket {
fn new(current_stat: BucketStat) -> Self {
Self {
current_stat,
..Default::default()
}
}
fn new_report(&mut self, report_ts: UnixSecs) -> BucketStat {
self.last_report_ts = report_ts;
match self.last_report_stat.replace(self.current_stat.clone()) {
Some(last) => {
let mut delta = BucketStat::new(
self.current_stat.meta.clone(),
pd_client::new_bucket_stats(&self.current_stat.meta),
);
// Buckets may be changed, recalculate last stats according to current meta.
merge_bucket_stats(
&delta.meta.keys,
&mut delta.stats,
&last.meta.keys,
&last.stats,
);
for i in 0..delta.meta.keys.len() - 1 {
delta.stats.write_bytes[i] =
self.current_stat.stats.write_bytes[i] - delta.stats.write_bytes[i];
delta.stats.write_keys[i] =
self.current_stat.stats.write_keys[i] - delta.stats.write_keys[i];
delta.stats.write_qps[i] =
self.current_stat.stats.write_qps[i] - delta.stats.write_qps[i];
delta.stats.read_bytes[i] =
self.current_stat.stats.read_bytes[i] - delta.stats.read_bytes[i];
delta.stats.read_keys[i] =
self.current_stat.stats.read_keys[i] - delta.stats.read_keys[i];
delta.stats.read_qps[i] =
self.current_stat.stats.read_qps[i] - delta.stats.read_qps[i];
}
delta
}
None => self.current_stat.clone(),
}
}
}
#[derive(Default, Clone)]
struct PeerCmpReadStat {
pub region_id: u64,
pub report_stat: u64,
}
impl Ord for PeerCmpReadStat {
fn cmp(&self, other: &Self) -> CmpOrdering {
self.report_stat.cmp(&other.report_stat)
}
}
impl Eq for PeerCmpReadStat {}
impl PartialEq for PeerCmpReadStat {
fn eq(&self, other: &Self) -> bool {
self.report_stat == other.report_stat
}
}
impl PartialOrd for PeerCmpReadStat {
fn partial_cmp(&self, other: &Self) -> Option<CmpOrdering> {
Some(self.report_stat.cmp(&other.report_stat))
}
}
impl<EK, ER> Display for Task<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match *self {
Task::AskSplit {
ref region,
ref split_key,
..
} => write!(
f,
"ask split region {} with key {}",
region.get_id(),
log_wrappers::Value::key(split_key),
),
Task::AutoSplit { ref split_infos } => {
write!(f, "auto split split regions, num is {}", split_infos.len(),)
}
Task::AskBatchSplit {
ref region,
ref split_keys,
..
} => write!(
f,
"ask split region {} with {}",
region.get_id(),
KeysInfoFormatter(split_keys.iter())
),
Task::Heartbeat(ref hb_task) => write!(
f,
"heartbeat for region {:?}, leader {}, replication status {:?}",
hb_task.region,
hb_task.peer.get_id(),
hb_task.replication_status
),
Task::StoreHeartbeat { ref stats, .. } => {
write!(f, "store heartbeat stats: {:?}", stats)
}
Task::ReportBatchSplit { ref regions } => write!(f, "report split {:?}", regions),
Task::ValidatePeer {
ref region,
ref peer,
} => write!(f, "validate peer {:?} with region {:?}", peer, region),
Task::ReadStats { ref read_stats } => {
write!(f, "get the read statistics {:?}", read_stats)
}
Task::WriteStats { ref write_stats } => {
write!(f, "get the write statistics {:?}", write_stats)
}
Task::DestroyPeer { ref region_id } => {
write!(f, "destroy peer of region {}", region_id)
}
Task::StoreInfos {
ref cpu_usages,
ref read_io_rates,
ref write_io_rates,
} => write!(
f,
"get store's information: cpu_usages {:?}, read_io_rates {:?}, write_io_rates {:?}",
cpu_usages, read_io_rates, write_io_rates,
),
Task::UpdateMaxTimestamp { region_id, .. } => write!(
f,
"update the max timestamp for region {} in the concurrency manager",
region_id
),
Task::QueryRegionLeader { region_id } => {
write!(f, "query the leader of region {}", region_id)
}
Task::UpdateSlowScore { id, ref duration } => {
write!(f, "compute slow score: id {}, duration {:?}", id, duration)
}
Task::RegionCPURecords(ref cpu_records) => {
write!(f, "get region cpu records: {:?}", cpu_records)
}
Task::ReportMinResolvedTS {
store_id,
min_resolved_ts,
} => {
write!(
f,
"report min resolved ts: store {}, resolved ts {}",
store_id, min_resolved_ts
)
}
Task::ReportBuckets(ref buckets) => {
write!(f, "report buckets: {:?}", buckets)
}
}
}
}
const DEFAULT_LOAD_BASE_SPLIT_CHECK_INTERVAL: Duration = Duration::from_secs(1);
const DEFAULT_COLLECT_TICK_INTERVAL: Duration = Duration::from_secs(1);
fn default_collect_tick_interval() -> Duration {
#[cfg(feature = "failpoints")]
fail_point!("mock_collect_tick_interval", |_| {
Duration::from_millis(1)
});
DEFAULT_COLLECT_TICK_INTERVAL
}
fn config(interval: Duration) -> Duration {
#[cfg(feature = "failpoints")]
fail_point!("mock_min_resolved_ts_interval", |_| {
Duration::from_millis(50)
});
interval
}
#[inline]
fn convert_record_pairs(m: HashMap<String, u64>) -> RecordPairVec {
m.into_iter()
.map(|(k, v)| {
let mut pair = pdpb::RecordPair::default();
pair.set_key(k);
pair.set_value(v);
pair
})
.collect()
}
struct StatsMonitor<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
scheduler: Scheduler<Task<EK, ER>>,
handle: Option<JoinHandle<()>>,
timer: Option<Sender<bool>>,
read_stats_sender: Option<Sender<ReadStats>>,
collect_store_infos_interval: Duration,
load_base_split_check_interval: Duration,
collect_tick_interval: Duration,
report_min_resolved_ts_interval: Duration,
}
impl<EK, ER> StatsMonitor<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
pub fn new(
interval: Duration,
report_min_resolved_ts_interval: Duration,
scheduler: Scheduler<Task<EK, ER>>,
) -> Self {
StatsMonitor {
scheduler,
handle: None,
timer: None,
read_stats_sender: None,
collect_store_infos_interval: interval,
load_base_split_check_interval: cmp::min(
DEFAULT_LOAD_BASE_SPLIT_CHECK_INTERVAL,
interval,
),
report_min_resolved_ts_interval: config(report_min_resolved_ts_interval),
collect_tick_interval: cmp::min(default_collect_tick_interval(), interval),
}
}
// Collecting thread information and obtaining qps information for auto split.
// They run together in the same thread by taking modulo at different intervals.
pub fn start(
&mut self,
mut auto_split_controller: AutoSplitController,
region_read_progress: RegionReadProgressRegistry,
store_id: u64,
) -> Result<(), io::Error> {
if self.collect_tick_interval < default_collect_tick_interval()
|| self.collect_store_infos_interval < self.collect_tick_interval
{
info!(
"interval is too small, skip stats monitoring. If we are running tests, it is normal, otherwise a check is needed."
);
return Ok(());
}
let mut timer_cnt = 0; // to run functions with different intervals in a loop
let tick_interval = self.collect_tick_interval;
let collect_store_infos_interval = self
.collect_store_infos_interval
.div_duration_f64(tick_interval) as u64;
let load_base_split_check_interval = self
.load_base_split_check_interval
.div_duration_f64(tick_interval) as u64;
let report_min_resolved_ts_interval = self
.report_min_resolved_ts_interval
.div_duration_f64(tick_interval) as u64;
let (timer_tx, timer_rx) = mpsc::channel();
self.timer = Some(timer_tx);
let (read_stats_sender, read_stats_receiver) = mpsc::channel();
self.read_stats_sender = Some(read_stats_sender);
let scheduler = self.scheduler.clone();
let props = tikv_util::thread_group::current_properties();
fn is_enable_tick(timer_cnt: u64, interval: u64) -> bool {
interval != 0 && timer_cnt % interval == 0
}
let h = Builder::new()
.name(thd_name!("stats-monitor"))
.spawn(move || {
tikv_util::thread_group::set_properties(props);
tikv_alloc::add_thread_memory_accessor();
let mut thread_stats = ThreadInfoStatistics::new();
while let Err(mpsc::RecvTimeoutError::Timeout) =
timer_rx.recv_timeout(tick_interval)
{
if is_enable_tick(timer_cnt, collect_store_infos_interval) {
StatsMonitor::collect_store_infos(&mut thread_stats, &scheduler);
}
if is_enable_tick(timer_cnt, load_base_split_check_interval) {
StatsMonitor::load_base_split(
&mut auto_split_controller,
&read_stats_receiver,
&scheduler,
);
}
if is_enable_tick(timer_cnt, report_min_resolved_ts_interval) {
StatsMonitor::report_min_resolved_ts(
®ion_read_progress,
store_id,
&scheduler,
);
}
timer_cnt += 1;
}
tikv_alloc::remove_thread_memory_accessor();
})?;
self.handle = Some(h);
Ok(())
}
pub fn collect_store_infos(
thread_stats: &mut ThreadInfoStatistics,
scheduler: &Scheduler<Task<EK, ER>>,
) {
thread_stats.record();
let cpu_usages = convert_record_pairs(thread_stats.get_cpu_usages());
let read_io_rates = convert_record_pairs(thread_stats.get_read_io_rates());
let write_io_rates = convert_record_pairs(thread_stats.get_write_io_rates());
let task = Task::StoreInfos {
cpu_usages,
read_io_rates,
write_io_rates,
};
if let Err(e) = scheduler.schedule(task) {
error!(
"failed to send store infos to pd worker";
"err" => ?e,
);
}
}
pub fn load_base_split(
auto_split_controller: &mut AutoSplitController,
receiver: &Receiver<ReadStats>,
scheduler: &Scheduler<Task<EK, ER>>,
) {
auto_split_controller.refresh_cfg();
let mut others = vec![];
while let Ok(other) = receiver.try_recv() {
others.push(other);
}
let (top, split_infos) = auto_split_controller.flush(others);
auto_split_controller.clear();
let task = Task::AutoSplit { split_infos };
if let Err(e) = scheduler.schedule(task) {
error!(
"failed to send split infos to pd worker";
"err" => ?e,
);
}
for i in 0..TOP_N {
if i < top.len() {
READ_QPS_TOPN
.with_label_values(&[&i.to_string()])
.set(top[i] as f64);
} else {
READ_QPS_TOPN.with_label_values(&[&i.to_string()]).set(0.0);
}
}
}
pub fn report_min_resolved_ts(
region_read_progress: &RegionReadProgressRegistry,
store_id: u64,
scheduler: &Scheduler<Task<EK, ER>>,
) {
let min_resolved_ts = region_read_progress.with(|registry| {
registry
.iter()
.map(|(_, rrp)| rrp.safe_ts())
.filter(|ts| *ts != 0) // ts == 0 means the peer is uninitialized
.min()
.unwrap_or(0)
});
let task = Task::ReportMinResolvedTS {
store_id,
min_resolved_ts,
};
if let Err(e) = scheduler.schedule(task) {
error!(
"failed to send min resolved ts to pd worker";
"err" => ?e,
);
}
}
pub fn stop(&mut self) {
if let Some(h) = self.handle.take() {
drop(self.timer.take());
drop(self.read_stats_sender.take());
if let Err(e) = h.join() {
error!("join stats collector failed"; "err" => ?e);
}
}
}
pub fn get_read_stats_sender(&self) -> &Option<Sender<ReadStats>> {
&self.read_stats_sender
}
}
const HOTSPOT_KEY_RATE_THRESHOLD: u64 = 128;
const HOTSPOT_QUERY_RATE_THRESHOLD: u64 = 128;
const HOTSPOT_BYTE_RATE_THRESHOLD: u64 = 8 * 1024;
const HOTSPOT_REPORT_CAPACITY: usize = 1000;
// TODO: support dynamic configure threshold in future.
fn hotspot_key_report_threshold() -> u64 {
#[cfg(feature = "failpoints")]
fail_point!("mock_hotspot_threshold", |_| { 0 });
HOTSPOT_KEY_RATE_THRESHOLD * 10
}
fn hotspot_byte_report_threshold() -> u64 {
#[cfg(feature = "failpoints")]
fail_point!("mock_hotspot_threshold", |_| { 0 });
HOTSPOT_BYTE_RATE_THRESHOLD * 10
}
fn hotspot_query_num_report_threshold() -> u64 {
#[cfg(feature = "failpoints")]
fail_point!("mock_hotspot_threshold", |_| { 0 });
HOTSPOT_QUERY_RATE_THRESHOLD * 10
}
// Slow score is a value that represents the speed of a store and ranges in [1, 100].
// It is maintained in the AIMD way.
// If there are some inspecting requests timeout during a round, by default the score
// will be increased at most 1x when above 10% inspecting requests timeout.
// If there is not any timeout inspecting requests, the score will go back to 1 in at least 5min.
struct SlowScore {
value: OrderedFloat<f64>,
last_record_time: Instant,
last_update_time: Instant,
timeout_requests: usize,
total_requests: usize,
inspect_interval: Duration,
// The maximal tolerated timeout ratio.
ratio_thresh: OrderedFloat<f64>,
// Minimal time that the score could be decreased from 100 to 1.
min_ttr: Duration,
// After how many ticks the value need to be updated.
round_ticks: u64,
// Identify every ticks.
last_tick_id: u64,
// If the last tick does not finished, it would be recorded as a timeout.
last_tick_finished: bool,
}
impl SlowScore {
fn new(inspect_interval: Duration) -> SlowScore {
SlowScore {
value: OrderedFloat(1.0),
timeout_requests: 0,
total_requests: 0,
inspect_interval,
ratio_thresh: OrderedFloat(0.1),
min_ttr: Duration::from_secs(5 * 60),
last_record_time: Instant::now(),
last_update_time: Instant::now(),
round_ticks: 30,
last_tick_id: 0,
last_tick_finished: true,
}
}
fn record(&mut self, id: u64, duration: Duration) {
self.last_record_time = Instant::now();
if id != self.last_tick_id {
return;
}
self.last_tick_finished = true;
self.total_requests += 1;
if duration >= self.inspect_interval {
self.timeout_requests += 1;
}
}
fn record_timeout(&mut self) {
self.last_tick_finished = true;
self.total_requests += 1;
self.timeout_requests += 1;
}
fn update(&mut self) -> f64 {
let elapsed = self.last_update_time.elapsed();
self.update_impl(elapsed).into()
}
fn get(&self) -> f64 {
self.value.into()
}
// Update the score in a AIMD way.
fn update_impl(&mut self, elapsed: Duration) -> OrderedFloat<f64> {
if self.timeout_requests == 0 {
let desc = 100.0 * (elapsed.as_millis() as f64 / self.min_ttr.as_millis() as f64);
if OrderedFloat(desc) > self.value - OrderedFloat(1.0) {
self.value = 1.0.into();
} else {
self.value -= desc;
}
} else {
let timeout_ratio = self.timeout_requests as f64 / self.total_requests as f64;
let near_thresh =
cmp::min(OrderedFloat(timeout_ratio), self.ratio_thresh) / self.ratio_thresh;
let value = self.value * (OrderedFloat(1.0) + near_thresh);
self.value = cmp::min(OrderedFloat(100.0), value);
}
self.total_requests = 0;
self.timeout_requests = 0;
self.last_update_time = Instant::now();
self.value
}
}
// RegionCPUMeteringCollector is used to collect the region-related CPU info.
struct RegionCPUMeteringCollector<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
scheduler: Scheduler<Task<EK, ER>>,
}
impl<EK, ER> RegionCPUMeteringCollector<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
fn new(scheduler: Scheduler<Task<EK, ER>>) -> RegionCPUMeteringCollector<EK, ER> {
RegionCPUMeteringCollector { scheduler }
}
}
impl<EK, ER> Collector for RegionCPUMeteringCollector<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
fn collect(&self, records: Arc<RawRecords>) {
self.scheduler
.schedule(Task::RegionCPURecords(records))
.ok();
}
}
pub struct Runner<EK, ER, T>
where
EK: KvEngine,
ER: RaftEngine,
T: PdClient + 'static,
{
store_id: u64,
pd_client: Arc<T>,
router: RaftRouter<EK, ER>,
region_peers: HashMap<u64, PeerStat>,
region_buckets: HashMap<u64, ReportBucket>,
store_stat: StoreStat,
is_hb_receiver_scheduled: bool,
// Records the boot time.
start_ts: UnixSecs,
// use for Runner inner handle function to send Task to itself
// actually it is the sender connected to Runner's Worker which
// calls Runner's run() on Task received.
scheduler: Scheduler<Task<EK, ER>>,
stats_monitor: StatsMonitor<EK, ER>,
_region_cpu_records_collector: CollectorGuard,
// region_id -> total_cpu_time_ms (since last region heartbeat)
region_cpu_records: HashMap<u64, u32>,
concurrency_manager: ConcurrencyManager,
snap_mgr: SnapManager,
remote: Remote<yatp::task::future::TaskCell>,
slow_score: SlowScore,
// The health status of the store is updated by the slow score mechanism.
health_service: Option<HealthService>,
curr_health_status: ServingStatus,
}
impl<EK, ER, T> Runner<EK, ER, T>
where
EK: KvEngine,
ER: RaftEngine,
T: PdClient + 'static,
{
const INTERVAL_DIVISOR: u32 = 2;
pub fn new(
cfg: &Config,
store_id: u64,
pd_client: Arc<T>,
router: RaftRouter<EK, ER>,
scheduler: Scheduler<Task<EK, ER>>,
store_heartbeat_interval: Duration,
auto_split_controller: AutoSplitController,
concurrency_manager: ConcurrencyManager,
snap_mgr: SnapManager,
remote: Remote<yatp::task::future::TaskCell>,
collector_reg_handle: CollectorRegHandle,
region_read_progress: RegionReadProgressRegistry,
health_service: Option<HealthService>,
) -> Runner<EK, ER, T> {
let interval = store_heartbeat_interval / Self::INTERVAL_DIVISOR;
let mut stats_monitor = StatsMonitor::new(
interval,
cfg.report_min_resolved_ts_interval.0,
scheduler.clone(),
);
if let Err(e) = stats_monitor.start(auto_split_controller, region_read_progress, store_id) {
error!("failed to start stats collector, error = {:?}", e);
}
let _region_cpu_records_collector = collector_reg_handle.register(
Box::new(RegionCPUMeteringCollector::new(scheduler.clone())),
true,
);
Runner {
store_id,
pd_client,
router,
is_hb_receiver_scheduled: false,
region_peers: HashMap::default(),
region_buckets: HashMap::default(),
store_stat: StoreStat::default(),
start_ts: UnixSecs::now(),
scheduler,
stats_monitor,
_region_cpu_records_collector,
region_cpu_records: HashMap::default(),
concurrency_manager,
snap_mgr,
remote,
slow_score: SlowScore::new(cfg.inspect_interval.0),
health_service,
curr_health_status: ServingStatus::Serving,
}
}
// Deprecate
fn handle_ask_split(
&self,
mut region: metapb::Region,
split_key: Vec<u8>,
peer: metapb::Peer,
right_derive: bool,
callback: Callback<EK::Snapshot>,
task: String,
) {
let router = self.router.clone();
let resp = self.pd_client.ask_split(region.clone());
let f = async move {
match resp.await {
Ok(mut resp) => {
info!(
"try to split region";
"region_id" => region.get_id(),
"new_region_id" => resp.get_new_region_id(),
"region" => ?region,
"task"=>task,
);
let req = new_split_region_request(
split_key,
resp.get_new_region_id(),
resp.take_new_peer_ids(),
right_derive,
);
let region_id = region.get_id();
let epoch = region.take_region_epoch();
send_admin_request(
&router,
region_id,
epoch,
peer,
req,
callback,
Default::default(),
);
}
Err(e) => {
warn!("failed to ask split";
"region_id" => region.get_id(),
"err" => ?e,
"task"=>task);
}
}
};
self.remote.spawn(f);
}
// Note: The parameter doesn't contain `self` because this function may
// be called in an asynchronous context.
fn handle_ask_batch_split(
router: RaftRouter<EK, ER>,
scheduler: Scheduler<Task<EK, ER>>,
pd_client: Arc<T>,
mut region: metapb::Region,
mut split_keys: Vec<Vec<u8>>,
peer: metapb::Peer,
right_derive: bool,
callback: Callback<EK::Snapshot>,
task: String,
remote: Remote<yatp::task::future::TaskCell>,
) {
if split_keys.is_empty() {
info!("empty split key, skip ask batch split";
"region_id" => region.get_id());
return;
}
let resp = pd_client.ask_batch_split(region.clone(), split_keys.len());
let f = async move {
match resp.await {
Ok(mut resp) => {
info!(
"try to batch split region";
"region_id" => region.get_id(),
"new_region_ids" => ?resp.get_ids(),
"region" => ?region,
"task" => task,
);
let req = new_batch_split_region_request(
split_keys,