/
mod.rs
8345 lines (7815 loc) · 281 KB
/
mod.rs
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.
// #[PerformanceCriticalPath]
//! This module contains TiKV's transaction layer. It lowers high-level, transactional
//! commands to low-level (raw key-value) interactions with persistent storage.
//!
//! This module is further split into layers: [`txn`](txn) lowers transactional commands to
//! key-value operations on an MVCC abstraction. [`mvcc`](mvcc) is our MVCC implementation.
//! [`kv`](kv) is an abstraction layer over persistent storage.
//!
//! Other responsibilities of this module are managing latches (see [`latch`](txn::latch)), deadlock
//! and wait handling (see [`lock_manager`](lock_manager)), sche
//! duling command execution (see
//! [`txn::scheduler`](txn::scheduler)), and handling commands from the raw and versioned APIs (in
//! the [`Storage`](Storage) struct).
//!
//! For more information about TiKV's transactions, see the [sig-txn docs](https://github.com/tikv/sig-transaction/tree/master/doc).
//!
//! Some important types are:
//!
//! * the [`Engine`](kv::Engine) trait and related traits, which abstracts over underlying storage,
//! * the [`MvccTxn`](mvcc::txn::MvccTxn) struct, which is the primary object in the MVCC
//! implementation,
//! * the commands in the [`commands`](txn::commands) module, which are how each command is implemented,
//! * the [`Storage`](Storage) struct, which is the primary entry point for this module.
//!
//! Related code:
//!
//! * the [`kv`](crate::server::service::kv) module, which is the interface for TiKV's APIs,
//! * the [`lock_manager](crate::server::lock_manager), which takes part in lock and deadlock
//! management,
//! * [`gc_worker`](crate::server::gc_worker), which drives garbage collection of old values,
//! * the [`txn_types](::txn_types) crate, some important types for this module's interface,
//! * the [`kvproto`](::kvproto) crate, which defines TiKV's protobuf API and includes some
//! documentation of the commands implemented here,
//! * the [`test_storage`](::test_storage) crate, integration tests for this module,
//! * the [`engine_traits`](::engine_traits) crate, more detail of the engine abstraction.
pub mod config;
pub mod errors;
pub mod kv;
pub mod lock_manager;
pub(crate) mod metrics;
pub mod mvcc;
pub mod raw;
pub mod txn;
mod read_pool;
mod types;
use self::kv::SnapContext;
pub use self::{
errors::{get_error_kind_from_header, get_tag_from_header, Error, ErrorHeaderKind, ErrorInner},
kv::{
CfStatistics, Cursor, CursorBuilder, Engine, FlowStatistics, FlowStatsReporter, Iterator,
PerfStatisticsDelta, PerfStatisticsInstant, RocksEngine, ScanMode, Snapshot,
StageLatencyStats, Statistics, TestEngineBuilder,
},
raw::RawStore,
read_pool::{build_read_pool, build_read_pool_for_test},
txn::{Latches, Lock as LatchLock, ProcessResult, Scanner, SnapshotStore, Store},
types::{PessimisticLockRes, PrewriteResult, SecondaryLocksStatus, StorageCallback, TxnStatus},
};
use crate::read_pool::{ReadPool, ReadPoolHandle};
use crate::storage::metrics::CommandKind;
use crate::storage::mvcc::MvccReader;
use crate::storage::txn::commands::{RawAtomicStore, RawCompareAndSwap};
use crate::storage::txn::flow_controller::FlowController;
use crate::server::lock_manager::waiter_manager;
use crate::storage::{
config::Config,
kv::{with_tls_engine, Modify, WriteData},
lock_manager::{DummyLockManager, LockManager},
metrics::*,
mvcc::PointGetterBuilder,
txn::{commands::TypedCommand, scheduler::Scheduler as TxnScheduler, Command},
types::StorageCallbackType,
};
use api_version::{match_template_api_version, APIVersion, KeyMode, RawValue, APIV2};
use concurrency_manager::ConcurrencyManager;
use engine_traits::{raw_ttl::ttl_to_expire_ts, CfName, CF_DEFAULT, CF_LOCK, CF_WRITE, DATA_CFS};
use futures::prelude::*;
use kvproto::kvrpcpb::ApiVersion;
use kvproto::kvrpcpb::{
ChecksumAlgorithm, CommandPri, Context, GetRequest, IsolationLevel, KeyRange, LockInfo,
RawGetRequest,
};
use kvproto::pdpb::QueryKind;
use raftstore::store::{util::build_key_range, TxnExt};
use raftstore::store::{ReadStats, WriteStats};
use rand::prelude::*;
use resource_metering::{FutureExt, ResourceTagFactory};
use std::{
borrow::Cow,
iter,
sync::{
atomic::{self, AtomicBool},
Arc,
},
};
use tikv_kv::SnapshotExt;
use tikv_util::time::{duration_to_ms, Instant, ThreadReadId};
use txn_types::{Key, KvPair, Lock, OldValues, RawMutation, TimeStamp, TsSet, Value};
pub type Result<T> = std::result::Result<T, Error>;
pub type Callback<T> = Box<dyn FnOnce(Result<T>) + Send>;
/// [`Storage`](Storage) implements transactional KV APIs and raw KV APIs on a given [`Engine`].
/// An [`Engine`] provides low level KV functionality. [`Engine`] has multiple implementations.
/// When a TiKV server is running, a [`RaftKv`](crate::server::raftkv::RaftKv) will be the
/// underlying [`Engine`] of [`Storage`]. The other two types of engines are for test purpose.
///
///[`Storage`] is reference counted and cloning [`Storage`] will just increase the reference counter.
/// Storage resources (i.e. threads, engine) will be released when all references are dropped.
///
/// Notice that read and write methods may not be performed over full data in most cases, i.e. when
/// underlying engine is [`RaftKv`](crate::server::raftkv::RaftKv),
/// which limits data access in the range of a single region
/// according to specified `ctx` parameter. However,
/// [`unsafe_destroy_range`](crate::server::gc_worker::GcTask::UnsafeDestroyRange) is the only exception.
/// It's always performed on the whole TiKV.
///
/// Operations of [`Storage`](Storage) can be divided into two types: MVCC operations and raw operations.
/// MVCC operations uses MVCC keys, which usually consist of several physical keys in different
/// CFs. In default CF and write CF, the key will be memcomparable-encoded and append the timestamp
/// to it, so that multiple versions can be saved at the same time.
/// Raw operations use raw keys, which are saved directly to the engine without memcomparable-
/// encoding and appending timestamp.
pub struct Storage<E: Engine, L: LockManager> {
// TODO: Too many Arcs, would be slow when clone.
engine: E,
sched: TxnScheduler<E, L>,
/// The thread pool used to run most read operations.
read_pool: ReadPoolHandle,
concurrency_manager: ConcurrencyManager,
/// How many strong references. Thread pool and workers will be stopped
/// once there are no more references.
// TODO: This should be implemented in thread pool and worker.
refs: Arc<atomic::AtomicUsize>,
// Fields below are storage configurations.
max_key_size: usize,
resource_tag_factory: ResourceTagFactory,
api_version: ApiVersion,
}
impl<E: Engine, L: LockManager> Clone for Storage<E, L> {
#[inline]
fn clone(&self) -> Self {
let refs = self.refs.fetch_add(1, atomic::Ordering::SeqCst);
trace!(
"Storage referenced"; "original_ref" => refs
);
Self {
engine: self.engine.clone(),
sched: self.sched.clone(),
read_pool: self.read_pool.clone(),
refs: self.refs.clone(),
max_key_size: self.max_key_size,
concurrency_manager: self.concurrency_manager.clone(),
api_version: self.api_version,
resource_tag_factory: self.resource_tag_factory.clone(),
}
}
}
impl<E: Engine, L: LockManager> Drop for Storage<E, L> {
#[inline]
fn drop(&mut self) {
let refs = self.refs.fetch_sub(1, atomic::Ordering::SeqCst);
trace!(
"Storage de-referenced"; "original_ref" => refs
);
if refs != 1 {
return;
}
info!("Storage stopped.");
}
}
macro_rules! check_key_size {
($key_iter: expr, $max_key_size: expr, $callback: ident) => {
for k in $key_iter {
let key_size = k.len();
if key_size > $max_key_size {
$callback(Err(Error::from(ErrorInner::KeyTooLarge {
size: key_size,
limit: $max_key_size,
})));
return Ok(());
}
}
};
}
impl<E: Engine, L: LockManager> Storage<E, L> {
/// Create a `Storage` from given engine.
pub fn from_engine<R: FlowStatsReporter>(
engine: E,
config: &Config,
read_pool: ReadPoolHandle,
lock_mgr: L,
concurrency_manager: ConcurrencyManager,
dynamic_switches: DynamicConfigs,
flow_controller: Arc<FlowController>,
reporter: R,
resource_tag_factory: ResourceTagFactory,
) -> Result<Self> {
let sched = TxnScheduler::new(
engine.clone(),
lock_mgr,
concurrency_manager.clone(),
config,
dynamic_switches,
flow_controller,
reporter,
resource_tag_factory.clone(),
);
info!("Storage started.");
Ok(Storage {
engine,
sched,
read_pool,
concurrency_manager,
refs: Arc::new(atomic::AtomicUsize::new(1)),
max_key_size: config.max_key_size,
api_version: config.api_version(),
resource_tag_factory,
})
}
/// Get the underlying `Engine` of the `Storage`.
pub fn get_engine(&self) -> E {
self.engine.clone()
}
pub fn get_concurrency_manager(&self) -> ConcurrencyManager {
self.concurrency_manager.clone()
}
pub fn dump_wait_for_entries(&self, cb: waiter_manager::Callback) {
self.sched.dump_wait_for_entries(cb);
}
/// Get a snapshot of `engine`.
fn snapshot(
engine: &E,
ctx: SnapContext<'_>,
) -> impl std::future::Future<Output = Result<E::Snap>> {
kv::snapshot(engine, ctx)
.map_err(txn::Error::from)
.map_err(Error::from)
}
#[cfg(test)]
pub fn get_snapshot(&self) -> E::Snap {
self.engine.snapshot(Default::default()).unwrap()
}
pub fn release_snapshot(&self) {
self.engine.release_snapshot();
}
pub fn get_readpool_queue_per_worker(&self) -> usize {
self.read_pool.get_queue_size_per_worker()
}
pub fn get_normal_pool_size(&self) -> usize {
self.read_pool.get_normal_pool_size()
}
#[inline]
fn with_tls_engine<F, R>(f: F) -> R
where
F: FnOnce(&E) -> R,
{
// Safety: the read pools ensure that a TLS engine exists.
unsafe { with_tls_engine(f) }
}
/// Check the given raw kv CF name. If the given cf is empty, CF_DEFAULT will be returned.
fn rawkv_cf(cf: &str, api_version: ApiVersion) -> Result<CfName> {
match api_version {
ApiVersion::V1 | ApiVersion::V1ttl => {
// In API V1, the possible cfs are CF_DEFAULT, CF_LOCK and CF_WRITE.
if cf.is_empty() {
return Ok(CF_DEFAULT);
}
for c in [CF_DEFAULT, CF_LOCK, CF_WRITE] {
if cf == c {
return Ok(c);
}
}
Err(Error::from(ErrorInner::InvalidCf(cf.to_owned())))
}
ApiVersion::V2 => {
// API V2 doesn't allow raw requests from explicitly specifying a `cf`.
if cf.is_empty() {
return Ok(CF_DEFAULT);
}
Err(Error::from(ErrorInner::CfDeprecated(cf.to_owned())))
}
}
}
/// Check if key range is valid
///
/// - If `reverse` is true, `end_key` is less than `start_key`. `end_key` is the lower bound.
/// - If `reverse` is false, `end_key` is greater than `start_key`. `end_key` is the upper bound.
fn check_key_ranges(ranges: &[KeyRange], reverse: bool) -> bool {
let ranges_len = ranges.len();
for i in 0..ranges_len {
let start_key = ranges[i].get_start_key();
let mut end_key = ranges[i].get_end_key();
if end_key.is_empty() && i + 1 != ranges_len {
end_key = ranges[i + 1].get_start_key();
}
if !end_key.is_empty()
&& (!reverse && start_key >= end_key || reverse && start_key <= end_key)
{
return false;
}
}
true
}
/// Check whether a raw kv command or not.
#[inline]
fn is_raw_command(cmd: CommandKind) -> bool {
matches!(
cmd,
CommandKind::raw_batch_get_command
| CommandKind::raw_get
| CommandKind::raw_batch_get
| CommandKind::raw_scan
| CommandKind::raw_batch_scan
| CommandKind::raw_put
| CommandKind::raw_batch_put
| CommandKind::raw_delete
| CommandKind::raw_delete_range
| CommandKind::raw_batch_delete
| CommandKind::raw_get_key_ttl
| CommandKind::raw_compare_and_swap
| CommandKind::raw_atomic_store
| CommandKind::raw_checksum
)
}
/// Check whether a trancsation kv command or not.
#[inline]
fn is_txn_command(cmd: CommandKind) -> bool {
!Self::is_raw_command(cmd)
}
/// Check api version.
///
/// When config.api_version = V1: accept request of V1 only.
/// When config.api_version = V2: accept the following:
/// * Request of V1 from TiDB, for compatibility.
/// * Request of V2 with legal prefix.
/// See the following for detail:
/// * rfc: https://github.com/tikv/rfcs/blob/master/text/0069-api-v2.md.
/// * proto: https://github.com/pingcap/kvproto/blob/master/proto/kvrpcpb.proto, enum APIVersion.
fn check_api_version(
storage_api_version: ApiVersion,
req_api_version: ApiVersion,
cmd: CommandKind,
keys: impl IntoIterator<Item = impl AsRef<[u8]>>,
) -> Result<()> {
match (storage_api_version, req_api_version) {
(ApiVersion::V1, ApiVersion::V1) => {}
(ApiVersion::V1ttl, ApiVersion::V1) if Self::is_raw_command(cmd) => {
// storage api_version = V1ttl, allow RawKV request only.
}
(ApiVersion::V2, ApiVersion::V1) if Self::is_txn_command(cmd) => {
// For compatibility, accept TiDB request only.
for key in keys {
if APIV2::parse_key_mode(key.as_ref()) != KeyMode::TiDB {
return Err(ErrorInner::invalid_key_mode(
cmd,
storage_api_version,
key.as_ref(),
)
.into());
}
}
}
(ApiVersion::V2, ApiVersion::V2) if Self::is_raw_command(cmd) => {
for key in keys {
if APIV2::parse_key_mode(key.as_ref()) != KeyMode::Raw {
return Err(ErrorInner::invalid_key_mode(
cmd,
storage_api_version,
key.as_ref(),
)
.into());
}
}
}
(ApiVersion::V2, ApiVersion::V2) if Self::is_txn_command(cmd) => {
for key in keys {
if APIV2::parse_key_mode(key.as_ref()) != KeyMode::Txn {
return Err(ErrorInner::invalid_key_mode(
cmd,
storage_api_version,
key.as_ref(),
)
.into());
}
}
}
_ => {
return Err(Error::from(ErrorInner::ApiVersionNotMatched {
cmd,
storage_api_version,
req_api_version,
}));
}
}
Ok(())
}
fn check_api_version_ranges(
storage_api_version: ApiVersion,
req_api_version: ApiVersion,
cmd: CommandKind,
ranges: impl IntoIterator<Item = (Option<impl AsRef<[u8]>>, Option<impl AsRef<[u8]>>)>,
) -> Result<()> {
match (storage_api_version, req_api_version) {
(ApiVersion::V1, ApiVersion::V1) => {}
(ApiVersion::V1ttl, ApiVersion::V1) if Self::is_raw_command(cmd) => {
// storage api_version = V1ttl, allow RawKV request only.
}
(ApiVersion::V2, ApiVersion::V1) if Self::is_txn_command(cmd) => {
// For compatibility, accept TiDB request only.
for range in ranges {
let range = (
range.0.as_ref().map(AsRef::as_ref),
range.1.as_ref().map(AsRef::as_ref),
);
if APIV2::parse_range_mode(range) != KeyMode::TiDB {
return Err(ErrorInner::invalid_key_range_mode(
cmd,
storage_api_version,
range,
)
.into());
}
}
}
(ApiVersion::V2, ApiVersion::V2) if Self::is_raw_command(cmd) => {
for range in ranges {
let range = (
range.0.as_ref().map(AsRef::as_ref),
range.1.as_ref().map(AsRef::as_ref),
);
if APIV2::parse_range_mode(range) != KeyMode::Raw {
return Err(ErrorInner::invalid_key_range_mode(
cmd,
storage_api_version,
range,
)
.into());
}
}
}
(ApiVersion::V2, ApiVersion::V2) if Self::is_txn_command(cmd) => {
for range in ranges {
let range = (
range.0.as_ref().map(AsRef::as_ref),
range.1.as_ref().map(AsRef::as_ref),
);
if APIV2::parse_range_mode(range) != KeyMode::Txn {
return Err(ErrorInner::invalid_key_range_mode(
cmd,
storage_api_version,
range,
)
.into());
}
}
}
_ => {
return Err(Error::from(ErrorInner::ApiVersionNotMatched {
cmd,
storage_api_version,
req_api_version,
}));
}
}
Ok(())
}
/// Get value of the given key from a snapshot.
///
/// Only writes that are committed before `start_ts` are visible.
pub fn get(
&self,
mut ctx: Context,
key: Key,
start_ts: TimeStamp,
) -> impl Future<Output = Result<(Option<Value>, KvGetStatistics)>> {
let stage_begin_ts = Instant::now_coarse();
const CMD: CommandKind = CommandKind::get;
let priority = ctx.get_priority();
let priority_tag = get_priority_tag(priority);
let resource_tag = self.resource_tag_factory.new_tag_with_key_ranges(
&ctx,
vec![(key.as_encoded().to_vec(), key.as_encoded().to_vec())],
);
let concurrency_manager = self.concurrency_manager.clone();
let api_version = self.api_version;
let res = self.read_pool.spawn_handle(
async move {
let stage_scheduled_ts = Instant::now_coarse();
tls_collect_query(
ctx.get_region_id(),
ctx.get_peer(),
key.as_encoded(),
key.as_encoded(),
false,
QueryKind::Get,
);
KV_COMMAND_COUNTER_VEC_STATIC.get(CMD).inc();
SCHED_COMMANDS_PRI_COUNTER_VEC_STATIC
.get(priority_tag)
.inc();
Self::check_api_version(api_version, ctx.api_version, CMD, [key.as_encoded()])?;
let command_duration = tikv_util::time::Instant::now_coarse();
// The bypass_locks and access_locks set will be checked at most once.
// `TsSet::vec` is more efficient here.
let bypass_locks = TsSet::vec_from_u64s(ctx.take_resolved_locks());
let access_locks = TsSet::vec_from_u64s(ctx.take_committed_locks());
let snap_ctx = prepare_snap_ctx(
&ctx,
iter::once(&key),
start_ts,
&bypass_locks,
&concurrency_manager,
CMD,
)?;
let snapshot =
Self::with_tls_engine(|engine| Self::snapshot(engine, snap_ctx)).await?;
{
let begin_instant = Instant::now_coarse();
let stage_snap_recv_ts = begin_instant;
let mut statistics = Statistics::default();
let perf_statistics = PerfStatisticsInstant::new();
let snap_store = SnapshotStore::new(
snapshot,
start_ts,
ctx.get_isolation_level(),
!ctx.get_not_fill_cache(),
bypass_locks,
access_locks,
false,
);
let result = snap_store
.get(&key, &mut statistics)
// map storage::txn::Error -> storage::Error
.map_err(Error::from)
.map(|r| {
KV_COMMAND_KEYREAD_HISTOGRAM_STATIC.get(CMD).observe(1_f64);
r
});
let delta = perf_statistics.delta();
metrics::tls_collect_scan_details(CMD, &statistics);
metrics::tls_collect_read_flow(ctx.get_region_id(), &statistics);
metrics::tls_collect_perf_stats(CMD, &delta);
SCHED_PROCESSING_READ_HISTOGRAM_STATIC
.get(CMD)
.observe(begin_instant.saturating_elapsed_secs());
SCHED_HISTOGRAM_VEC_STATIC
.get(CMD)
.observe(command_duration.saturating_elapsed_secs());
let stage_finished_ts = Instant::now_coarse();
let schedule_wait_time =
stage_scheduled_ts.saturating_duration_since(stage_begin_ts);
let snapshot_wait_time =
stage_snap_recv_ts.saturating_duration_since(stage_scheduled_ts);
let wait_wall_time =
stage_snap_recv_ts.saturating_duration_since(stage_begin_ts);
let process_wall_time =
stage_finished_ts.saturating_duration_since(stage_snap_recv_ts);
let latency_stats = StageLatencyStats {
schedule_wait_time_ms: duration_to_ms(schedule_wait_time),
snapshot_wait_time_ms: duration_to_ms(snapshot_wait_time),
wait_wall_time_ms: duration_to_ms(wait_wall_time),
process_wall_time_ms: duration_to_ms(process_wall_time),
};
Ok((
result?,
KvGetStatistics {
stats: statistics,
perf_stats: delta,
latency_stats,
},
))
}
}
.in_resource_metering_tag(resource_tag),
priority,
thread_rng().next_u64(),
);
async move {
res.map_err(|_| Error::from(ErrorInner::SchedTooBusy))
.await?
}
}
/// Get values of a set of keys with separate context from a snapshot, return a list of `Result`s.
///
/// Only writes that are committed before their respective `start_ts` are visible.
pub fn batch_get_command<
P: 'static + ResponseBatchConsumer<(Option<Vec<u8>>, Statistics, PerfStatisticsDelta)>,
>(
&self,
requests: Vec<GetRequest>,
ids: Vec<u64>,
consumer: P,
begin_instant: tikv_util::time::Instant,
) -> impl Future<Output = Result<()>> {
const CMD: CommandKind = CommandKind::batch_get_command;
// all requests in a batch have the same region, epoch, term, replica_read
let priority = requests[0].get_context().get_priority();
let concurrency_manager = self.concurrency_manager.clone();
let api_version = self.api_version;
// The resource tags of these batched requests are not the same, and it is quite expensive
// to distinguish them, so we can find random one of them as a representative.
let rand_index = rand::thread_rng().gen_range(0, requests.len());
let rand_ctx = requests[rand_index].get_context();
let rand_key = requests[rand_index].get_key().to_vec();
let resource_tag = self
.resource_tag_factory
.new_tag_with_key_ranges(rand_ctx, vec![(rand_key.clone(), rand_key)]);
let res = self.read_pool.spawn_handle(
async move {
KV_COMMAND_COUNTER_VEC_STATIC.get(CMD).inc();
KV_COMMAND_KEYREAD_HISTOGRAM_STATIC
.get(CMD)
.observe(requests.len() as f64);
let command_duration = tikv_util::time::Instant::now_coarse();
let read_id = Some(ThreadReadId::new());
let mut statistics = Statistics::default();
let mut req_snaps = vec![];
for (mut req, id) in requests.into_iter().zip(ids) {
let mut ctx = req.take_context();
let region_id = ctx.get_region_id();
let peer = ctx.get_peer();
let key = Key::from_raw(req.get_key());
tls_collect_query(
region_id,
peer,
key.as_encoded(),
key.as_encoded(),
false,
QueryKind::Get,
);
Self::check_api_version(api_version, ctx.api_version, CMD, [key.as_encoded()])?;
let start_ts = req.get_version().into();
let isolation_level = ctx.get_isolation_level();
let fill_cache = !ctx.get_not_fill_cache();
let bypass_locks = TsSet::vec_from_u64s(ctx.take_resolved_locks());
let access_locks = TsSet::vec_from_u64s(ctx.take_committed_locks());
let region_id = ctx.get_region_id();
let snap_ctx = match prepare_snap_ctx(
&ctx,
iter::once(&key),
start_ts,
&bypass_locks,
&concurrency_manager,
CMD,
) {
Ok(mut snap_ctx) => {
snap_ctx.read_id = if ctx.get_stale_read() {
None
} else {
read_id.clone()
};
snap_ctx
}
Err(e) => {
consumer.consume(id, Err(e), begin_instant);
continue;
}
};
let snap = Self::with_tls_engine(|engine| Self::snapshot(engine, snap_ctx));
req_snaps.push((
snap,
key,
start_ts,
isolation_level,
fill_cache,
bypass_locks,
access_locks,
region_id,
id,
));
}
Self::with_tls_engine(|engine| engine.release_snapshot());
for req_snap in req_snaps {
let (
snap,
key,
start_ts,
isolation_level,
fill_cache,
bypass_locks,
access_locks,
region_id,
id,
) = req_snap;
match snap.await {
Ok(snapshot) => {
match PointGetterBuilder::new(snapshot, start_ts)
.fill_cache(fill_cache)
.isolation_level(isolation_level)
.multi(false)
.bypass_locks(bypass_locks)
.access_locks(access_locks)
.build()
{
Ok(mut point_getter) => {
let perf_statistics = PerfStatisticsInstant::new();
let v = point_getter.get(&key);
let stat = point_getter.take_statistics();
let delta = perf_statistics.delta();
metrics::tls_collect_read_flow(region_id, &stat);
metrics::tls_collect_perf_stats(CMD, &delta);
statistics.add(&stat);
consumer.consume(
id,
v.map_err(|e| Error::from(txn::Error::from(e)))
.map(|v| (v, stat, delta)),
begin_instant,
);
}
Err(e) => {
consumer.consume(
id,
Err(Error::from(txn::Error::from(e))),
begin_instant,
);
}
}
}
Err(e) => {
consumer.consume(id, Err(e), begin_instant);
}
}
}
metrics::tls_collect_scan_details(CMD, &statistics);
SCHED_HISTOGRAM_VEC_STATIC
.get(CMD)
.observe(command_duration.saturating_elapsed_secs());
Ok(())
}
.in_resource_metering_tag(resource_tag),
priority,
thread_rng().next_u64(),
);
async move {
res.map_err(|_| Error::from(ErrorInner::SchedTooBusy))
.await?
}
}
/// Get values of a set of keys in a batch from the snapshot.
///
/// Only writes that are committed before `start_ts` are visible.
pub fn batch_get(
&self,
mut ctx: Context,
keys: Vec<Key>,
start_ts: TimeStamp,
) -> impl Future<Output = Result<(Vec<Result<KvPair>>, KvGetStatistics)>> {
let stage_begin_ts = Instant::now_coarse();
const CMD: CommandKind = CommandKind::batch_get;
let priority = ctx.get_priority();
let priority_tag = get_priority_tag(priority);
let key_ranges = keys
.iter()
.map(|k| (k.as_encoded().to_vec(), k.as_encoded().to_vec()))
.collect();
let resource_tag = self
.resource_tag_factory
.new_tag_with_key_ranges(&ctx, key_ranges);
let concurrency_manager = self.concurrency_manager.clone();
let api_version = self.api_version;
let res = self.read_pool.spawn_handle(
async move {
let stage_scheduled_ts = Instant::now_coarse();
let mut key_ranges = vec![];
for key in &keys {
key_ranges.push(build_key_range(key.as_encoded(), key.as_encoded(), false));
}
tls_collect_query_batch(
ctx.get_region_id(),
ctx.get_peer(),
key_ranges,
QueryKind::Get,
);
KV_COMMAND_COUNTER_VEC_STATIC.get(CMD).inc();
SCHED_COMMANDS_PRI_COUNTER_VEC_STATIC
.get(priority_tag)
.inc();
Self::check_api_version(
api_version,
ctx.api_version,
CMD,
keys.iter().map(Key::as_encoded),
)?;
let command_duration = tikv_util::time::Instant::now_coarse();
let bypass_locks = TsSet::from_u64s(ctx.take_resolved_locks());
let access_locks = TsSet::from_u64s(ctx.take_committed_locks());
let snap_ctx = prepare_snap_ctx(
&ctx,
&keys,
start_ts,
&bypass_locks,
&concurrency_manager,
CMD,
)?;
let snapshot =
Self::with_tls_engine(|engine| Self::snapshot(engine, snap_ctx)).await?;
{
let begin_instant = Instant::now_coarse();
let stage_snap_recv_ts = begin_instant;
let mut statistics = Statistics::default();
let perf_statistics = PerfStatisticsInstant::new();
let snap_store = SnapshotStore::new(
snapshot,
start_ts,
ctx.get_isolation_level(),
!ctx.get_not_fill_cache(),
bypass_locks,
access_locks,
false,
);
let result = snap_store
.batch_get(&keys, &mut statistics)
.map_err(Error::from)
.map(|v| {
let kv_pairs: Vec<_> = v
.into_iter()
.zip(keys)
.filter(|&(ref v, ref _k)| {
!(v.is_ok() && v.as_ref().unwrap().is_none())
})
.map(|(v, k)| match v {
Ok(Some(x)) => Ok((k.into_raw().unwrap(), x)),
Err(e) => Err(Error::from(e)),
_ => unreachable!(),
})
.collect();
KV_COMMAND_KEYREAD_HISTOGRAM_STATIC
.get(CMD)
.observe(kv_pairs.len() as f64);
kv_pairs
});
let delta = perf_statistics.delta();
metrics::tls_collect_scan_details(CMD, &statistics);
metrics::tls_collect_read_flow(ctx.get_region_id(), &statistics);
metrics::tls_collect_perf_stats(CMD, &delta);
SCHED_PROCESSING_READ_HISTOGRAM_STATIC
.get(CMD)
.observe(begin_instant.saturating_elapsed_secs());
SCHED_HISTOGRAM_VEC_STATIC
.get(CMD)
.observe(command_duration.saturating_elapsed_secs());
let stage_finished_ts = Instant::now_coarse();
let schedule_wait_time =
stage_scheduled_ts.saturating_duration_since(stage_begin_ts);
let snapshot_wait_time =
stage_snap_recv_ts.saturating_duration_since(stage_scheduled_ts);
let wait_wall_time =
stage_snap_recv_ts.saturating_duration_since(stage_begin_ts);
let process_wall_time =
stage_finished_ts.saturating_duration_since(stage_snap_recv_ts);
let latency_stats = StageLatencyStats {
schedule_wait_time_ms: duration_to_ms(schedule_wait_time),
snapshot_wait_time_ms: duration_to_ms(snapshot_wait_time),
wait_wall_time_ms: duration_to_ms(wait_wall_time),
process_wall_time_ms: duration_to_ms(process_wall_time),
};
Ok((
result?,
KvGetStatistics {
stats: statistics,
perf_stats: delta,
latency_stats,
},
))
}
}
.in_resource_metering_tag(resource_tag),
priority,
thread_rng().next_u64(),
);
async move {
res.map_err(|_| Error::from(ErrorInner::SchedTooBusy))
.await?
}
}
/// Scan keys in [`start_key`, `end_key`) up to `limit` keys from the snapshot.
/// If `reverse_scan` is true, it scans [`end_key`, `start_key`) in descending order.
/// If `end_key` is `None`, it means the upper bound or the lower bound if reverse scan is unbounded.
///
/// Only writes committed before `start_ts` are visible.
pub fn scan(
&self,
mut ctx: Context,
start_key: Key,
end_key: Option<Key>,
limit: usize,
sample_step: usize,
start_ts: TimeStamp,
key_only: bool,
reverse_scan: bool,
) -> impl Future<Output = Result<Vec<Result<KvPair>>>> {
const CMD: CommandKind = CommandKind::scan;
let priority = ctx.get_priority();
let priority_tag = get_priority_tag(priority);
let resource_tag = self.resource_tag_factory.new_tag_with_key_ranges(
&ctx,
vec![(
start_key.as_encoded().to_vec(),
match &end_key {
Some(k) => k.as_encoded().to_vec(),
None => vec![],
},
)],
);
let concurrency_manager = self.concurrency_manager.clone();
let api_version = self.api_version;
let res = self.read_pool.spawn_handle(
async move {
{
let end_key = match &end_key {
Some(k) => k.as_encoded().as_slice(),
None => &[],
};
tls_collect_query(
ctx.get_region_id(),
ctx.get_peer(),
start_key.as_encoded(),
end_key,
reverse_scan,
QueryKind::Scan,
);
}
KV_COMMAND_COUNTER_VEC_STATIC.get(CMD).inc();
SCHED_COMMANDS_PRI_COUNTER_VEC_STATIC
.get(priority_tag)
.inc();