forked from tikv/tikv
/
router.rs
2129 lines (1929 loc) · 73 KB
/
router.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 2022 TiKV Project Authors. Licensed under Apache-2.0.
use std::{
borrow::Borrow,
collections::HashMap,
fmt::Display,
io,
path::{Path, PathBuf},
result,
sync::{
atomic::{AtomicBool, AtomicPtr, AtomicU64, AtomicUsize, Ordering},
Arc, RwLock as SyncRwLock,
},
time::Duration,
};
use engine_traits::{CfName, CF_DEFAULT, CF_LOCK, CF_WRITE};
use external_storage::{BackendConfig, UnpinReader};
use external_storage_export::{create_storage, ExternalStorage};
use futures::io::Cursor;
use kvproto::{
brpb::{DataFileInfo, FileType, Metadata, StreamBackupTaskInfo},
raft_cmdpb::CmdType,
};
use openssl::hash::{Hasher, MessageDigest};
use protobuf::Message;
use raftstore::coprocessor::CmdBatch;
use slog_global::debug;
use tidb_query_datatype::codec::table::decode_table_id;
use tikv_util::{
box_err,
codec::stream_event::EventEncoder,
error, info,
time::{Instant, Limiter},
warn,
worker::Scheduler,
Either, HandyRwLock,
};
use tokio::{
fs::{remove_file, File},
io::{AsyncWriteExt, BufWriter},
sync::{Mutex, RwLock},
};
use tokio_util::compat::TokioAsyncReadCompatExt;
use txn_types::{Key, Lock, TimeStamp, WriteRef};
use super::errors::Result;
use crate::{
annotate,
endpoint::Task,
errors::{ContextualResultExt, Error},
metadata::StreamTask,
metrics::{HANDLE_KV_HISTOGRAM, SKIP_KV_COUNTER},
subscription_track::TwoPhaseResolver,
try_send,
utils::{self, SegmentMap, Slot, SlotMap, StopWatch},
};
const FLUSH_FAILURE_BECOME_FATAL_THRESHOLD: usize = 30;
/// FLUSH_LOG_CONCURRENT_BATCH_COUNT specifies the concurrent count to write to storage.
/// 'Log backup' will produce a large mount of small files during flush interval,
/// and storage could take mistaken if writing all of these files to storage concurrently.
const FLUSH_LOG_CONCURRENT_BATCH_COUNT: usize = 128;
#[derive(Clone, Debug)]
pub enum TaskSelector {
ByName(String),
ByKey(Vec<u8>),
ByRange(Vec<u8>, Vec<u8>),
All,
}
impl TaskSelector {
pub fn reference(&self) -> TaskSelectorRef<'_> {
match self {
TaskSelector::ByName(s) => TaskSelectorRef::ByName(s),
TaskSelector::ByKey(k) => TaskSelectorRef::ByKey(&*k),
TaskSelector::ByRange(s, e) => TaskSelectorRef::ByRange(&*s, &*e),
TaskSelector::All => TaskSelectorRef::All,
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum TaskSelectorRef<'a> {
ByName(&'a str),
ByKey(&'a [u8]),
ByRange(&'a [u8], &'a [u8]),
All,
}
impl<'a> TaskSelectorRef<'a> {
fn matches<'c, 'd>(
self,
task_name: &str,
mut task_range: impl Iterator<Item = (&'c [u8], &'d [u8])>,
) -> bool {
match self {
TaskSelectorRef::ByName(name) => task_name == name,
TaskSelectorRef::ByKey(k) => task_range.any(|(s, e)| utils::is_in_range(k, (&*s, &*e))),
TaskSelectorRef::ByRange(x1, y1) => {
task_range.any(|(x2, y2)| utils::is_overlapping((x1, y1), (&*x2, &*y2)))
}
TaskSelectorRef::All => true,
}
}
}
#[derive(Debug)]
pub struct ApplyEvent {
pub key: Vec<u8>,
pub value: Vec<u8>,
pub cf: CfName,
pub cmd_type: CmdType,
}
#[derive(Debug)]
pub struct ApplyEvents {
events: Vec<ApplyEvent>,
region_id: u64,
// TODO: this field is useless, maybe remove it.
region_resolved_ts: u64,
}
impl ApplyEvents {
/// Convert a [CmdBatch] to a vector of events. Ignoring admin / error commands.
/// At the same time, advancing status of the `Resolver` by those keys.
/// Note: the resolved ts cannot be advanced if there is no command,
/// maybe we also need to update resolved_ts when flushing?
pub fn from_cmd_batch(cmd: CmdBatch, resolver: &mut TwoPhaseResolver) -> Self {
let region_id = cmd.region_id;
let mut result = vec![];
for req in cmd
.cmds
.into_iter()
.filter(|cmd| {
// We will add some log then, this is just a template.
#[allow(clippy::if_same_then_else)]
#[allow(clippy::needless_bool)]
if cmd.response.get_header().has_error() {
// Add some log for skipping the error.
false
} else if cmd.request.has_admin_request() {
// Add some log for skipping the admin request.
false
} else {
true
}
})
.flat_map(|mut cmd| cmd.request.take_requests().into_iter())
{
let cmd_type = req.get_cmd_type();
let (key, value, cf) = match utils::request_to_triple(req) {
Either::Left(t) => t,
Either::Right(req) => {
debug!("ignoring unexpected request"; "type" => ?req.get_cmd_type());
SKIP_KV_COUNTER.inc();
continue;
}
};
if cf == CF_LOCK {
match cmd_type {
CmdType::Put => {
match Lock::parse(&value).map_err(|err| {
annotate!(
err,
"failed to parse lock (value = {})",
utils::redact(&value)
)
}) {
Ok(lock) => {
if utils::should_track_lock(&lock) {
resolver.track_lock(lock.ts, key)
}
}
Err(err) => err.report(format!("region id = {}", region_id)),
}
}
CmdType::Delete => resolver.untrack_lock(&key),
_ => {}
}
continue;
}
let item = ApplyEvent {
key,
value,
cf,
cmd_type,
};
if !item.should_record() {
SKIP_KV_COUNTER.inc();
continue;
}
result.push(item);
}
Self {
events: result,
region_id,
region_resolved_ts: resolver.resolved_ts().into_inner(),
}
}
pub fn push(&mut self, event: ApplyEvent) {
self.events.push(event);
}
pub fn with_capacity(cap: usize, region_id: u64) -> Self {
Self {
events: Vec::with_capacity(cap),
region_id,
region_resolved_ts: 0,
}
}
pub fn size(&self) -> usize {
self.events.iter().map(ApplyEvent::size).sum()
}
pub fn len(&self) -> usize {
self.events.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn group_by<T: std::hash::Hash + Clone + Eq, R: Borrow<T>>(
self,
mut partition_fn: impl FnMut(&ApplyEvent) -> Option<R>,
) -> HashMap<T, Self> {
let mut result: HashMap<T, Self> = HashMap::new();
let event_len = self.len();
for event in self.events {
if let Some(item) = partition_fn(&event) {
if let Some(events) = result.get_mut(<R as Borrow<T>>::borrow(&item)) {
events.events.push(event);
} else {
result.insert(
<R as Borrow<T>>::borrow(&item).clone(),
ApplyEvents {
events: {
// assuming the keys in the same region would probably be in one group.
let mut v = Vec::with_capacity(event_len);
v.push(event);
v
},
region_resolved_ts: self.region_resolved_ts,
region_id: self.region_id,
},
);
}
}
}
result
}
fn partition_by_range(self, ranges: &SegmentMap<Vec<u8>, String>) -> HashMap<String, Self> {
self.group_by(|event| ranges.get_value_by_point(&event.key))
}
fn partition_by_table_key(self) -> HashMap<TempFileKey, Self> {
let region_id = self.region_id;
self.group_by(move |event| Some(TempFileKey::of(event, region_id)))
}
}
impl ApplyEvent {
/// Check whether the key associate to the event is a meta key.
pub fn is_meta(&self) -> bool {
// Can we make things not looking so hacky?
self.key.starts_with(b"m")
}
/// Check whether the event should be recorded.
/// (We would ignore LOCK cf)
pub fn should_record(&self) -> bool {
let cf_can_handle = self.cf == CF_DEFAULT || self.cf == CF_WRITE;
// should we handle prewrite here?
let cmd_can_handle = self.cmd_type == CmdType::Delete || self.cmd_type == CmdType::Put;
cf_can_handle && cmd_can_handle
}
/// The size of the event.
pub fn size(&self) -> usize {
self.key.len() + self.value.len()
}
}
/// The shared version of router.
#[derive(Debug, Clone)]
pub struct Router(Arc<RouterInner>);
impl Router {
/// Create a new router with the temporary folder.
pub fn new(
prefix: PathBuf,
scheduler: Scheduler<Task>,
temp_file_size_limit: u64,
max_flush_interval: Duration,
) -> Self {
Self(Arc::new(RouterInner::new(
prefix,
scheduler,
temp_file_size_limit,
max_flush_interval,
)))
}
}
impl std::ops::Deref for Router {
type Target = RouterInner;
fn deref(&self) -> &Self::Target {
Arc::deref(&self.0)
}
}
/// An Router for Backup Stream.
///
/// It works as a table-filter.
/// 1. route the kv event to different task
/// 2. filter the kv event not belong to the task
// TODO maybe we should introduce table key from tidb_query_datatype module.
pub struct RouterInner {
// TODO find a proper way to record the ranges of table_filter.
// TODO replace all map like things with lock free map, to get rid of the Mutex.
/// The index for search tasks by range.
/// It uses the `start_key` of range as the key.
/// Given there isn't overlapping, we can simply use binary search to find
/// which range a point belongs to.
ranges: SyncRwLock<SegmentMap<Vec<u8>, String>>,
/// The temporary files associated to some task.
tasks: Mutex<HashMap<String, Arc<StreamTaskInfo>>>,
/// The temporary directory for all tasks.
prefix: PathBuf,
/// The handle to Endpoint, we should send `Flush` to endpoint if there are too many temporary files.
scheduler: Scheduler<Task>,
/// The size limit of temporary file per task.
temp_file_size_limit: u64,
/// The max duration the local data can be pending.
max_flush_interval: Duration,
}
impl std::fmt::Debug for RouterInner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RouterInner")
.field("ranges", &self.ranges)
.field("tasks", &self.tasks)
.field("prefix", &self.prefix)
.finish()
}
}
impl RouterInner {
pub fn new(
prefix: PathBuf,
scheduler: Scheduler<Task>,
temp_file_size_limit: u64,
max_flush_interval: Duration,
) -> Self {
RouterInner {
ranges: SyncRwLock::new(SegmentMap::default()),
tasks: Mutex::new(HashMap::default()),
prefix,
scheduler,
temp_file_size_limit,
max_flush_interval,
}
}
/// Find the task for a region. If `end_key` is empty, search from start_key to +inf.
/// It simply search for a random possible overlapping range and get its task.
/// FIXME: If a region crosses many tasks, this can only find one of them.
pub fn find_task_by_range(&self, start_key: &[u8], mut end_key: &[u8]) -> Option<String> {
let r = self.ranges.rl();
if end_key.is_empty() {
end_key = &[0xffu8; 32];
}
r.find_overlapping((start_key, end_key))
.map(|x| x.2.clone())
}
/// Register some ranges associated to some task.
/// Because the observer interface yields encoded data key, the key should be ENCODED DATA KEY too.
/// (i.e. encoded by `Key::from_raw(key).into_encoded()`, [`utils::wrap_key`] could be a shortcut.).
/// We keep ranges in memory to filter kv events not in these ranges.
fn register_ranges(&self, task_name: &str, ranges: Vec<(Vec<u8>, Vec<u8>)>) {
// TODO reigister ranges to filter kv event
// register ranges has two main purpose.
// 1. filter kv event that no need to backup
// 2. route kv event to the corresponding file.
let mut w = self.ranges.write().unwrap();
for range in ranges {
debug!(
"backup stream register observe range";
"task_name" => task_name,
"start_key" => utils::redact(&range.0),
"end_key" => utils::redact(&range.1),
);
w.insert(range, task_name.to_owned());
}
}
fn unregister_ranges(&self, task_name: &str) {
let mut ranges = self.ranges.write().unwrap();
ranges.get_inner().retain(|_, v| v.item != task_name);
}
// register task info ans range info to router
pub async fn register_task(
&self,
mut task: StreamTask,
ranges: Vec<(Vec<u8>, Vec<u8>)>,
) -> Result<()> {
let task_name = task.info.take_name();
// register task info
let prefix_path = self.prefix.join(&task_name);
let stream_task =
StreamTaskInfo::new(prefix_path, task, self.max_flush_interval, ranges.clone()).await?;
self.tasks
.lock()
.await
.insert(task_name.clone(), Arc::new(stream_task));
// register ragnes
self.register_ranges(&task_name, ranges);
Ok(())
}
pub async fn unregister_task(&self, task_name: &str) -> Option<StreamBackupTaskInfo> {
self.tasks.lock().await.remove(task_name).map(|t| {
info!(
"backup stream unregister task";
"task" => task_name,
);
self.unregister_ranges(task_name);
t.task.info.clone()
})
}
/// get the task name by a key.
pub fn get_task_by_key(&self, key: &[u8]) -> Option<String> {
let r = self.ranges.read().unwrap();
r.get_value_by_point(key).cloned()
}
pub async fn select_task(&self, selector: TaskSelectorRef<'_>) -> Vec<String> {
let s = self.tasks.lock().await;
s.iter()
.filter(|(name, info)| {
selector.matches(
name.as_str(),
info.ranges
.iter()
.map(|(s, e)| (s.as_slice(), e.as_slice())),
)
})
.map(|(name, _)| name.to_owned())
.collect()
}
#[cfg(test)]
pub(crate) async fn must_mut_task_info<F>(&self, task_name: &str, mutator: F)
where
F: FnOnce(&mut StreamTaskInfo),
{
let mut tasks = self.tasks.lock().await;
let t = tasks.remove(task_name);
let mut raw = Arc::try_unwrap(t.unwrap()).unwrap();
mutator(&mut raw);
tasks.insert(task_name.to_owned(), Arc::new(raw));
}
pub async fn get_task_info(&self, task_name: &str) -> Result<Arc<StreamTaskInfo>> {
let task_info = match self.tasks.lock().await.get(task_name) {
Some(t) => t.clone(),
None => {
info!("backup stream no task"; "task" => ?task_name);
return Err(Error::NoSuchTask {
task_name: task_name.to_string(),
});
}
};
Ok(task_info)
}
async fn on_event(&self, task: String, events: ApplyEvents) -> Result<()> {
let task_info = self.get_task_info(&task).await?;
task_info.on_events(events).await?;
// When this event make the size of temporary files exceeds the size limit, make a flush.
// Note that we only flush if the size is less than the limit before the event,
// or we may send multiplied flush requests.
debug!(
"backup stream statics size";
"task" => ?task,
"next_size" => task_info.total_size(),
"size_limit" => self.temp_file_size_limit,
);
let cur_size = task_info.total_size();
if cur_size > self.temp_file_size_limit && !task_info.is_flushing() {
info!("try flushing task"; "task" => %task, "size" => %cur_size);
if task_info.set_flushing_status_cas(false, true).is_ok() {
if let Err(e) = self.scheduler.schedule(Task::Flush(task)) {
error!("backup stream schedule task failed"; "error" => ?e);
task_info.set_flushing_status(false);
}
}
}
Ok(())
}
pub async fn on_events(&self, kv: ApplyEvents) -> Vec<(String, Result<()>)> {
use futures::FutureExt;
HANDLE_KV_HISTOGRAM.observe(kv.len() as _);
let partitioned_events = kv.partition_by_range(&self.ranges.rl());
let tasks = partitioned_events
.into_iter()
.map(|(task, events)| self.on_event(task.clone(), events).map(move |r| (task, r)));
futures::future::join_all(tasks).await
}
/// flush the specified task, once once success, return the min resolved ts of this flush.
/// returns `None` if failed.
pub async fn do_flush(
&self,
task_name: &str,
store_id: u64,
resolve_to: TimeStamp,
) -> Option<u64> {
let task = self.tasks.lock().await.get(task_name).cloned();
match task {
Some(task_info) => {
let result = task_info.do_flush(store_id, resolve_to).await;
// set false to flushing whether success or fail
task_info.set_flushing_status(false);
if let Err(e) = result {
e.report("failed to flush task.");
warn!("backup steam do flush fail"; "err" => ?e);
if task_info.flush_failure_count() > FLUSH_FAILURE_BECOME_FATAL_THRESHOLD {
// NOTE: Maybe we'd better record all errors and send them to the client?
try_send!(
self.scheduler,
Task::FatalError(
TaskSelector::ByName(task_name.to_owned()),
Box::new(e)
)
);
}
return None;
}
// if succeed in flushing, update flush_time. Or retry do_flush immediately.
task_info.update_flush_time();
result.ok().flatten()
}
_ => None,
}
}
pub async fn update_global_checkpoint(
&self,
task_name: &str,
global_checkpoint: u64,
store_id: u64,
) -> Result<bool> {
self.get_task_info(task_name)
.await?
.update_global_checkpoint(global_checkpoint, store_id)
.await
}
/// tick aims to flush log/meta to extern storage periodically.
pub async fn tick(&self) {
for (name, task_info) in self.tasks.lock().await.iter() {
if let Err(e) = self
.scheduler
.schedule(Task::UpdateGlobalCheckpoint(name.to_string()))
{
error!("backup stream schedule task failed"; "error" => ?e);
}
// if stream task need flush this time, schedule Task::Flush, or update time justly.
if task_info.should_flush() && task_info.set_flushing_status_cas(false, true).is_ok() {
info!(
"backup stream trigger flush task by tick";
"task" => ?task_info,
);
if let Err(e) = self.scheduler.schedule(Task::Flush(name.clone())) {
error!("backup stream schedule task failed"; "error" => ?e);
task_info.set_flushing_status(false);
}
}
}
}
}
/// The handle of a temporary file.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
struct TempFileKey {
table_id: i64,
region_id: u64,
cf: CfName,
cmd_type: CmdType,
is_meta: bool,
}
pub enum FormatType {
Date,
Hour,
}
impl TempFileKey {
/// Create the key for an event. The key can be used to find which temporary file the event should be stored.
fn of(kv: &ApplyEvent, region_id: u64) -> Self {
let table_id = if kv.is_meta() {
// Force table id of meta key be zero.
0
} else {
// When we cannot extract the table key, use 0 for the table key(perhaps we insert meta key here.).
// Can we elide the copy here(or at least, take a slice of key instead of decoding the whole key)?
Key::from_encoded_slice(&kv.key)
.into_raw()
.ok()
.and_then(|decoded_key| decode_table_id(&decoded_key).ok())
.unwrap_or(0)
};
Self {
is_meta: kv.is_meta(),
table_id,
region_id,
cf: kv.cf,
cmd_type: kv.cmd_type,
}
}
fn get_file_type(&self) -> FileType {
let file_type = match self.cmd_type {
CmdType::Put => FileType::Put,
CmdType::Delete => FileType::Delete,
_ => {
warn!("error cmdtype"; "cmdtype" => ?self.cmd_type);
panic!("error CmdType");
}
};
file_type
}
/// The full name of the file owns the key.
fn temp_file_name(&self) -> String {
if self.is_meta {
format!(
"meta_{:08}_{}_{:?}_{}.temp.log",
self.region_id,
self.cf,
self.cmd_type,
TimeStamp::physical_now(),
)
} else {
format!(
"{:08}_{:08}_{}_{:?}_{}.temp.log",
self.table_id,
self.region_id,
self.cf,
self.cmd_type,
TimeStamp::physical_now(),
)
}
}
fn format_date_time(ts: u64, t: FormatType) -> impl Display {
use chrono::prelude::*;
let millis = TimeStamp::physical(ts.into());
let dt = Utc.timestamp_millis(millis as _);
#[cfg(feature = "failpoints")]
{
fail::fail_point!("stream_format_date_time", |s| {
return dt
.format(&s.unwrap_or_else(|| "%Y%m".to_owned()))
.to_string();
});
match t {
FormatType::Date => dt.format("%Y%m%d").to_string(),
FormatType::Hour => dt.format("%H").to_string(),
}
}
#[cfg(not(feature = "failpoints"))]
match t {
FormatType::Date => dt.format("%Y%m%d"),
FormatType::Hour => dt.format("%H"),
}
}
/// path_to_log_file specifies the path of record log.
/// eg. "v1/${date}/${hour}/${store_id}/t00000071/434098800931373064-f0251bd5-1441-499a-8f53-adc0d1057a73.log"
fn path_to_log_file(&self, store_id: u64, min_ts: u64, max_ts: u64) -> String {
format!(
"v1/{}/{}/{}/t{:08}/{:012}-{}.log",
// We may delete a range of files, so using the max_ts for preventing remove some records wrong.
Self::format_date_time(max_ts, FormatType::Date),
Self::format_date_time(max_ts, FormatType::Hour),
store_id,
self.table_id,
min_ts,
uuid::Uuid::new_v4()
)
}
/// path_to_schema_file specifies the path of schema log.
/// eg. "v1/${date}/${hour}/${store_id}/schema-meta/434055683656384515-cc3cb7a3-e03b-4434-ab6c-907656fddf67.log"
fn path_to_schema_file(store_id: u64, min_ts: u64, max_ts: u64) -> String {
format!(
"v1/{}/{}/{}/schema-meta/{:012}-{}.log",
Self::format_date_time(max_ts, FormatType::Date),
Self::format_date_time(max_ts, FormatType::Hour),
store_id,
min_ts,
uuid::Uuid::new_v4(),
)
}
fn file_name(&self, store_id: u64, min_ts: TimeStamp, max_ts: TimeStamp) -> String {
if self.is_meta {
Self::path_to_schema_file(store_id, min_ts.into_inner(), max_ts.into_inner())
} else {
self.path_to_log_file(store_id, min_ts.into_inner(), max_ts.into_inner())
}
}
}
pub struct StreamTaskInfo {
pub(crate) task: StreamTask,
/// support external storage. eg local/s3.
pub(crate) storage: Arc<dyn ExternalStorage>,
/// The listening range of the task.
ranges: Vec<(Vec<u8>, Vec<u8>)>,
/// The parent directory of temporary files.
temp_dir: PathBuf,
/// The temporary file index. Both meta (m prefixed keys) and data (t prefixed keys).
files: SlotMap<TempFileKey, DataFile>,
/// flushing_files contains files pending flush.
flushing_files: RwLock<Vec<(TempFileKey, Slot<DataFile>, DataFileInfo)>>,
/// last_flush_ts represents last time this task flushed to storage.
last_flush_time: AtomicPtr<Instant>,
/// flush_interval represents the tick interval of flush, setting by users.
flush_interval: Duration,
/// The min resolved TS of all regions involved.
min_resolved_ts: TimeStamp,
/// Total size of all temporary files in byte.
total_size: AtomicUsize,
/// This should only be set to `true` by `compare_and_set(current=false, value=ture)`.
/// The thread who setting it to `true` takes the responsibility of sending the request to the
/// scheduler for flushing the files then.
///
/// If the request failed, that thread can set it to `false` back then.
flushing: AtomicBool,
/// This counts how many times this task has failed to flush.
flush_fail_count: AtomicUsize,
/// global checkpoint ts for this task.
global_checkpoint_ts: AtomicU64,
}
impl Drop for StreamTaskInfo {
fn drop(&mut self) {
let (success, failed): (Vec<_>, Vec<_>) = self
.flushing_files
.get_mut()
.drain(..)
.map(|(a, b, _)| (a, b))
.chain(self.files.get_mut().drain())
.map(|(_, f)| f.into_inner().local_path)
.map(std::fs::remove_file)
.partition(|r| r.is_ok());
info!("stream task info dropped, removing temp files"; "success" => %success.len(), "failure" => %failed.len())
}
}
impl std::fmt::Debug for StreamTaskInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StreamTaskInfo")
.field("task", &self.task.info.name)
.field("temp_dir", &self.temp_dir)
.field("min_resolved_ts", &self.min_resolved_ts)
.field("total_size", &self.total_size)
.field("flushing", &self.flushing)
.finish()
}
}
impl StreamTaskInfo {
/// Create a new temporary file set at the `temp_dir`.
pub async fn new(
temp_dir: PathBuf,
task: StreamTask,
flush_interval: Duration,
ranges: Vec<(Vec<u8>, Vec<u8>)>,
) -> Result<Self> {
tokio::fs::create_dir_all(&temp_dir).await?;
let storage = Arc::from(create_storage(
task.info.get_storage(),
BackendConfig::default(),
)?);
let start_ts = task.info.get_start_ts();
Ok(Self {
task,
storage,
temp_dir,
ranges,
min_resolved_ts: TimeStamp::max(),
files: SlotMap::default(),
flushing_files: RwLock::default(),
last_flush_time: AtomicPtr::new(Box::into_raw(Box::new(Instant::now()))),
flush_interval,
total_size: AtomicUsize::new(0),
flushing: AtomicBool::new(false),
flush_fail_count: AtomicUsize::new(0),
global_checkpoint_ts: AtomicU64::new(start_ts),
})
}
async fn on_events_of_key(&self, key: TempFileKey, events: ApplyEvents) -> Result<()> {
if let Some(f) = self.files.read().await.get(&key) {
self.total_size
.fetch_add(f.lock().await.on_events(events).await?, Ordering::SeqCst);
return Ok(());
}
// slow path: try to insert the element.
let mut w = self.files.write().await;
// double check before insert. there may be someone already insert that
// when we are waiting for the write lock.
// slience the lint advising us to use the `Entry` API which may introduce copying.
#[allow(clippy::map_entry)]
if !w.contains_key(&key) {
let path = self.temp_dir.join(key.temp_file_name());
let val = Mutex::new(DataFile::new(path).await?);
w.insert(key, val);
}
let f = w.get(&key).unwrap();
self.total_size
.fetch_add(f.lock().await.on_events(events).await?, Ordering::SeqCst);
Ok(())
}
/// Append a event to the files. This wouldn't trigger `fsync` syscall.
/// i.e. No guarantee of persistence.
pub async fn on_events(&self, kv: ApplyEvents) -> Result<()> {
use futures::FutureExt;
let now = Instant::now_coarse();
futures::future::try_join_all(kv.partition_by_table_key().into_iter().map(
|(key, events)| {
self.on_events_of_key(key, events)
.map(move |r| r.context(format_args!("when handling the file key {:?}", key)))
},
))
.await?;
crate::metrics::ON_EVENT_COST_HISTOGRAM
.with_label_values(&["write_to_tempfile"])
.observe(now.saturating_elapsed_secs());
Ok(())
}
pub fn get_last_flush_time(&self) -> Instant {
unsafe { *(self.last_flush_time.load(Ordering::SeqCst) as *const Instant) }
}
pub fn total_size(&self) -> u64 {
self.total_size.load(Ordering::SeqCst) as _
}
/// Flush all template files and generate corresponding metadata.
pub async fn generate_metadata(&self, store_id: u64) -> Result<MetadataInfo> {
let w = self.flushing_files.read().await;
// Let's flush all files first...
futures::future::join_all(w.iter().map(|(_, f, _)| async move {
let file = &mut f.lock().await.inner;
file.flush().await?;
file.get_ref().sync_all().await?;
Result::Ok(())
}))
.await
.into_iter()
.map(|r| r.map_err(Error::from))
.fold(Ok(()), Result::and)?;
let mut metadata = MetadataInfo::with_capacity(w.len());
metadata.set_store_id(store_id);
for (_, _, file_meta) in w.iter() {
metadata.push(file_meta.to_owned())
}
Ok(metadata)
}
pub fn set_flushing_status_cas(&self, expect: bool, new: bool) -> result::Result<bool, bool> {
self.flushing
.compare_exchange(expect, new, Ordering::SeqCst, Ordering::SeqCst)
}
pub fn set_flushing_status(&self, set_flushing: bool) {
self.flushing.store(set_flushing, Ordering::SeqCst);
}
pub fn update_flush_time(&self) {
let ptr = self
.last_flush_time
.swap(Box::into_raw(Box::new(Instant::now())), Ordering::SeqCst);
// manual gc last instant
unsafe { Box::from_raw(ptr) };
}
pub fn should_flush(&self) -> bool {
// When it doesn't flush since 0.8x of auto-flush interval, we get ready to start flushing.
// So that we will get a buffer for the cost of actual flushing.
self.get_last_flush_time().saturating_elapsed_secs()
>= self.flush_interval.as_secs_f64() * 0.8
}
pub fn is_flushing(&self) -> bool {
self.flushing.load(Ordering::SeqCst)
}
/// move need-flushing files to flushing_files.
pub async fn move_to_flushing_files(&self, store_id: u64) -> Result<&Self> {
// if flushing_files is not empty, which represents this flush is a retry operation.
if !self.flushing_files.read().await.is_empty() {
return Ok(self);
}
let mut w = self.files.write().await;
let mut fw = self.flushing_files.write().await;
for (k, v) in w.drain() {
// we should generate file metadata(calculate sha256) when moving file.
// because sha256 calculation is a unsafe move operation.
// we cannot re-calculate it in retry.
// TODO refactor move_to_flushing_files and generate_metadata
let file_meta = v.lock().await.generate_metadata(&k, store_id)?;
fw.push((k, v, file_meta));
}
Ok(self)
}
pub async fn clear_flushing_files(&self) {
for (_, v, _) in self.flushing_files.write().await.drain(..) {
let data_file = v.lock().await;
debug!("removing data file"; "size" => %data_file.file_size, "name" => %data_file.local_path.display());
self.total_size
.fetch_sub(data_file.file_size, Ordering::SeqCst);
if let Err(e) = data_file.remove_temp_file().await {
// if remove template failed, just skip it.
info!("remove template file"; "err" => ?e);
}
}
}
async fn flush_log_file_to(
storage: Arc<dyn ExternalStorage>,
file: &Mutex<DataFile>,
) -> Result<()> {
let data_file = file.lock().await;
// to do: limiter to storage
let limiter = Limiter::builder(std::f64::INFINITY).build();
let reader = File::open(data_file.local_path.clone()).await?;
let stat = reader.metadata().await?;
let reader = UnpinReader(Box::new(limiter.limit(reader.compat())));
let filepath = &data_file.storage_path;
let est_len = stat.len();
let ret = storage.write(filepath, reader, est_len).await;
match ret {
Ok(_) => {
debug!(
"backup stream flush success";
"tmp file" => ?data_file.local_path,
"storage file" => ?filepath,
);
}
Err(e) => {
warn!("backup stream flush failed";
"file" => ?data_file.local_path,
"est_len" => ?est_len,
"err" => ?e,
);
return Err(Error::Io(e));
}
}
Ok(())
}
pub async fn flush_log(&self) -> Result<()> {
// if failed to write storage, we should retry write flushing_files.
let storage = self.storage.clone();