/
snap.rs
2182 lines (1983 loc) · 70.5 KB
/
snap.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 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
use std::error;
use std::io::{self, ErrorKind, Read, Write};
use std::fmt::{self, Display, Formatter};
use std::fs::{self, Metadata};
use std::sync::{Arc, RwLock};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::path::Path;
use std::result;
use std::str;
use std::time;
use std::thread;
use protobuf::Message;
use rocksdb::{CFHandle, Writable, WriteBatch, DB};
use kvproto::eraftpb::Snapshot as RaftSnapshot;
use kvproto::metapb::Region;
use kvproto::raft_serverpb::RaftSnapshotData;
use raftstore::Result as RaftStoreResult;
use raftstore::errors::Error as RaftStoreError;
use raftstore::store::Msg;
use raftstore::store::util::check_key_in_region;
use storage::{CfName, CF_DEFAULT, CF_LOCK, CF_WRITE};
use util::transport::SendCh;
use util::HandyRwLock;
use util::collections::{HashMap, HashMapEntry as Entry};
use util::codec::bytes::{BytesEncoder, CompactBytesDecoder};
use raftstore::store::engine::{Iterable, Snapshot as DbSnapshot};
use raftstore::store::keys::{self, enc_end_key, enc_start_key};
use raftstore::store::metrics::{SNAPSHOT_BUILD_TIME_HISTOGRAM, SNAPSHOT_CF_KV_COUNT,
SNAPSHOT_CF_SIZE};
use raftstore::store::peer_storage::JOB_STATUS_CANCELLING;
// Data in CF_RAFT should be excluded for a snapshot.
pub const SNAPSHOT_CFS: &'static [CfName] = &[CF_DEFAULT, CF_LOCK, CF_WRITE];
/// Name prefix for the self-generated snapshot file.
const SNAP_GEN_PREFIX: &'static str = "gen";
/// Name prefix for the received snapshot file.
const SNAP_REV_PREFIX: &'static str = "rev";
const TMP_FILE_SUFFIX: &'static str = ".tmp";
const SST_FILE_SUFFIX: &'static str = ".sst";
const DELETE_RETRY_MAX_TIMES: u32 = 6;
const DELETE_RETRY_TIME_MILLIS: u64 = 500;
quick_error! {
#[derive(Debug)]
pub enum Error {
Abort {
description("abort")
display("abort")
}
Other(err: Box<error::Error + Sync + Send>) {
from()
cause(err.as_ref())
description(err.description())
display("snap failed {:?}", err)
}
}
}
pub type Result<T> = result::Result<T, Error>;
// CF_LOCK is relatively small, so we use plain file for performance issue.
#[inline]
fn plain_file_used(cf: &str) -> bool {
cf == CF_LOCK
}
#[inline]
pub fn check_abort(status: &AtomicUsize) -> Result<()> {
if status.load(Ordering::Relaxed) == JOB_STATUS_CANCELLING {
return Err(Error::Abort);
}
Ok(())
}
#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct SnapKey {
pub region_id: u64,
pub term: u64,
pub idx: u64,
}
impl SnapKey {
#[inline]
pub fn new(region_id: u64, term: u64, idx: u64) -> SnapKey {
SnapKey {
region_id: region_id,
term: term,
idx: idx,
}
}
pub fn from_region_snap(region_id: u64, snap: &RaftSnapshot) -> SnapKey {
let index = snap.get_metadata().get_index();
let term = snap.get_metadata().get_term();
SnapKey::new(region_id, term, index)
}
pub fn from_snap(snap: &RaftSnapshot) -> io::Result<SnapKey> {
let mut snap_data = RaftSnapshotData::new();
if let Err(e) = snap_data.merge_from_bytes(snap.get_data()) {
return Err(io::Error::new(ErrorKind::Other, e));
}
Ok(SnapKey::from_region_snap(
snap_data.get_region().get_id(),
snap,
))
}
}
impl Display for SnapKey {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}_{}_{}", self.region_id, self.term, self.idx)
}
}
#[derive(Default)]
pub struct SnapshotStatistics {
pub size: u64,
pub kv_count: usize,
}
impl SnapshotStatistics {
pub fn new() -> SnapshotStatistics {
SnapshotStatistics {
..Default::default()
}
}
}
pub struct ApplyOptions {
pub db: Arc<DB>,
pub region: Region,
pub abort: Arc<AtomicUsize>,
pub write_batch_size: usize,
}
/// `Snapshot` is a trait for snapshot.
/// It's used in these scenarios:
/// 1. build local snapshot
/// 2. read local snapshot and then replicate it to remote raftstores
/// 3. receive snapshot from remote raftstore and write it to local storage
/// 4. apply snapshot
/// 5. snapshot gc
pub trait Snapshot: Read + Write + Send {
fn build(
&mut self,
snap: &DbSnapshot,
region: &Region,
snap_data: &mut RaftSnapshotData,
stat: &mut SnapshotStatistics,
deleter: Box<SnapshotDeleter>,
) -> RaftStoreResult<()>;
fn path(&self) -> &str;
fn exists(&self) -> bool;
fn delete(&self);
fn meta(&self) -> io::Result<Metadata>;
fn total_size(&self) -> io::Result<u64>;
fn save(&mut self) -> io::Result<()>;
fn apply(&mut self, options: ApplyOptions) -> Result<()>;
}
// A helper function to copy snapshot.
// Only used in tests.
pub fn copy_snapshot(mut from: Box<Snapshot>, mut to: Box<Snapshot>) -> io::Result<()> {
if !to.exists() {
try!(io::copy(&mut from, &mut to));
try!(to.save());
}
Ok(())
}
/// `SnapshotDeleter` is a trait for deleting snapshot.
/// It's used to ensure that the snapshot deletion happens under the protection of locking
/// to avoid race case for concurrent read/write.
pub trait SnapshotDeleter {
// Return true if it successfully delete the specified snapshot.
fn delete_snapshot(&self, key: &SnapKey, snap: &Snapshot, check_entry: bool) -> bool;
}
// Try to delete the specified snapshot using deleter, return true if the deletion is done.
pub fn retry_delete_snapshot(
deleter: Box<SnapshotDeleter>,
key: &SnapKey,
snap: &Snapshot,
) -> bool {
let d = time::Duration::from_millis(DELETE_RETRY_TIME_MILLIS);
for _ in 0..DELETE_RETRY_MAX_TIMES {
if deleter.delete_snapshot(key, snap, true) {
return true;
}
thread::sleep(d);
}
false
}
use std::fs::{File, OpenOptions};
use std::path::PathBuf;
use std::time::Instant;
use crc::crc32::{self, Digest, Hasher32};
use protobuf::RepeatedField;
use kvproto::raft_serverpb::{SnapshotCFFile, SnapshotMeta};
use rocksdb::{DBCompressionType, EnvOptions, IngestExternalFileOptions, SstFileWriter};
use util::rocksdb;
use util::time::duration_to_sec;
use util::file::{delete_file_if_exist, file_exists, get_file_size};
use util::rocksdb::get_fastest_supported_compression_type;
pub const SNAPSHOT_VERSION: u64 = 2;
const META_FILE_SUFFIX: &'static str = ".meta";
const DIGEST_BUFFER_SIZE: usize = 10240;
fn calc_crc32(p: &PathBuf) -> io::Result<u32> {
let mut digest = Digest::new(crc32::IEEE);
let mut f = try!(OpenOptions::new().read(true).open(&p));
let mut buf = vec![0; DIGEST_BUFFER_SIZE];
loop {
match f.read(&mut buf[..]) {
Ok(0) => {
return Ok(digest.sum32());
}
Ok(n) => {
digest.write(&buf[..n]);
}
Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
Err(err) => return Err(err),
}
}
}
fn gen_snapshot_meta(cf_files: &[CfFile]) -> RaftStoreResult<SnapshotMeta> {
let mut meta = Vec::with_capacity(cf_files.len());
for cf_file in cf_files {
if SNAPSHOT_CFS.iter().find(|&cf| cf_file.cf == *cf).is_none() {
return Err(box_err!(
"failed to encode invalid snapshot cf {}",
cf_file.cf
));
}
let mut cf_file_meta = SnapshotCFFile::new();
cf_file_meta.set_cf(cf_file.cf.to_owned());
cf_file_meta.set_size(cf_file.size);
cf_file_meta.set_checksum(cf_file.checksum);
meta.push(cf_file_meta);
}
let mut snapshot_meta = SnapshotMeta::new();
snapshot_meta.set_cf_files(RepeatedField::from_vec(meta));
Ok(snapshot_meta)
}
fn check_file_size(path: &PathBuf, expected_size: u64) -> RaftStoreResult<()> {
let size = try!(get_file_size(path));
if size != expected_size {
return Err(box_err!(
"invalid size {} for snapshot cf file {}, expected {}",
size,
path.display(),
expected_size
));
}
Ok(())
}
fn check_file_checksum(path: &PathBuf, expected_checksum: u32) -> RaftStoreResult<()> {
let checksum = try!(calc_crc32(path));
if checksum != expected_checksum {
return Err(box_err!(
"invalid checksum {} for snapshot cf file {}, expected {}",
checksum,
path.display(),
expected_checksum
));
}
Ok(())
}
fn check_file_size_and_checksum(
path: &PathBuf,
expected_size: u64,
expected_checksum: u32,
) -> RaftStoreResult<()> {
check_file_size(path, expected_size).and_then(|_| check_file_checksum(path, expected_checksum))
}
#[derive(Default)]
struct CfFile {
pub cf: CfName,
pub path: PathBuf,
pub tmp_path: PathBuf,
pub sst_writer: Option<SstFileWriter>,
pub file: Option<File>,
pub kv_count: u64,
pub size: u64,
pub written_size: u64,
pub checksum: u32,
pub write_digest: Option<Digest>,
}
#[derive(Default)]
struct MetaFile {
pub meta: SnapshotMeta,
pub path: PathBuf,
pub file: Option<File>,
// for writing snapshot
pub tmp_path: PathBuf,
}
pub struct Snap {
key: SnapKey,
display_path: String,
cf_files: Vec<CfFile>,
cf_index: usize,
meta_file: MetaFile,
size_track: Arc<RwLock<u64>>,
}
impl Snap {
fn new<T: Into<PathBuf>>(
dir: T,
key: &SnapKey,
size_track: Arc<RwLock<u64>>,
is_sending: bool,
to_build: bool,
deleter: Box<SnapshotDeleter>,
) -> RaftStoreResult<Snap> {
let dir_path = dir.into();
if !dir_path.exists() {
try!(fs::create_dir_all(dir_path.as_path()));
}
let snap_prefix = if is_sending {
SNAP_GEN_PREFIX
} else {
SNAP_REV_PREFIX
};
let prefix = format!("{}_{}", snap_prefix, key);
let display_path = Snap::get_display_path(&dir_path, &prefix);
let mut cf_files = Vec::with_capacity(SNAPSHOT_CFS.len());
for cf in SNAPSHOT_CFS {
let filename = format!("{}_{}{}", prefix, cf, SST_FILE_SUFFIX);
let path = dir_path.join(&filename);
let tmp_path = dir_path.join(format!("{}{}", filename, TMP_FILE_SUFFIX));
let cf_file = CfFile {
cf: cf,
path: path,
tmp_path: tmp_path,
..Default::default()
};
cf_files.push(cf_file);
}
let meta_filename = format!("{}{}", prefix, META_FILE_SUFFIX);
let meta_path = dir_path.join(&meta_filename);
let meta_tmp_path = dir_path.join(format!("{}{}", meta_filename, TMP_FILE_SUFFIX));
let meta_file = MetaFile {
path: meta_path,
tmp_path: meta_tmp_path,
..Default::default()
};
let mut s = Snap {
key: key.clone(),
display_path: display_path,
cf_files: cf_files,
cf_index: 0,
meta_file: meta_file,
size_track: size_track,
};
// load snapshot meta if meta_file exists
if file_exists(&s.meta_file.path) {
if let Err(e) = s.load_snapshot_meta() {
if !to_build {
return Err(e);
}
warn!(
"failed to load existent snapshot meta when try to build {}: {:?}",
s.path(),
e
);
if !retry_delete_snapshot(deleter, key, &s) {
warn!(
"failed to delete snapshot {} because it's already registered elsewhere",
s.path()
);
return Err(e);
}
}
}
Ok(s)
}
pub fn new_for_building<T: Into<PathBuf>>(
dir: T,
key: &SnapKey,
snap: &DbSnapshot,
size_track: Arc<RwLock<u64>>,
deleter: Box<SnapshotDeleter>,
) -> RaftStoreResult<Snap> {
let mut s = try!(Snap::new(dir, key, size_track, true, true, deleter));
try!(s.init_for_building(snap));
Ok(s)
}
pub fn new_for_sending<T: Into<PathBuf>>(
dir: T,
key: &SnapKey,
size_track: Arc<RwLock<u64>>,
deleter: Box<SnapshotDeleter>,
) -> RaftStoreResult<Snap> {
let mut s = try!(Snap::new(dir, key, size_track, true, false, deleter));
if !s.exists() {
// Skip the initialization below if it doesn't exists.
return Ok(s);
}
for cf_file in &mut s.cf_files {
// initialize cf file size and reader
if cf_file.size > 0 {
let file = try!(File::open(&cf_file.path));
cf_file.file = Some(file);
}
}
Ok(s)
}
pub fn new_for_receiving<T: Into<PathBuf>>(
dir: T,
key: &SnapKey,
snapshot_meta: SnapshotMeta,
size_track: Arc<RwLock<u64>>,
deleter: Box<SnapshotDeleter>,
) -> RaftStoreResult<Snap> {
let mut s = try!(Snap::new(dir, key, size_track, false, false, deleter));
try!(s.set_snapshot_meta(snapshot_meta));
if s.exists() {
return Ok(s);
}
for cf_file in &mut s.cf_files {
if cf_file.size == 0 {
continue;
}
let f = try!(
OpenOptions::new()
.write(true)
.create_new(true)
.open(&cf_file.tmp_path)
);
cf_file.file = Some(f);
cf_file.write_digest = Some(Digest::new(crc32::IEEE));
}
let f = try!(
OpenOptions::new()
.write(true)
.create_new(true)
.open(&s.meta_file.tmp_path)
);
s.meta_file.file = Some(f);
Ok(s)
}
pub fn new_for_applying<T: Into<PathBuf>>(
dir: T,
key: &SnapKey,
size_track: Arc<RwLock<u64>>,
deleter: Box<SnapshotDeleter>,
) -> RaftStoreResult<Snap> {
let s = try!(Snap::new(dir, key, size_track, false, false, deleter));
Ok(s)
}
fn init_for_building(&mut self, snap: &DbSnapshot) -> RaftStoreResult<()> {
if self.exists() {
return Ok(());
}
for cf_file in &mut self.cf_files {
if plain_file_used(cf_file.cf) {
let f = try!(
OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&cf_file.tmp_path)
);
cf_file.file = Some(f);
} else {
let handle = try!(snap.cf_handle(cf_file.cf));
let mut io_options = snap.get_db().get_options_cf(handle).clone();
io_options.compression(get_fastest_supported_compression_type());
// in rocksdb 5.5.1, SstFileWriter will try to use bottommost_compression and
// compression_per_level first, so to make sure our specified compression type
// being used, we must set them empty or disabled.
io_options.compression_per_level(&[]);
io_options.bottommost_compression(DBCompressionType::Disable);
let mut writer = SstFileWriter::new(EnvOptions::new(), io_options);
box_try!(writer.open(cf_file.tmp_path.as_path().to_str().unwrap()));
cf_file.sst_writer = Some(writer);
}
}
let file = try!(
OpenOptions::new()
.write(true)
.create_new(true)
.open(&self.meta_file.tmp_path)
);
self.meta_file.file = Some(file);
Ok(())
}
fn read_snapshot_meta(&mut self) -> RaftStoreResult<SnapshotMeta> {
let size = try!(get_file_size(&self.meta_file.path));
let mut file = try!(File::open(&self.meta_file.path));
let mut buf = Vec::with_capacity(size as usize);
try!(file.read_to_end(&mut buf));
let mut snapshot_meta = SnapshotMeta::new();
try!(snapshot_meta.merge_from_bytes(&buf));
Ok(snapshot_meta)
}
fn set_snapshot_meta(&mut self, snapshot_meta: SnapshotMeta) -> RaftStoreResult<()> {
if snapshot_meta.get_cf_files().len() != self.cf_files.len() {
return Err(box_err!(
"invalid cf number of snapshot meta, expect {}, got {}",
SNAPSHOT_CFS.len(),
snapshot_meta.get_cf_files().len()
));
}
for (i, cf_file) in self.cf_files.iter_mut().enumerate() {
let meta = snapshot_meta.get_cf_files().get(i).unwrap();
if meta.get_cf() != cf_file.cf {
return Err(box_err!(
"invalid {} cf in snapshot meta, expect {}, got {}",
i,
cf_file.cf,
meta.get_cf()
));
}
if file_exists(&cf_file.path) {
// Check only the file size for `exists()` to work correctly.
try!(check_file_size(&cf_file.path, meta.get_size()));
}
cf_file.size = meta.get_size();
cf_file.checksum = meta.get_checksum();
}
self.meta_file.meta = snapshot_meta;
Ok(())
}
fn load_snapshot_meta(&mut self) -> RaftStoreResult<()> {
let snapshot_meta = try!(self.read_snapshot_meta());
try!(self.set_snapshot_meta(snapshot_meta));
// check if there is a data corruption when the meta file exists
// but cf files are deleted.
if !self.exists() {
return Err(box_err!(
"snapshot {} is corrupted, some cf file is missing",
self.path()
));
}
Ok(())
}
fn get_display_path(dir_path: &PathBuf, prefix: &str) -> String {
let cf_names = "(".to_owned() + &SNAPSHOT_CFS.join("|") + ")";
format!(
"{}/{}_{}{}",
dir_path.display(),
prefix,
cf_names,
SST_FILE_SUFFIX
)
}
fn validate(&self) -> RaftStoreResult<()> {
for cf_file in &self.cf_files {
if cf_file.size == 0 {
// Skip empty file. The checksum of this cf file should be 0 and
// this is checked when loading the snapshot meta.
continue;
}
try!(check_file_size_and_checksum(
&cf_file.path,
cf_file.size,
cf_file.checksum
));
}
Ok(())
}
fn switch_to_cf_file(&mut self, cf: &str) -> io::Result<()> {
match self.cf_files.iter().position(|x| x.cf == cf) {
Some(index) => {
self.cf_index = index;
Ok(())
}
None => Err(io::Error::new(
ErrorKind::Other,
format!("fail to find cf {}", cf),
)),
}
}
fn add_kv(&mut self, k: &[u8], v: &[u8]) -> io::Result<()> {
let cf_file = &mut self.cf_files[self.cf_index];
let writer = cf_file.sst_writer.as_mut().unwrap();
if let Err(e) = writer.add(k, v) {
return Err(io::Error::new(ErrorKind::Other, e));
}
cf_file.kv_count += 1;
Ok(())
}
fn save_cf_files(&mut self) -> io::Result<()> {
for cf_file in &mut self.cf_files {
if plain_file_used(cf_file.cf) {
let _ = cf_file.file.take();
} else if cf_file.kv_count == 0 {
let _ = cf_file.sst_writer.take().unwrap();
} else {
let mut writer = cf_file.sst_writer.take().unwrap();
if let Err(e) = writer.finish() {
return Err(io::Error::new(ErrorKind::Other, e));
}
}
let size = try!(get_file_size(&cf_file.tmp_path));
if size > 0 {
try!(fs::rename(&cf_file.tmp_path, &cf_file.path));
cf_file.size = size;
// add size
let mut size_track = self.size_track.wl();
*size_track = size_track.saturating_add(size);
cf_file.checksum = try!(calc_crc32(&cf_file.path));
} else {
// Clean up the `tmp_path` if this cf file is empty.
delete_file_if_exist(&cf_file.tmp_path);
}
}
Ok(())
}
fn save_meta_file(&mut self) -> RaftStoreResult<()> {
let mut v = vec![];
box_try!(self.meta_file.meta.write_to_vec(&mut v));
{
let mut f = self.meta_file.file.take().unwrap();
try!(f.write_all(&v[..]));
try!(f.flush());
}
try!(fs::rename(&self.meta_file.tmp_path, &self.meta_file.path));
Ok(())
}
fn do_build(
&mut self,
snap: &DbSnapshot,
region: &Region,
stat: &mut SnapshotStatistics,
deleter: Box<SnapshotDeleter>,
) -> RaftStoreResult<()> {
if self.exists() {
match self.validate() {
Ok(()) => return Ok(()),
Err(e) => {
error!(
"[region {}] file {} is corrupted, will rebuild: {:?}",
region.get_id(),
self.path(),
e
);
if !retry_delete_snapshot(deleter, &self.key, self) {
error!(
"[region {}] failed to delete corrupted snapshot because it's \
already registered elsewhere",
self.path()
);
return Err(e);
}
try!(self.init_for_building(snap));
}
}
}
let mut snap_key_count = 0;
let (begin_key, end_key) = (enc_start_key(region), enc_end_key(region));
for cf in SNAPSHOT_CFS {
try!(self.switch_to_cf_file(cf));
let (cf_key_count, cf_size) = if plain_file_used(cf) {
let file = self.cf_files[self.cf_index].file.as_mut().unwrap();
try!(build_plain_cf_file(file, snap, cf, &begin_key, &end_key))
} else {
let mut key_count = 0;
let mut size = 0;
try!(snap.scan_cf(
cf,
&begin_key,
&end_key,
false,
&mut |key, value| {
key_count += 1;
size += key.len() + value.len();
try!(self.add_kv(key, value));
Ok(true)
}
));
(key_count, size)
};
snap_key_count += cf_key_count;
SNAPSHOT_CF_KV_COUNT
.with_label_values(&[cf])
.observe(cf_key_count as f64);
SNAPSHOT_CF_SIZE
.with_label_values(&[cf])
.observe(cf_size as f64);
info!(
"[region {}] scan snapshot {}, cf {}, key count {}, size {}",
region.get_id(),
self.path(),
cf,
cf_key_count,
cf_size
);
}
try!(self.save_cf_files());
stat.kv_count = snap_key_count;
// save snapshot meta to meta file
let snapshot_meta = try!(gen_snapshot_meta(&self.cf_files[..]));
self.meta_file.meta = snapshot_meta;
try!(self.save_meta_file());
Ok(())
}
}
pub fn build_plain_cf_file<E: BytesEncoder>(
encoder: &mut E,
snap: &DbSnapshot,
cf: &str,
start_key: &[u8],
end_key: &[u8],
) -> RaftStoreResult<(usize, usize)> {
let mut cf_key_count = 0;
let mut cf_size = 0;
try!(snap.scan_cf(
cf,
start_key,
end_key,
false,
&mut |key, value| {
cf_key_count += 1;
cf_size += key.len() + value.len();
try!(encoder.encode_compact_bytes(key));
try!(encoder.encode_compact_bytes(value));
Ok(true)
}
));
// use an empty byte array to indicate that cf reaches an end.
box_try!(encoder.encode_compact_bytes(b""));
Ok((cf_key_count, cf_size))
}
fn apply_plain_cf_file<D: CompactBytesDecoder>(
decoder: &mut D,
options: &ApplyOptions,
handle: &CFHandle,
) -> Result<()> {
let mut wb = WriteBatch::new();
let mut batch_size = 0;
loop {
try!(check_abort(&options.abort));
let key = box_try!(decoder.decode_compact_bytes());
if key.is_empty() {
if batch_size > 0 {
box_try!(options.db.write(wb));
}
break;
}
box_try!(check_key_in_region(keys::origin_key(&key), &options.region));
batch_size += key.len();
let value = box_try!(decoder.decode_compact_bytes());
batch_size += value.len();
box_try!(wb.put_cf(handle, &key, &value));
if batch_size >= options.write_batch_size {
box_try!(options.db.write(wb));
wb = WriteBatch::new();
batch_size = 0;
}
}
Ok(())
}
impl Snapshot for Snap {
fn build(
&mut self,
snap: &DbSnapshot,
region: &Region,
snap_data: &mut RaftSnapshotData,
stat: &mut SnapshotStatistics,
deleter: Box<SnapshotDeleter>,
) -> RaftStoreResult<()> {
let t = Instant::now();
try!(self.do_build(snap, region, stat, deleter));
let total_size = try!(self.total_size());
stat.size = total_size;
// set snapshot meta data
snap_data.set_file_size(total_size);
snap_data.set_version(SNAPSHOT_VERSION);
snap_data.set_meta(self.meta_file.meta.clone());
SNAPSHOT_BUILD_TIME_HISTOGRAM.observe(duration_to_sec(t.elapsed()) as f64);
info!(
"[region {}] scan snapshot {}, size {}, key count {}, takes {:?}",
region.get_id(),
self.path(),
total_size,
stat.kv_count,
t.elapsed()
);
Ok(())
}
fn path(&self) -> &str {
&self.display_path
}
fn exists(&self) -> bool {
self.cf_files
.iter()
.all(|cf_file| cf_file.size == 0 || file_exists(&cf_file.path)) &&
file_exists(&self.meta_file.path)
}
fn delete(&self) {
debug!("deleting {}", self.path());
for cf_file in &self.cf_files {
delete_file_if_exist(&cf_file.tmp_path);
if file_exists(&cf_file.path) {
let mut size_track = self.size_track.wl();
*size_track = size_track.saturating_sub(cf_file.size);
}
delete_file_if_exist(&cf_file.path);
}
delete_file_if_exist(&self.meta_file.tmp_path);
delete_file_if_exist(&self.meta_file.path);
}
fn meta(&self) -> io::Result<Metadata> {
fs::metadata(&self.meta_file.path)
}
fn total_size(&self) -> io::Result<u64> {
Ok(self.cf_files.iter().fold(0, |acc, x| acc + x.size))
}
fn save(&mut self) -> io::Result<()> {
debug!("saving to {}", self.path());
for cf_file in &mut self.cf_files {
if cf_file.size == 0 {
// Skip empty cf file.
continue;
}
// Check each cf file has been fully written, and the checksum matches.
{
let mut file = cf_file.file.take().unwrap();
try!(file.flush());
}
if cf_file.written_size != cf_file.size {
return Err(io::Error::new(
ErrorKind::Other,
format!(
"snapshot file {} for cf {} size mismatches, \
real size {}, expected size {}",
cf_file.path.display(),
cf_file.cf,
cf_file.written_size,
cf_file.size
),
));
}
let checksum = cf_file.write_digest.as_ref().unwrap().sum32();
if checksum != cf_file.checksum {
return Err(io::Error::new(
ErrorKind::Other,
format!(
"snapshot file {} for cf {} checksum \
mismatches, real checksum {}, expected \
checksum {}",
cf_file.path.display(),
cf_file.cf,
checksum,
cf_file.checksum
),
));
}
try!(fs::rename(&cf_file.tmp_path, &cf_file.path));
let mut size_track = self.size_track.wl();
*size_track = size_track.saturating_add(cf_file.size);
}
// write meta file
let mut v = vec![];
try!(self.meta_file.meta.write_to_vec(&mut v));
try!(self.meta_file.file.take().unwrap().write_all(&v[..]));
try!(fs::rename(&self.meta_file.tmp_path, &self.meta_file.path));
Ok(())
}
fn apply(&mut self, options: ApplyOptions) -> Result<()> {
box_try!(self.validate());
for cf_file in &mut self.cf_files {
if cf_file.size == 0 {
// Skip empty cf file.
continue;
}
try!(check_abort(&options.abort));
let cf_handle = box_try!(rocksdb::get_cf_handle(&options.db, cf_file.cf));
if plain_file_used(cf_file.cf) {
let mut file = box_try!(File::open(&cf_file.path));
try!(apply_plain_cf_file(&mut file, &options, cf_handle));
} else {
let ingest_opt = IngestExternalFileOptions::new();
// TODO: move SST file instead of copy
// after changing logic in raft, ask for resending snapshot if applying fail.
// ingest_opt.move_files(true);
let path = cf_file.path.as_path().to_str().unwrap();
box_try!(
options
.db
.ingest_external_file_cf(cf_handle, &ingest_opt, &[path])
);
}
}
Ok(())
}
}
impl Read for Snap {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
while self.cf_index < self.cf_files.len() {
let cf_file = &mut self.cf_files[self.cf_index];
if cf_file.size == 0 {
self.cf_index += 1;
continue;
}
match cf_file.file.as_mut().unwrap().read(buf) {
Ok(0) => {
// EOF. Switch to next file.
self.cf_index += 1;
}
Ok(n) => {
return Ok(n);
}
e => return e,
}
}
Ok(0)
}
}
impl Write for Snap {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
let mut next_buf = buf;