-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
endpoint.rs
2165 lines (1991 loc) · 80.6 KB
/
endpoint.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 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::{
borrow::Cow, future::Future, iter::FromIterator, marker::PhantomData, mem, sync::Arc,
time::Duration,
};
use ::tracker::{
set_tls_tracker_token, with_tls_tracker, RequestInfo, RequestType, GLOBAL_TRACKERS,
};
use api_version::{dispatch_api_version, KvFormat};
use async_stream::try_stream;
use concurrency_manager::ConcurrencyManager;
use engine_traits::PerfLevel;
use futures::{
channel::{mpsc, oneshot},
future::Either,
prelude::*,
};
use kvproto::{coprocessor as coppb, errorpb, kvrpcpb, kvrpcpb::CommandPri};
use online_config::ConfigManager;
use protobuf::{CodedInputStream, Message};
use resource_control::{ResourceGroupManager, ResourceLimiter, TaskMetadata};
use resource_metering::{FutureExt, ResourceTagFactory, StreamExt};
use tidb_query_common::execute_stats::ExecSummary;
use tikv_alloc::trace::MemoryTraceGuard;
use tikv_kv::SnapshotExt;
use tikv_util::{
deadline::set_deadline_exceeded_busy_error,
memory::{MemoryQuota, OwnedAllocated},
quota_limiter::QuotaLimiter,
time::Instant,
};
use tipb::{AnalyzeReq, AnalyzeType, ChecksumRequest, ChecksumScanOn, DagRequest, ExecType};
use tokio::sync::Semaphore;
use txn_types::Lock;
use super::config_manager::CopConfigManager;
use crate::{
coprocessor::{
cache::CachedRequestHandler, interceptors::*, metrics::*,
statistics::analyze_context::AnalyzeContext, tracker::Tracker, *,
},
read_pool::ReadPoolHandle,
server::Config,
storage::{
self,
kv::{self, with_tls_engine, SnapContext},
mvcc::Error as MvccError,
need_check_locks, need_check_locks_in_replica_read, Engine, Snapshot, SnapshotStore,
},
};
/// Requests that need time of less than `LIGHT_TASK_THRESHOLD` is considered as
/// light ones, which means they don't need a permit from the semaphore before
/// execution.
const LIGHT_TASK_THRESHOLD: Duration = Duration::from_millis(5);
/// A pool to build and run Coprocessor request handlers.
#[derive(Clone)]
pub struct Endpoint<E: Engine> {
/// The thread pool to run Coprocessor requests.
read_pool: ReadPoolHandle,
/// The concurrency limiter of the coprocessor.
semaphore: Option<Arc<Semaphore>>,
/// The memory quota for coprocessor requests.
memory_quota: Arc<MemoryQuota>,
concurrency_manager: ConcurrencyManager,
// Perf stats level
perf_level: PerfLevel,
resource_tag_factory: ResourceTagFactory,
/// The recursion limit when parsing Coprocessor Protobuf requests.
recursion_limit: u32,
batch_row_limit: usize,
stream_batch_row_limit: usize,
stream_channel_size: usize,
/// The soft time limit of handling Coprocessor requests.
max_handle_duration: Duration,
slow_log_threshold: Duration,
quota_limiter: Arc<QuotaLimiter>,
resource_ctl: Option<Arc<ResourceGroupManager>>,
_phantom: PhantomData<E>,
}
impl<E: Engine> tikv_util::AssertSend for Endpoint<E> {}
impl<E: Engine> Endpoint<E> {
pub fn new(
cfg: &Config,
read_pool: ReadPoolHandle,
concurrency_manager: ConcurrencyManager,
resource_tag_factory: ResourceTagFactory,
quota_limiter: Arc<QuotaLimiter>,
resource_ctl: Option<Arc<ResourceGroupManager>>,
) -> Self {
let semaphore = match &read_pool {
ReadPoolHandle::Yatp { .. } => {
Some(Arc::new(Semaphore::new(cfg.end_point_max_concurrency)))
}
_ => None,
};
let memory_quota = Arc::new(MemoryQuota::new(cfg.end_point_memory_quota.0 as _));
register_coprocessor_memory_quota_metrics(memory_quota.clone());
Self {
read_pool,
semaphore,
memory_quota,
concurrency_manager,
perf_level: cfg.end_point_perf_level,
resource_tag_factory,
recursion_limit: cfg.end_point_recursion_limit,
batch_row_limit: cfg.end_point_batch_row_limit,
stream_batch_row_limit: cfg.end_point_stream_batch_row_limit,
stream_channel_size: cfg.end_point_stream_channel_size,
max_handle_duration: cfg.end_point_request_max_handle_duration().0,
slow_log_threshold: cfg.end_point_slow_log_threshold.0,
quota_limiter,
resource_ctl,
_phantom: Default::default(),
}
}
pub fn config_manager(&self) -> Box<dyn ConfigManager> {
Box::new(CopConfigManager::new(self.memory_quota.clone()))
}
fn check_memory_locks(&self, req_ctx: &ReqContext) -> Result<()> {
let start_ts = req_ctx.txn_start_ts;
if !req_ctx.context.get_stale_read() {
self.concurrency_manager.update_max_ts(start_ts);
}
if need_check_locks(req_ctx.context.get_isolation_level()) {
let begin_instant = Instant::now();
for range in &req_ctx.ranges {
let start_key = txn_types::Key::from_raw_maybe_unbounded(range.get_start());
let end_key = txn_types::Key::from_raw_maybe_unbounded(range.get_end());
self.concurrency_manager
.read_range_check(start_key.as_ref(), end_key.as_ref(), |key, lock| {
Lock::check_ts_conflict(
Cow::Borrowed(lock),
key,
start_ts,
&req_ctx.bypass_locks,
req_ctx.context.get_isolation_level(),
)
})
.map_err(|e| {
MEM_LOCK_CHECK_HISTOGRAM_VEC_STATIC
.locked
.observe(begin_instant.saturating_elapsed().as_secs_f64());
MvccError::from(e)
})?;
}
MEM_LOCK_CHECK_HISTOGRAM_VEC_STATIC
.unlocked
.observe(begin_instant.saturating_elapsed().as_secs_f64());
}
Ok(())
}
/// Parse the raw `Request` to create `RequestHandlerBuilder` and
/// `ReqContext`. Returns `Err` if fails.
///
/// It also checks if there are locks in memory blocking this read request.
fn parse_request_and_check_memory_locks(
&self,
req: coppb::Request,
peer: Option<String>,
is_streaming: bool,
) -> Result<(RequestHandlerBuilder<E::Snap>, ReqContext)> {
dispatch_api_version!(req.get_context().get_api_version(), {
self.parse_request_and_check_memory_locks_impl::<API>(req, peer, is_streaming)
})
}
/// Parse the raw `Request` to create `RequestHandlerBuilder` and
/// `ReqContext`. Returns `Err` if fails.
///
/// It also checks if there are locks in memory blocking this read request.
fn parse_request_and_check_memory_locks_impl<F: KvFormat>(
&self,
mut req: coppb::Request,
peer: Option<String>,
is_streaming: bool,
) -> Result<(RequestHandlerBuilder<E::Snap>, ReqContext)> {
fail_point!("coprocessor_parse_request", |_| Err(box_err!(
"unsupported tp (failpoint)"
)));
let (context, data, ranges, mut start_ts) = (
req.take_context(),
req.take_data(),
req.take_ranges().to_vec(),
req.get_start_ts(),
);
let cache_match_version = if req.get_is_cache_enabled() {
Some(req.get_cache_if_match_version())
} else {
None
};
let mut input = CodedInputStream::from_bytes(&data);
input.set_recursion_limit(self.recursion_limit);
let mut req_ctx: ReqContext;
let builder: RequestHandlerBuilder<E::Snap>;
match req.get_tp() {
REQ_TYPE_DAG => {
let mut dag = DagRequest::default();
box_try!(dag.merge_from(&mut input));
let mut table_scan = false;
let mut is_desc_scan = false;
if let Some(scan) = dag.get_executors().iter().next() {
table_scan = scan.get_tp() == ExecType::TypeTableScan;
if table_scan {
is_desc_scan = scan.get_tbl_scan().get_desc();
} else {
is_desc_scan = scan.get_idx_scan().get_desc();
}
}
if start_ts == 0 {
start_ts = dag.get_start_ts_fallback();
}
let tag = if table_scan {
ReqTag::select
} else {
ReqTag::index
};
req_ctx = ReqContext::new(
tag,
context,
ranges,
self.max_handle_duration,
peer,
Some(is_desc_scan),
start_ts.into(),
cache_match_version,
self.perf_level,
);
with_tls_tracker(|tracker| {
tracker.req_info.request_type = RequestType::CoprocessorDag;
tracker.req_info.start_ts = start_ts;
});
self.check_memory_locks(&req_ctx)?;
let batch_row_limit = self.get_batch_row_limit(is_streaming);
let quota_limiter = self.quota_limiter.clone();
builder = Box::new(move |snap, req_ctx| {
let data_version = snap.ext().get_data_version();
let store = SnapshotStore::new(
snap,
start_ts.into(),
req_ctx.context.get_isolation_level(),
!req_ctx.context.get_not_fill_cache(),
req_ctx.bypass_locks.clone(),
req_ctx.access_locks.clone(),
req.get_is_cache_enabled(),
);
let paging_size = match req.get_paging_size() {
0 => None,
i => Some(i),
};
dag::DagHandlerBuilder::<_, F>::new(
dag,
req_ctx.ranges.clone(),
store,
req_ctx.deadline,
batch_row_limit,
is_streaming,
req.get_is_cache_enabled(),
paging_size,
quota_limiter,
)
.data_version(data_version)
.build()
});
}
REQ_TYPE_ANALYZE => {
let mut analyze = AnalyzeReq::default();
box_try!(analyze.merge_from(&mut input));
if start_ts == 0 {
start_ts = analyze.get_start_ts_fallback();
}
let tag = match analyze.get_tp() {
AnalyzeType::TypeIndex | AnalyzeType::TypeCommonHandle => ReqTag::analyze_index,
AnalyzeType::TypeColumn | AnalyzeType::TypeMixed => ReqTag::analyze_table,
AnalyzeType::TypeFullSampling => ReqTag::analyze_full_sampling,
AnalyzeType::TypeSampleIndex => unimplemented!(),
};
req_ctx = ReqContext::new(
tag,
context,
ranges,
self.max_handle_duration,
peer,
None,
start_ts.into(),
cache_match_version,
self.perf_level,
);
with_tls_tracker(|tracker| {
tracker.req_info.request_type = RequestType::CoprocessorAnalyze;
tracker.req_info.start_ts = start_ts;
});
self.check_memory_locks(&req_ctx)?;
let quota_limiter = self.quota_limiter.clone();
builder = Box::new(move |snap, req_ctx| {
AnalyzeContext::<_, F>::new(
analyze,
req_ctx.ranges.clone(),
start_ts,
snap,
req_ctx,
quota_limiter,
)
.map(|h| h.into_boxed())
});
}
REQ_TYPE_CHECKSUM => {
let mut checksum = ChecksumRequest::default();
box_try!(checksum.merge_from(&mut input));
let table_scan = checksum.get_scan_on() == ChecksumScanOn::Table;
if start_ts == 0 {
start_ts = checksum.get_start_ts_fallback();
}
let tag = if table_scan {
ReqTag::checksum_table
} else {
ReqTag::checksum_index
};
req_ctx = ReqContext::new(
tag,
context,
ranges,
self.max_handle_duration,
peer,
None,
start_ts.into(),
cache_match_version,
self.perf_level,
);
// Checksum is allowed during the flashback period to make sure the tool such
// like BR can work.
req_ctx.allowed_in_flashback = true;
with_tls_tracker(|tracker| {
tracker.req_info.request_type = RequestType::CoprocessorChecksum;
tracker.req_info.start_ts = start_ts;
});
self.check_memory_locks(&req_ctx)?;
builder = Box::new(move |snap, req_ctx| {
checksum::ChecksumContext::new(
checksum,
req_ctx.ranges.clone(),
start_ts,
snap,
req_ctx,
)
.map(|h| h.into_boxed())
});
}
tp => return Err(box_err!("unsupported tp {}", tp)),
};
Ok((builder, req_ctx))
}
/// Get the batch row limit configuration.
#[inline]
fn get_batch_row_limit(&self, is_streaming: bool) -> usize {
if is_streaming {
self.stream_batch_row_limit
} else {
self.batch_row_limit
}
}
#[inline]
fn async_snapshot(
engine: &mut E,
ctx: &ReqContext,
) -> impl std::future::Future<Output = Result<E::Snap>> {
let mut snap_ctx = SnapContext {
pb_ctx: &ctx.context,
start_ts: Some(ctx.txn_start_ts),
allowed_in_flashback: ctx.allowed_in_flashback,
..Default::default()
};
// need to pass start_ts and ranges to check memory locks for replica read
if need_check_locks_in_replica_read(&ctx.context) {
for r in &ctx.ranges {
let start_key = txn_types::Key::from_raw(r.get_start());
let end_key = txn_types::Key::from_raw(r.get_end());
let mut key_range = kvrpcpb::KeyRange::default();
key_range.set_start_key(start_key.into_encoded());
key_range.set_end_key(end_key.into_encoded());
snap_ctx.key_ranges.push(key_range);
}
}
kv::snapshot(engine, snap_ctx).map_err(Error::from)
}
/// The real implementation of handling a unary request.
///
/// It first retrieves a snapshot, then builds the `RequestHandler` over the
/// snapshot and the given `handler_builder`. Finally, it calls the unary
/// request interface of the `RequestHandler` to process the request and
/// produce a result.
async fn handle_unary_request_impl(
semaphore: Option<Arc<Semaphore>>,
mut tracker: Box<Tracker<E>>,
handler_builder: RequestHandlerBuilder<E::Snap>,
) -> Result<MemoryTraceGuard<coppb::Response>> {
// When this function is being executed, it may be queued for a long time, so
// that deadline may exceed.
tracker.on_scheduled();
tracker.req_ctx.deadline.check()?;
// Safety: spawning this function using a `FuturePool` ensures that a TLS engine
// exists.
let snapshot =
unsafe { with_tls_engine(|engine| Self::async_snapshot(engine, &tracker.req_ctx)) }
.await?;
let latest_buckets = snapshot.ext().get_buckets();
// Check if the buckets version is latest.
// skip if request don't carry this bucket version.
if let Some(ref buckets) = latest_buckets
&& buckets.version > tracker.req_ctx.context.buckets_version
&& tracker.req_ctx.context.buckets_version != 0
{
let mut bucket_not_match = errorpb::BucketVersionNotMatch::default();
bucket_not_match.set_version(buckets.version);
bucket_not_match.set_keys(buckets.keys.clone().into());
let mut err = errorpb::Error::default();
err.set_bucket_version_not_match(bucket_not_match);
return Err(Error::Region(err));
}
// When snapshot is retrieved, deadline may exceed.
tracker.on_snapshot_finished();
tracker.req_ctx.deadline.check()?;
tracker.buckets = latest_buckets;
let buckets_version = tracker.buckets.as_ref().map_or(0, |b| b.version);
let mut handler = if tracker.req_ctx.cache_match_version.is_some()
&& tracker.req_ctx.cache_match_version == snapshot.ext().get_data_version()
{
// Build a cached request handler instead if cache version is matching.
CachedRequestHandler::builder()(snapshot, &tracker.req_ctx)?
} else {
handler_builder(snapshot, &tracker.req_ctx)?
};
tracker.on_begin_all_items();
let deadline = tracker.req_ctx.deadline;
let handle_request_future = check_deadline(handler.handle_request(), deadline);
let handle_request_future = track(handle_request_future, &mut tracker);
let deadline_res = if let Some(semaphore) = &semaphore {
limit_concurrency(handle_request_future, semaphore, LIGHT_TASK_THRESHOLD).await
} else {
handle_request_future.await
};
let result = deadline_res.map_err(Error::from).and_then(|res| res);
// There might be errors when handling requests. In this case, we still need its
// execution metrics.
let mut exec_summary = ExecSummary::default();
handler.collect_scan_summary(&mut exec_summary);
tracker.collect_scan_process_time(exec_summary);
let mut storage_stats = Statistics::default();
handler.collect_scan_statistics(&mut storage_stats);
tracker.collect_storage_statistics(storage_stats);
let (exec_details, exec_details_v2) = tracker.get_exec_details();
tracker.on_finish_all_items();
let mut resp = match result {
Ok(resp) => {
COPR_RESP_SIZE.inc_by(resp.data.len() as u64);
resp
}
Err(e) => make_error_response(e).into(),
};
resp.set_exec_details(exec_details);
resp.set_exec_details_v2(exec_details_v2);
resp.set_latest_buckets_version(buckets_version);
Ok(resp)
}
/// Handle a unary request and run on the read pool.
///
/// Returns `Err(err)` if the read pool is full. Returns `Ok(future)` in
/// other cases. The future inside may be an error however.
fn handle_unary_request(
&self,
req_ctx: ReqContext,
handler_builder: RequestHandlerBuilder<E::Snap>,
) -> impl Future<Output = Result<MemoryTraceGuard<coppb::Response>>> {
let priority = req_ctx.context.get_priority();
let task_id = req_ctx.build_task_id();
let key_ranges: Vec<_> = req_ctx
.ranges
.iter()
.map(|key_range| (key_range.get_start().to_vec(), key_range.get_end().to_vec()))
.collect();
let resource_tag = self
.resource_tag_factory
.new_tag_with_key_ranges(&req_ctx.context, key_ranges);
let mut allocated_bytes = resource_tag.approximate_heap_size();
let metadata = TaskMetadata::from_ctx(req_ctx.context.get_resource_control_context());
let resource_limiter = self.resource_ctl.as_ref().and_then(|r| {
r.get_resource_limiter(
req_ctx
.context
.get_resource_control_context()
.get_resource_group_name(),
req_ctx.context.get_request_source(),
req_ctx
.context
.get_resource_control_context()
.get_override_priority(),
)
});
// box the tracker so that moving it is cheap.
let tracker = Box::new(Tracker::new(req_ctx, self.slow_log_threshold));
allocated_bytes += tracker.approximate_mem_size();
let (tx, rx) = oneshot::channel();
let future =
Self::handle_unary_request_impl(self.semaphore.clone(), tracker, handler_builder)
.in_resource_metering_tag(resource_tag)
.map(|res| {
let _ = tx.send(res);
});
let res = self.read_pool_spawn_with_memory_quota_check(
allocated_bytes,
future,
priority,
task_id,
metadata,
resource_limiter,
);
async move {
res?;
rx.map_err(|_| Error::MaxPendingTasksExceeded).await?
}
}
/// Parses and handles a unary request. Returns a future that will never
/// fail. If there are errors during parsing or handling, they will be
/// converted into a `Response` as the success result of the future.
#[inline]
pub fn parse_and_handle_unary_request(
&self,
mut req: coppb::Request,
peer: Option<String>,
) -> impl Future<Output = MemoryTraceGuard<coppb::Response>> {
let now = Instant::now();
// Check the load of the read pool. If it's too busy, generate and return
// error in the gRPC thread to avoid waiting in the queue of the read pool.
if let Err(busy_err) = self.read_pool.check_busy_threshold(Duration::from_millis(
req.get_context().get_busy_threshold_ms() as u64,
)) {
let mut pb_error = errorpb::Error::new();
pb_error.set_server_is_busy(busy_err);
let resp = make_error_response(Error::Region(pb_error));
return Either::Left(async move { resp.into() });
}
let tracker = GLOBAL_TRACKERS.insert(::tracker::Tracker::new(RequestInfo::new(
req.get_context(),
RequestType::Unknown,
req.start_ts,
)));
let result_of_batch = self.process_batch_tasks(&mut req, &peer);
set_tls_tracker_token(tracker);
let result_of_future = self
.parse_request_and_check_memory_locks(req, peer, false)
.map(|(handler_builder, req_ctx)| self.handle_unary_request(req_ctx, handler_builder));
with_tls_tracker(|tracker| {
tracker.metrics.grpc_process_nanos = now.saturating_elapsed().as_nanos() as u64;
});
let fut = async move {
let res = match result_of_future {
Err(e) => {
let mut res = make_error_response(e);
let batch_res = result_of_batch.await;
res.set_batch_responses(batch_res.into());
res.into()
}
Ok(handle_fut) => {
let (handle_res, batch_res) = futures::join!(handle_fut, result_of_batch);
let mut res = handle_res.unwrap_or_else(|e| make_error_response(e).into());
res.set_batch_responses(batch_res.into());
GLOBAL_TRACKERS.with_tracker(tracker, |tracker| {
let exec_detail_v2 = res.mut_exec_details_v2();
tracker.write_scan_detail(exec_detail_v2.mut_scan_detail_v2());
tracker.write_time_detail(exec_detail_v2.mut_time_detail_v2());
});
res
}
};
GLOBAL_TRACKERS.remove(tracker);
res
};
Either::Right(fut)
}
// process_batch_tasks process the input batched coprocessor tasks if any,
// prepare all the requests and schedule them into the read pool, then
// collect all the responses and convert them into the `StoreBatchResponse`
// type.
pub fn process_batch_tasks(
&self,
req: &mut coppb::Request,
peer: &Option<String>,
) -> impl Future<Output = Vec<coppb::StoreBatchTaskResponse>> {
let mut batch_futs = Vec::with_capacity(req.tasks.len());
let batch_reqs: Vec<(coppb::Request, u64)> = req
.take_tasks()
.iter_mut()
.map(|task| {
let mut new_req = req.clone();
// Disable the coprocessor cache path for the batched tasks, the
// coprocessor cache related fields are not passed in the "task" by now.
new_req.is_cache_enabled = false;
new_req.ranges = task.take_ranges();
let new_context = new_req.mut_context();
new_context.set_region_id(task.get_region_id());
new_context.set_region_epoch(task.take_region_epoch());
new_context.set_peer(task.take_peer());
(new_req, task.get_task_id())
})
.collect();
for (cur_req, task_id) in batch_reqs.into_iter() {
let request_info = RequestInfo::new(
cur_req.get_context(),
RequestType::Unknown,
cur_req.start_ts,
);
let mut response = coppb::StoreBatchTaskResponse::new();
response.set_task_id(task_id);
match self.parse_request_and_check_memory_locks(cur_req, peer.clone(), false) {
Ok((handler_builder, req_ctx)) => {
let cur_tracker = GLOBAL_TRACKERS.insert(::tracker::Tracker::new(request_info));
set_tls_tracker_token(cur_tracker);
let fut = self.handle_unary_request(req_ctx, handler_builder);
let fut = async move {
let res = fut.await;
match res {
Ok(mut resp) => {
response.set_data(resp.take_data());
if let Some(err) = resp.region_error.take() {
response.set_region_error(err);
}
if let Some(lock_info) = resp.locked.take() {
response.set_locked(lock_info);
}
response.set_other_error(resp.take_other_error());
// keep the exec details already generated.
response.set_exec_details_v2(resp.take_exec_details_v2());
GLOBAL_TRACKERS.with_tracker(cur_tracker, |tracker| {
tracker.write_scan_detail(
response.mut_exec_details_v2().mut_scan_detail_v2(),
);
});
}
Err(e) => {
make_error_batch_response(&mut response, e);
}
}
GLOBAL_TRACKERS.remove(cur_tracker);
response
};
batch_futs.push(future::Either::Left(fut));
}
Err(e) => batch_futs.push(future::Either::Right(async move {
make_error_batch_response(&mut response, e);
response
})),
}
}
stream::FuturesOrdered::from_iter(batch_futs).collect()
}
/// The real implementation of handling a stream request.
///
/// It first retrieves a snapshot, then builds the `RequestHandler` over the
/// snapshot and the given `handler_builder`. Finally, it calls the stream
/// request interface of the `RequestHandler` multiple times to process the
/// request and produce multiple results.
fn handle_stream_request_impl(
semaphore: Option<Arc<Semaphore>>,
mut tracker: Box<Tracker<E>>,
handler_builder: RequestHandlerBuilder<E::Snap>,
) -> impl futures::stream::Stream<Item = Result<coppb::Response>> {
try_stream! {
let _permit = if let Some(semaphore) = semaphore.as_ref() {
Some(semaphore.acquire().await.expect("the semaphore never be closed"))
} else {
None
};
// When this function is being executed, it may be queued for a long time, so that
// deadline may exceed.
tracker.on_scheduled();
tracker.req_ctx.deadline.check()?;
// Safety: spawning this function using a `FuturePool` ensures that a TLS engine
// exists.
let snapshot = unsafe {
with_tls_engine(|engine| Self::async_snapshot(engine, &tracker.req_ctx))
}
.await?;
// When snapshot is retrieved, deadline may exceed.
tracker.on_snapshot_finished();
tracker.req_ctx.deadline.check()?;
let mut handler = handler_builder(snapshot, &tracker.req_ctx)?;
tracker.on_begin_all_items();
loop {
let result = {
tracker.on_begin_item();
let result = handler.handle_streaming_request().await;
let mut storage_stats = Statistics::default();
handler.collect_scan_statistics(&mut storage_stats);
tracker.on_finish_item(Some(storage_stats));
result
};
let (exec_details, exec_details_v2) = tracker.get_item_exec_details();
match result {
Err(e) => {
let mut resp = make_error_response(e);
resp.set_exec_details(exec_details);
resp.set_exec_details_v2(exec_details_v2);
yield resp;
break;
},
Ok((None, _)) => break,
Ok((Some(mut resp), finished)) => {
COPR_RESP_SIZE.inc_by(resp.data.len() as u64);
resp.set_exec_details(exec_details);
resp.set_exec_details_v2(exec_details_v2);
yield resp;
if finished {
break;
}
}
}
}
tracker.on_finish_all_items();
}
}
/// Handle a stream request and run on the read pool.
///
/// Returns `Err(err)` if the read pool is full. Returns `Ok(stream)` in
/// other cases. The stream inside may produce errors however.
fn handle_stream_request(
&self,
req_ctx: ReqContext,
handler_builder: RequestHandlerBuilder<E::Snap>,
) -> Result<impl futures::stream::Stream<Item = Result<coppb::Response>>> {
let (tx, rx) = mpsc::channel::<Result<coppb::Response>>(self.stream_channel_size);
let priority = req_ctx.context.get_priority();
let metadata = TaskMetadata::from_ctx(req_ctx.context.get_resource_control_context());
let resource_limiter = self.resource_ctl.as_ref().and_then(|r| {
r.get_resource_limiter(
req_ctx
.context
.get_resource_control_context()
.get_resource_group_name(),
req_ctx.context.get_request_source(),
req_ctx
.context
.get_resource_control_context()
.get_override_priority(),
)
});
let key_ranges = req_ctx
.ranges
.iter()
.map(|key_range| (key_range.get_start().to_vec(), key_range.get_end().to_vec()))
.collect();
let resource_tag = self
.resource_tag_factory
.new_tag_with_key_ranges(&req_ctx.context, key_ranges);
let mut allocated_bytes = resource_tag.approximate_heap_size();
let task_id = req_ctx.build_task_id();
let tracker = Box::new(Tracker::new(req_ctx, self.slow_log_threshold));
allocated_bytes += tracker.approximate_mem_size();
let future =
Self::handle_stream_request_impl(self.semaphore.clone(), tracker, handler_builder)
.in_resource_metering_tag(resource_tag)
.then(futures::future::ok::<_, mpsc::SendError>)
.forward(tx)
.unwrap_or_else(|e| {
warn!("coprocessor stream send error"; "error" => %e);
});
self.read_pool_spawn_with_memory_quota_check(
allocated_bytes,
future,
priority,
task_id,
metadata,
resource_limiter,
)?;
Ok(rx)
}
/// Parses and handles a stream request. Returns a stream that produce each
/// result in a `Response` and will never fail. If there are errors during
/// parsing or handling, they will be converted into a `Response` as the
/// only stream item.
#[inline]
pub fn parse_and_handle_stream_request(
&self,
req: coppb::Request,
peer: Option<String>,
) -> impl futures::stream::Stream<Item = coppb::Response> {
let result_of_stream = self
.parse_request_and_check_memory_locks(req, peer, true)
.and_then(|(handler_builder, req_ctx)| {
self.handle_stream_request(req_ctx, handler_builder)
}); // Result<Stream<Resp, Error>, Error>
futures::stream::once(futures::future::ready(result_of_stream)) // Stream<Stream<Resp, Error>, Error>
.try_flatten() // Stream<Resp, Error>
.or_else(|e| futures::future::ok(make_error_response(e))) // Stream<Resp, ()>
.map(|item: std::result::Result<_, ()>| item.unwrap())
}
fn read_pool_spawn_with_memory_quota_check<F>(
&self,
mut allocated_bytes: usize,
future: F,
priority: CommandPri,
task_id: u64,
metadata: TaskMetadata<'_>,
resource_limiter: Option<Arc<ResourceLimiter>>,
) -> Result<()>
where
F: Future<Output = ()> + Send + 'static,
{
allocated_bytes += mem::size_of_val(&future);
let mut owned_quota = OwnedAllocated::new(self.memory_quota.clone());
owned_quota.alloc(allocated_bytes)?;
let fut = future.map(move |_| {
// Release quota after handle completed.
drop(owned_quota);
});
self.read_pool
.spawn(fut, priority, task_id, metadata, resource_limiter)
.map_err(|_| Error::MaxPendingTasksExceeded)
}
}
macro_rules! make_error_response_common {
($resp:expr, $tag:expr, $e:expr) => {{
match $e {
Error::Region(e) => {
$tag = storage::get_tag_from_header(&e);
$resp.set_region_error(e);
}
Error::Locked(info) => {
$tag = "meet_lock";
$resp.set_locked(info);
}
Error::DeadlineExceeded => {
$tag = "deadline_exceeded";
let mut err = errorpb::Error::default();
set_deadline_exceeded_busy_error(&mut err);
err.set_message($e.to_string());
$resp.set_region_error(err);
}
Error::MaxPendingTasksExceeded => {
$tag = "max_pending_tasks_exceeded";
let mut server_is_busy_err = errorpb::ServerIsBusy::default();
server_is_busy_err.set_reason($e.to_string());
let mut errorpb = errorpb::Error::default();
errorpb.set_message($e.to_string());
errorpb.set_server_is_busy(server_is_busy_err);
$resp.set_region_error(errorpb);
}
Error::MemoryQuotaExceeded => {
$tag = "memory_quota_exceeded";
let mut server_is_busy_err = errorpb::ServerIsBusy::default();
server_is_busy_err.set_reason($e.to_string());
let mut errorpb = errorpb::Error::default();
errorpb.set_message($e.to_string());
errorpb.set_server_is_busy(server_is_busy_err);
$resp.set_region_error(errorpb);
}
Error::Other(_) => {
$tag = "other";
warn!("unexpected other error encountered processing coprocessor task";
"error" => ?&$e,
);
$resp.set_other_error($e.to_string());
}
};
COPR_REQ_ERROR.with_label_values(&[$tag]).inc();
}};
}
fn make_error_batch_response(batch_resp: &mut coppb::StoreBatchTaskResponse, e: Error) {
debug!(
"batch cop task error-response";
"err" => %e
);
let tag;
make_error_response_common!(batch_resp, tag, e);
}
fn make_error_response(e: Error) -> coppb::Response {
debug!(
"error-response";
"err" => %e
);
let tag;
let mut resp = coppb::Response::default();
make_error_response_common!(resp, tag, e);
resp
}
#[cfg(test)]
mod tests {
use std::{
sync::{atomic, mpsc},
thread, vec,
};
use futures::executor::{block_on, block_on_stream};
use kvproto::kvrpcpb::IsolationLevel;
use protobuf::Message;
use tipb::{Executor, Expr};
use txn_types::{Key, LockType};
use super::*;
use crate::{
config::CoprReadPoolConfig,
coprocessor::readpool_impl::build_read_pool_for_test,
read_pool::ReadPool,
storage::{kv::RocksEngine, TestEngineBuilder},
};
/// A unary `RequestHandler` that always produces a fixture.
struct UnaryFixture {
handle_duration: Duration,
yieldable: bool,
result: Option<Result<coppb::Response>>,
}
impl UnaryFixture {
pub fn new(result: Result<coppb::Response>) -> UnaryFixture {
UnaryFixture {
handle_duration: Default::default(),
yieldable: false,
result: Some(result),
}
}
pub fn new_with_duration(
result: Result<coppb::Response>,
handle_duration: Duration,
) -> UnaryFixture {
UnaryFixture {
handle_duration,
yieldable: false,