-
Notifications
You must be signed in to change notification settings - Fork 165
/
db_impl.cc
1527 lines (1411 loc) · 53.9 KB
/
db_impl.cc
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
#include "db_impl.h"
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <cinttypes>
#include "db/arena_wrapped_db_iter.h"
#include "logging/log_buffer.h"
#include "monitoring/statistics_impl.h"
#include "options/options_helper.h"
#include "port/port.h"
#include "util/autovector.h"
#include "util/mutexlock.h"
#include "util/string_util.h"
#include "util/threadpool_imp.h"
#include "base_db_listener.h"
#include "blob_file_builder.h"
#include "blob_file_iterator.h"
#include "blob_file_size_collector.h"
#include "blob_gc.h"
#include "compaction_filter.h"
#include "db_iter.h"
#include "table_factory.h"
#include "titan_build_version.h"
#include "titan_logging.h"
#include "titan_stats.h"
namespace rocksdb {
namespace titandb {
class TitanDBImpl::FileManager : public BlobFileManager {
public:
FileManager(TitanDBImpl* db) : db_(db) {}
Status NewFile(std::unique_ptr<BlobFileHandle>* handle,
Env::IOPriority pri) override {
auto number = db_->blob_file_set_->NewFileNumber();
auto name = BlobFileName(db_->dirname_, number);
Status s;
std::unique_ptr<WritableFileWriter> file;
{
std::unique_ptr<FSWritableFile> f;
s = db_->env_->GetFileSystem()->NewWritableFile(
name, FileOptions(db_->env_options_), &f, nullptr /*dbg*/);
if (!s.ok()) return s;
f->SetIOPriority(pri);
file.reset(new WritableFileWriter(std::move(f), name,
FileOptions(db_->env_options_)));
}
handle->reset(new FileHandle(number, name, std::move(file)));
{
MutexLock l(&db_->mutex_);
db_->pending_outputs_.insert(number);
}
return s;
}
Status BatchFinishFiles(
uint32_t cf_id,
const std::vector<std::pair<std::shared_ptr<BlobFileMeta>,
std::unique_ptr<BlobFileHandle>>>& files)
override {
Status s;
if (files.empty()) return s;
VersionEdit edit;
edit.SetColumnFamilyID(cf_id);
for (auto& file : files) {
RecordTick(statistics(db_->stats_.get()), TITAN_BLOB_FILE_SYNCED);
{
StopWatch sync_sw(db_->env_->GetSystemClock().get(),
statistics(db_->stats_.get()),
TITAN_BLOB_FILE_SYNC_MICROS);
s = file.second->GetFile()->Sync(false);
}
if (s.ok()) {
s = file.second->GetFile()->Close();
}
if (!s.ok()) return s;
TITAN_LOG_INFO(db_->db_options_.info_log,
"Titan adding blob file [%" PRIu64 "] range [%s, %s]",
file.first->file_number(),
Slice(file.first->smallest_key()).ToString(true).c_str(),
Slice(file.first->largest_key()).ToString(true).c_str());
edit.AddBlobFile(file.first);
}
s = db_->directory_->Fsync();
if (!s.ok()) {
return s;
}
{
MutexLock l(&db_->mutex_);
s = db_->blob_file_set_->LogAndApply(edit);
if (!s.ok()) {
db_->SetBGError(s);
}
for (const auto& file : files)
db_->pending_outputs_.erase(file.second->GetNumber());
}
return s;
}
Status BatchDeleteFiles(
const std::vector<std::unique_ptr<BlobFileHandle>>& handles) override {
Status s;
for (auto& handle : handles) {
s = db_->env_->DeleteFile(handle->GetName());
}
{
MutexLock l(&db_->mutex_);
for (const auto& handle : handles)
db_->pending_outputs_.erase(handle->GetNumber());
}
return s;
}
private:
class FileHandle : public BlobFileHandle {
public:
FileHandle(uint64_t number, const std::string& name,
std::unique_ptr<WritableFileWriter> file)
: number_(number), name_(name), file_(std::move(file)) {}
uint64_t GetNumber() const override { return number_; }
const std::string& GetName() const override { return name_; }
WritableFileWriter* GetFile() const override { return file_.get(); }
private:
uint64_t number_;
std::string name_;
std::unique_ptr<WritableFileWriter> file_;
};
TitanDBImpl* db_;
};
TitanDBImpl::TitanDBImpl(const TitanDBOptions& options,
const std::string& dbname)
: bg_cv_(&mutex_),
dbname_(dbname),
env_(options.env),
env_options_(options),
db_options_(options) {
if (db_options_.dirname.empty()) {
db_options_.dirname = dbname_ + "/titandb";
}
dirname_ = db_options_.dirname;
if (db_options_.statistics != nullptr) {
// The point of `statistics` is that it can be shared by multiple instances.
// So we should check if it's a qualified statistics instead of overwriting
// it.
db_options_.statistics->getTickerCount(TITAN_TICKER_ENUM_MAX - 1);
HistogramData data;
db_options_.statistics->histogramData(TITAN_HISTOGRAM_ENUM_MAX - 1, &data);
stats_.reset(new TitanStats(db_options_.statistics.get()));
}
blob_manager_.reset(new FileManager(this));
}
TitanDBImpl::~TitanDBImpl() { Close(); }
void TitanDBImpl::StartBackgroundTasks() {
if (thread_purge_obsolete_ == nullptr &&
db_options_.purge_obsolete_files_period_sec > 0) {
thread_purge_obsolete_.reset(new rocksdb::RepeatableThread(
[this]() { TitanDBImpl::PurgeObsoleteFiles(); }, "titanbg",
env_->GetSystemClock().get(),
db_options_.purge_obsolete_files_period_sec * 1000 * 1000));
}
if (thread_dump_stats_ == nullptr &&
db_options_.titan_stats_dump_period_sec > 0) {
thread_dump_stats_.reset(new rocksdb::RepeatableThread(
[this]() { TitanDBImpl::DumpStats(); }, "titanst",
env_->GetSystemClock().get(),
db_options_.titan_stats_dump_period_sec * 1000 * 1000));
}
}
Status TitanDBImpl::ValidateOptions(
const TitanDBOptions& options,
const std::vector<TitanCFDescriptor>& column_families) const {
for (const auto& cf : column_families) {
if (cf.options.level_merge &&
!cf.options.level_compaction_dynamic_level_bytes) {
return Status::InvalidArgument(
"Require enabling level_compaction_dynamic_level_bytes for "
"level_merge");
}
}
return Status::OK();
}
Status TitanDBImpl::Open(const std::vector<TitanCFDescriptor>& descs,
std::vector<ColumnFamilyHandle*>* handles) {
if (handles == nullptr) {
return Status::InvalidArgument("handles must be non-null.");
}
Status s = OpenImpl(descs, handles);
// Cleanup after failure.
if (!s.ok()) {
if (handles->size() > 0) {
assert(db_ != nullptr);
for (ColumnFamilyHandle* cfh : *handles) {
Status destroy_handle_status = db_->DestroyColumnFamilyHandle(cfh);
if (!destroy_handle_status.ok()) {
TITAN_LOG_ERROR(db_options_.info_log,
"Failed to destroy CF handle after open failure: %s",
destroy_handle_status.ToString().c_str());
}
}
handles->clear();
}
if (db_ != nullptr) {
Status close_status = db_->Close();
if (!close_status.ok()) {
TITAN_LOG_ERROR(db_options_.info_log,
"Failed to close base DB after open failure: %s",
close_status.ToString().c_str());
}
db_ = nullptr;
db_impl_ = nullptr;
}
if (lock_) {
env_->UnlockFile(lock_);
lock_ = nullptr;
}
}
return s;
}
Status TitanDBImpl::OpenImpl(const std::vector<TitanCFDescriptor>& descs,
std::vector<ColumnFamilyHandle*>* handles) {
Status s = ValidateOptions(db_options_, descs);
if (!s.ok()) {
return s;
}
// Sets up directories for base DB and Titan.
s = env_->CreateDirIfMissing(dbname_);
if (!s.ok()) {
return s;
}
if (!db_options_.info_log) {
s = CreateLoggerFromOptions(dbname_, db_options_, &db_options_.info_log);
if (!s.ok()) {
return s;
}
}
s = env_->CreateDirIfMissing(dirname_);
if (!s.ok()) {
return s;
}
s = env_->NewDirectory(dirname_, &directory_);
if (!s.ok()) {
return s;
}
s = env_->LockFile(LockFileName(dirname_), &lock_);
if (!s.ok()) {
return s;
}
// Note that info log is initialized after `CreateLoggerFromOptions`,
// so new `BlobFileSet` here but not in constructor is to get a proper info
// log.
blob_file_set_.reset(
new BlobFileSet(db_options_, stats_.get(), &initialized_, &mutex_));
// Setup options.
db_options_.listeners.emplace_back(std::make_shared<BaseDbListener>(this));
// Descriptors for actually open DB.
std::vector<ColumnFamilyDescriptor> base_descs;
std::vector<std::shared_ptr<TitanTableFactory>> titan_table_factories;
for (auto& desc : descs) {
base_descs.emplace_back(desc.name, desc.options);
ColumnFamilyOptions& cf_opts = base_descs.back().options;
// Disable compactions before blob file set is initialized.
cf_opts.disable_auto_compactions = true;
cf_opts.table_properties_collector_factories.emplace_back(
std::make_shared<BlobFileSizeCollectorFactory>());
titan_table_factories.push_back(std::make_shared<TitanTableFactory>(
db_options_, desc.options, blob_manager_, &mutex_, blob_file_set_.get(),
stats_.get()));
cf_opts.table_factory = titan_table_factories.back();
if (cf_opts.compaction_filter != nullptr ||
cf_opts.compaction_filter_factory != nullptr) {
std::shared_ptr<TitanCompactionFilterFactory> titan_cf_factory =
std::make_shared<TitanCompactionFilterFactory>(
cf_opts.compaction_filter, cf_opts.compaction_filter_factory,
this, desc.options.skip_value_in_compaction_filter, desc.name);
cf_opts.compaction_filter = nullptr;
cf_opts.compaction_filter_factory = titan_cf_factory;
}
}
// Initialize GC thread pool.
if (!db_options_.disable_background_gc && db_options_.max_background_gc > 0) {
auto pool = NewThreadPool(0);
// Hack: set thread priority to change the thread name
(reinterpret_cast<ThreadPoolImpl*>(pool))
->SetThreadPriority(Env::Priority::USER);
pool->SetBackgroundThreads(db_options_.max_background_gc);
thread_pool_.reset(pool);
}
// Open base DB.
s = DB::Open(db_options_, dbname_, base_descs, handles, &db_);
if (!s.ok()) {
db_ = nullptr;
handles->clear();
return s;
}
db_impl_ = reinterpret_cast<DBImpl*>(db_->GetRootDB());
assert(db_ != nullptr);
assert(handles->size() == descs.size());
std::map<uint32_t, TitanCFOptions> column_families;
std::vector<ColumnFamilyHandle*> cf_with_compaction;
for (size_t i = 0; i < descs.size(); i++) {
cf_info_.emplace((*handles)[i]->GetID(),
TitanColumnFamilyInfo(
{(*handles)[i]->GetName(),
ImmutableTitanCFOptions(descs[i].options),
MutableTitanCFOptions(descs[i].options),
descs[i].options.table_factory /*base_table_factory*/,
titan_table_factories[i]}));
column_families[(*handles)[i]->GetID()] = descs[i].options;
}
s = blob_file_set_->Open(column_families, GenerateCachePrefix());
if (!s.ok()) {
return s;
}
for (size_t i = 0; i < handles->size(); i++) {
auto rocks_cf_handle =
static_cast_with_check<rocksdb::ColumnFamilyHandleImpl>((*handles)[i]);
auto titan_handle = new TitanColumnFamilyHandle(
rocks_cf_handle,
blob_file_set_->GetBlobStorage(rocks_cf_handle->GetID()).lock());
(*handles)[i] = titan_handle;
if ((*handles)[i]->GetName() == kDefaultColumnFamilyName) {
// New a separate handle for default column family, so default column
// family handle is always available even if caller delete the default
// column family handle.
default_cf_handle_ = new TitanColumnFamilyHandle(
rocks_cf_handle,
blob_file_set_->GetBlobStorage(rocks_cf_handle->GetID()).lock(),
false);
}
if (!descs[i].options.disable_auto_compactions) {
cf_with_compaction.push_back(titan_handle);
}
}
s = AsyncInitializeGC(*handles);
if (!s.ok()) {
return s;
}
// Enable compaction and background tasks after blob file set is opened.
db_->EnableAutoCompaction(cf_with_compaction);
StartBackgroundTasks();
// Dump options.
TITAN_LOG_INFO(db_options_.info_log, "Titan DB open.");
TITAN_LOG_HEADER(db_options_.info_log, "Titan git sha: %s",
titan_build_git_sha);
db_options_.Dump(db_options_.info_log.get());
for (auto& desc : descs) {
TITAN_LOG_HEADER(db_options_.info_log,
"Column family [%s], options:", desc.name.c_str());
desc.options.Dump(db_options_.info_log.get());
}
return s;
}
Status TitanDBImpl::Close() {
Status s;
CloseImpl();
if (db_) {
if (default_cf_handle_ != nullptr) {
delete default_cf_handle_;
default_cf_handle_ = nullptr;
}
s = db_->Close();
delete db_;
db_ = nullptr;
db_impl_ = nullptr;
}
if (lock_) {
env_->UnlockFile(lock_);
lock_ = nullptr;
}
return s;
}
Status TitanDBImpl::CloseImpl() {
{
MutexLock l(&mutex_);
// Although `shuting_down_` is atomic bool object, we should set it under
// the protection of mutex_, otherwise, there maybe something wrong with it,
// like:
// 1, A thread: shuting_down_.load = false
// 2, B thread: shuting_down_.store(true)
// 3, B thread: unschedule all bg work
// 4, A thread: schedule bg work
shuting_down_.store(true, std::memory_order_release);
}
if (thread_pool_ != nullptr) {
thread_pool_->JoinAllThreads();
}
{
MutexLock l(&mutex_);
// `bg_gc_scheduled_` should be 0 after `JoinAllThreads`, double check here.
while (bg_gc_scheduled_ > 0) {
bg_cv_.Wait();
}
}
if (thread_purge_obsolete_ != nullptr) {
thread_purge_obsolete_->cancel();
mutex_.Lock();
thread_purge_obsolete_.reset();
mutex_.Unlock();
}
if (thread_dump_stats_ != nullptr) {
thread_dump_stats_->cancel();
mutex_.Lock();
thread_dump_stats_.reset();
mutex_.Unlock();
}
if (thread_initialize_gc_ != nullptr) {
if (thread_initialize_gc_->joinable()) {
thread_initialize_gc_->join();
}
mutex_.Lock();
thread_initialize_gc_.reset();
mutex_.Unlock();
}
return Status::OK();
}
Status TitanDBImpl::CreateColumnFamilies(
const std::vector<TitanCFDescriptor>& descs,
std::vector<ColumnFamilyHandle*>* handles) {
std::vector<ColumnFamilyDescriptor> base_descs;
std::vector<std::shared_ptr<TableFactory>> base_table_factory;
std::vector<std::shared_ptr<TitanTableFactory>> titan_table_factory;
for (auto& desc : descs) {
ColumnFamilyOptions options = desc.options;
// Replaces the provided table factory with TitanTableFactory.
base_table_factory.emplace_back(options.table_factory);
titan_table_factory.emplace_back(std::make_shared<TitanTableFactory>(
db_options_, desc.options, blob_manager_, &mutex_, blob_file_set_.get(),
stats_.get()));
options.table_factory = titan_table_factory.back();
options.table_properties_collector_factories.emplace_back(
std::make_shared<BlobFileSizeCollectorFactory>());
if (options.compaction_filter != nullptr ||
options.compaction_filter_factory != nullptr) {
std::shared_ptr<TitanCompactionFilterFactory> titan_cf_factory =
std::make_shared<TitanCompactionFilterFactory>(
options.compaction_filter, options.compaction_filter_factory,
this, desc.options.skip_value_in_compaction_filter, desc.name);
options.compaction_filter = nullptr;
options.compaction_filter_factory = titan_cf_factory;
}
base_descs.emplace_back(desc.name, options);
}
Status s = db_impl_->CreateColumnFamilies(base_descs, handles);
assert(handles->size() == descs.size());
if (s.ok()) {
std::map<uint32_t, TitanCFOptions> column_families;
{
MutexLock l(&mutex_);
for (size_t i = 0; i < descs.size(); i++) {
ColumnFamilyHandle* handle = (*handles)[i];
uint32_t cf_id = handle->GetID();
column_families.emplace(cf_id, descs[i].options);
cf_info_.emplace(
cf_id,
TitanColumnFamilyInfo(
{handle->GetName(), ImmutableTitanCFOptions(descs[i].options),
MutableTitanCFOptions(descs[i].options), base_table_factory[i],
titan_table_factory[i]}));
}
blob_file_set_->AddColumnFamilies(column_families, GenerateCachePrefix());
for (size_t i = 0; i < handles->size(); i++) {
auto rocks_cf_handle =
static_cast_with_check<rocksdb::ColumnFamilyHandleImpl>(
(*handles)[i]);
auto titan_handle = new TitanColumnFamilyHandle(
rocks_cf_handle,
blob_file_set_->GetBlobStorage(rocks_cf_handle->GetID()).lock());
(*handles)[i] = titan_handle;
}
}
}
if (s.ok()) {
for (auto& desc : descs) {
TITAN_LOG_INFO(db_options_.info_log, "Created column family [%s].",
desc.name.c_str());
desc.options.Dump(db_options_.info_log.get());
}
} else {
std::string column_families_str;
for (auto& desc : descs) {
column_families_str += "[" + desc.name + "]";
}
TITAN_LOG_ERROR(db_options_.info_log,
"Failed to create column families %s: %s",
column_families_str.c_str(), s.ToString().c_str());
}
return s;
}
Status TitanDBImpl::DropColumnFamilies(
const std::vector<ColumnFamilyHandle*>& handles) {
TEST_SYNC_POINT("TitanDBImpl::DropColumnFamilies:Begin");
std::vector<uint32_t> column_families;
std::string column_families_str;
for (auto& handle : handles) {
column_families.emplace_back(handle->GetID());
column_families_str += "[" + handle->GetName() + "]";
}
{
MutexLock l(&mutex_);
drop_cf_requests_++;
// Has to wait till no GC job is running before proceed, otherwise GC jobs
// can fail and set background error.
// TODO(yiwu): only wait for GC jobs of CFs being dropped.
while (bg_gc_running_ > 0) {
bg_cv_.Wait();
}
}
TEST_SYNC_POINT_CALLBACK("TitanDBImpl::DropColumnFamilies:BeforeBaseDBDropCF",
nullptr);
Status s = db_impl_->DropColumnFamilies(handles);
if (s.ok()) {
MutexLock l(&mutex_);
SequenceNumber obsolete_sequence = db_impl_->GetLatestSequenceNumber();
s = blob_file_set_->DropColumnFamilies(column_families, obsolete_sequence);
drop_cf_requests_--;
if (drop_cf_requests_ == 0) {
bg_cv_.SignalAll();
}
}
if (s.ok()) {
TITAN_LOG_INFO(db_options_.info_log, "Dropped column families: %s",
column_families_str.c_str());
} else {
TITAN_LOG_ERROR(db_options_.info_log,
"Failed to drop column families %s: %s",
column_families_str.c_str(), s.ToString().c_str());
}
return s;
}
Status TitanDBImpl::DestroyColumnFamilyHandle(
ColumnFamilyHandle* column_family) {
if (column_family == nullptr) {
return Status::InvalidArgument("Column family handle is nullptr.");
}
auto cf_id = column_family->GetID();
auto cf_name = column_family->GetName();
if (column_family == default_cf_handle_) {
return Status::InvalidArgument(
"Default column family handle is not destroyable.");
}
Status s = db_impl_->DestroyColumnFamilyHandle(column_family);
if (s.ok()) {
MutexLock l(&mutex_);
// it just changes some marks and doesn't delete blob files physically.
Status destroy_status = blob_file_set_->MaybeDestroyColumnFamily(cf_id);
// BlobFileSet will return NotFound status if the cf is not destroyed.
if (destroy_status.ok()) {
assert(cf_info_.count(cf_id) > 0);
cf_info_.erase(cf_id);
}
}
if (s.ok()) {
TITAN_LOG_INFO(db_options_.info_log, "Destroyed column family handle [%s].",
cf_name.c_str());
} else {
TITAN_LOG_ERROR(db_options_.info_log,
"Failed to destroy column family handle [%s]: %s",
cf_name.c_str(), s.ToString().c_str());
}
return s;
}
Status TitanDBImpl::CompactFiles(
const CompactionOptions& compact_options, ColumnFamilyHandle* column_family,
const std::vector<std::string>& input_file_names, const int output_level,
const int output_path_id, std::vector<std::string>* const output_file_names,
CompactionJobInfo* compaction_job_info) {
if (HasBGError()) return GetBGError();
std::unique_ptr<CompactionJobInfo> compaction_job_info_ptr;
if (compaction_job_info == nullptr) {
compaction_job_info_ptr.reset(new CompactionJobInfo());
compaction_job_info = compaction_job_info_ptr.get();
}
auto s = db_impl_->CompactFiles(
compact_options, column_family, input_file_names, output_level,
output_path_id, output_file_names, compaction_job_info);
if (s.ok()) {
OnCompactionCompleted(*compaction_job_info);
}
return s;
}
Status TitanDBImpl::Put(const rocksdb::WriteOptions& options,
rocksdb::ColumnFamilyHandle* column_family,
const rocksdb::Slice& key,
const rocksdb::Slice& value) {
return HasBGError() ? GetBGError()
: db_->Put(options, column_family, key, value);
}
Status TitanDBImpl::Write(const rocksdb::WriteOptions& options,
rocksdb::WriteBatch* updates,
PostWriteCallback* callback) {
return HasBGError() ? GetBGError() : db_->Write(options, updates, callback);
}
Status TitanDBImpl::MultiBatchWrite(const WriteOptions& options,
std::vector<WriteBatch*>&& updates,
PostWriteCallback* callback) {
return HasBGError()
? GetBGError()
: db_->MultiBatchWrite(options, std::move(updates), callback);
}
Status TitanDBImpl::Delete(const rocksdb::WriteOptions& options,
rocksdb::ColumnFamilyHandle* column_family,
const rocksdb::Slice& key) {
return HasBGError() ? GetBGError() : db_->Delete(options, column_family, key);
}
Status TitanDBImpl::IngestExternalFile(
rocksdb::ColumnFamilyHandle* column_family,
const std::vector<std::string>& external_files,
const rocksdb::IngestExternalFileOptions& options) {
return HasBGError()
? GetBGError()
: db_->IngestExternalFile(column_family, external_files, options);
}
Status TitanDBImpl::CompactRange(const rocksdb::CompactRangeOptions& options,
rocksdb::ColumnFamilyHandle* column_family,
const rocksdb::Slice* begin,
const rocksdb::Slice* end) {
return HasBGError() ? GetBGError()
: db_->CompactRange(options, column_family, begin, end);
}
Status TitanDBImpl::Flush(const rocksdb::FlushOptions& options,
rocksdb::ColumnFamilyHandle* column_family) {
return HasBGError() ? GetBGError() : db_->Flush(options, column_family);
}
Status TitanDBImpl::Get(const ReadOptions& options, ColumnFamilyHandle* handle,
const Slice& key, PinnableSlice* value) {
if (options.snapshot) {
return GetImpl(options, handle, key, value);
}
ReadOptions ro(options);
ManagedSnapshot snapshot(this);
ro.snapshot = snapshot.snapshot();
return GetImpl(ro, handle, key, value);
}
Status TitanDBImpl::GetImpl(const ReadOptions& options,
ColumnFamilyHandle* handle, const Slice& key,
PinnableSlice* value) {
Status s;
bool is_blob_index = false;
DBImpl::GetImplOptions gopts;
gopts.column_family = handle;
gopts.value = value;
gopts.is_blob_index = &is_blob_index;
s = db_impl_->GetImpl(options, key, gopts);
if (!s.ok() || !is_blob_index) return s;
StopWatch get_sw(env_->GetSystemClock().get(), statistics(stats_.get()),
TITAN_GET_MICROS);
RecordTick(statistics(stats_.get()), TITAN_NUM_GET);
BlobIndex index;
s = index.DecodeFrom(value);
assert(s.ok());
if (!s.ok()) return s;
auto storage =
static_cast_with_check<TitanColumnFamilyHandle>(handle)->GetBlobStorage();
if (storage) {
StopWatch read_sw(env_->GetSystemClock().get(), statistics(stats_.get()),
TITAN_BLOB_FILE_READ_MICROS);
value->Reset();
BlobRecord record;
s = storage->Get(options, index, &record, value);
RecordTick(statistics(stats_.get()), TITAN_BLOB_FILE_NUM_KEYS_READ);
RecordTick(statistics(stats_.get()), TITAN_BLOB_FILE_BYTES_READ,
index.blob_handle.size);
} else {
TITAN_LOG_ERROR(db_options_.info_log,
"Column family id:%" PRIu32 " not Found.", handle->GetID());
return Status::NotFound(
"Column family id: " + std::to_string(handle->GetID()) + " not Found.");
}
if (s.IsCorruption()) {
TITAN_LOG_ERROR(db_options_.info_log,
"Key:%s Snapshot:%" PRIu64 " GetBlobFile err:%s\n",
key.ToString(true).c_str(),
options.snapshot->GetSequenceNumber(),
s.ToString().c_str());
}
return s;
}
std::vector<Status> TitanDBImpl::MultiGet(
const ReadOptions& options, const std::vector<ColumnFamilyHandle*>& handles,
const std::vector<Slice>& keys, std::vector<std::string>* values) {
if (options.snapshot) {
return MultiGetImpl(options, handles, keys, values);
}
ReadOptions ro(options);
ManagedSnapshot snapshot(this);
ro.snapshot = snapshot.snapshot();
return MultiGetImpl(ro, handles, keys, values);
}
std::vector<Status> TitanDBImpl::MultiGetImpl(
const ReadOptions& options, const std::vector<ColumnFamilyHandle*>& handles,
const std::vector<Slice>& keys, std::vector<std::string>* values) {
std::vector<Status> res;
res.resize(keys.size());
values->resize(keys.size());
for (size_t i = 0; i < keys.size(); i++) {
auto value = &(*values)[i];
PinnableSlice pinnable_value(value);
res[i] = GetImpl(options, handles[i], keys[i], &pinnable_value);
if (res[i].ok() && pinnable_value.IsPinned()) {
value->assign(pinnable_value.data(), pinnable_value.size());
}
}
return res;
}
Iterator* TitanDBImpl::NewIterator(const TitanReadOptions& options,
ColumnFamilyHandle* handle) {
std::shared_ptr<ManagedSnapshot> snapshot;
if (options.snapshot) {
return NewIteratorImpl(options, handle, snapshot);
}
TitanReadOptions ro(options);
snapshot.reset(new ManagedSnapshot(this));
ro.snapshot = snapshot->snapshot();
return NewIteratorImpl(ro, handle, snapshot);
}
Iterator* TitanDBImpl::NewIteratorImpl(
const TitanReadOptions& options, ColumnFamilyHandle* handle,
std::shared_ptr<ManagedSnapshot> snapshot) {
auto cfd = reinterpret_cast<ColumnFamilyHandleImpl*>(handle)->cfd();
auto storage =
static_cast_with_check<TitanColumnFamilyHandle>(handle)->GetBlobStorage();
if (!storage) {
TITAN_LOG_ERROR(db_options_.info_log,
"Column family id:%" PRIu32 " not Found.", handle->GetID());
return nullptr;
}
std::unique_ptr<ArenaWrappedDBIter> iter(db_impl_->NewIteratorImpl(
options, cfd, cfd->GetReferencedSuperVersion(db_impl_),
options.snapshot->GetSequenceNumber(), nullptr /*read_callback*/,
true /*expose_blob_index*/, true /*allow_refresh*/));
return new TitanDBIterator(options, storage.get(), snapshot, std::move(iter),
env_->GetSystemClock().get(), stats_.get(),
db_options_.info_log.get());
}
Status TitanDBImpl::NewIterators(
const TitanReadOptions& options,
const std::vector<ColumnFamilyHandle*>& handles,
std::vector<Iterator*>* iterators) {
TitanReadOptions ro(options);
std::shared_ptr<ManagedSnapshot> snapshot;
if (!ro.snapshot) {
snapshot.reset(new ManagedSnapshot(this));
ro.snapshot = snapshot->snapshot();
}
iterators->clear();
iterators->reserve(handles.size());
for (auto& handle : handles) {
iterators->emplace_back(NewIteratorImpl(ro, handle, snapshot));
}
return Status::OK();
}
const Snapshot* TitanDBImpl::GetSnapshot() { return db_->GetSnapshot(); }
void TitanDBImpl::ReleaseSnapshot(const Snapshot* snapshot) {
// TODO:
// We can record here whether the oldest snapshot is released.
// If not, we can just skip the next round of purging obsolete files.
db_->ReleaseSnapshot(snapshot);
}
Status TitanDBImpl::DisableFileDeletions() {
// Disable base DB file deletions.
Status s = db_impl_->DisableFileDeletions();
if (!s.ok()) {
return s;
}
int count = 0;
{
// Hold delete_titandb_file_mutex_ to make sure no
// PurgeObsoleteFiles job is running.
MutexLock l(&delete_titandb_file_mutex_);
count = ++disable_titandb_file_deletions_;
}
TITAN_LOG_INFO(db_options_.info_log,
"Disalbed blob file deletions. count: %d", count);
return Status::OK();
}
Status TitanDBImpl::EnableFileDeletions(bool force) {
// Enable base DB file deletions.
Status s = db_impl_->EnableFileDeletions(force);
if (!s.ok()) {
return s;
}
int count = 0;
{
MutexLock l(&delete_titandb_file_mutex_);
if (force) {
disable_titandb_file_deletions_ = 0;
} else if (disable_titandb_file_deletions_ > 0) {
count = --disable_titandb_file_deletions_;
}
assert(count >= 0);
}
TITAN_LOG_INFO(db_options_.info_log, "Enabled blob file deletions. count: %d",
count);
return Status::OK();
}
Status TitanDBImpl::GetAllTitanFiles(std::vector<std::string>& files,
std::vector<VersionEdit>* edits) {
Status s = DisableFileDeletions();
if (!s.ok()) {
return s;
}
{
MutexLock l(&mutex_);
blob_file_set_->GetAllFiles(&files, edits);
}
return EnableFileDeletions(false);
}
Status TitanDBImpl::DeleteFilesInRanges(ColumnFamilyHandle* column_family,
const RangePtr* ranges, size_t n,
bool include_end) {
TablePropertiesCollection props;
auto cfh = reinterpret_cast<ColumnFamilyHandleImpl*>(column_family);
auto cfd = cfh->cfd();
Version* version = nullptr;
// Increment the ref count
{
InstrumentedMutexLock l(db_impl_->mutex());
version = cfd->current();
version->Ref();
}
auto* vstorage = version->storage_info();
for (size_t i = 0; i < n; i++) {
auto begin = ranges[i].start, end = ranges[i].limit;
// Get all the files within range except L0, cause `DeleteFilesInRanges`
// would not delete the files in L0.
for (int level = 1; level < vstorage->num_non_empty_levels(); level++) {
if (vstorage->LevelFiles(level).empty() ||
!vstorage->OverlapInLevel(level, begin, end)) {
continue;
}
std::vector<FileMetaData*> level_files;
InternalKey begin_storage, end_storage, *begin_key, *end_key;
if (begin == nullptr) {
begin_key = nullptr;
} else {
begin_storage.SetMinPossibleForUserKey(*begin);
begin_key = &begin_storage;
}
if (end == nullptr) {
end_key = nullptr;
} else {
end_storage.SetMaxPossibleForUserKey(*end);
end_key = &end_storage;
}
std::vector<FileMetaData*> files;
vstorage->GetCleanInputsWithinInterval(level, begin_key, end_key, &files,
-1 /* hint_index */,
nullptr /* file_index */);
for (const auto& file_meta : files) {
if (file_meta->being_compacted) {
continue;
}
if (!include_end && end != nullptr &&
cfd->user_comparator()->Compare(file_meta->largest.user_key(),
*end) == 0) {
continue;
}
auto fname =
TableFileName(cfd->ioptions()->cf_paths, file_meta->fd.GetNumber(),
file_meta->fd.GetPathId());
if (props.count(fname) == 0) {
std::shared_ptr<const TableProperties> table_properties;
Status s = version->GetTableProperties(
ReadOptions(), &table_properties, file_meta, &fname);
if (s.ok() && table_properties) {
props.insert({fname, table_properties});
} else {
return s;
}
}
}
}
}
// Decrement the ref count
{
InstrumentedMutexLock l(db_impl_->mutex());
version->Unref();
}
auto cf_id = column_family->GetID();
std::map<uint64_t, int64_t> blob_file_size_diff;
for (auto& prop : props) {
Status gc_stats_status = ExtractGCStatsFromTableProperty(
prop.second, false /*to_add*/, &blob_file_size_diff);
if (!gc_stats_status.ok()) {
// TODO: Should treat it as background error and make DB read-only.
TITAN_LOG_ERROR(db_options_.info_log,
"failed to extract GC stats, file: %s, error: %s",
prop.first.c_str(), gc_stats_status.ToString().c_str());
assert(false);
}
}
// Here could be a running compaction install a new version after obtain
// current and before we call DeleteFilesInRange for the base DB. In this case
// the properties we get could be inaccurate.
// TODO: we can use the OnTableFileDeleted callback after adding table
// property field to TableFileDeletionInfo.
Status s =
db_impl_->DeleteFilesInRanges(column_family, ranges, n, include_end);
if (!s.ok()) return s;
MutexLock l(&mutex_);
auto bs = static_cast_with_check<TitanColumnFamilyHandle>(column_family)
->GetBlobStorage();
if (!bs) {
// TODO: Should treat it as background error and make DB read-only.
TITAN_LOG_ERROR(db_options_.info_log,
"Column family id:%" PRIu32 " not Found.", cf_id);
return Status::NotFound("Column family id: " + std::to_string(cf_id) +
" not Found.");
}
VersionEdit edit;
auto cf_options = bs->cf_options();
for (const auto& file_size : blob_file_size_diff) {
uint64_t file_number = file_size.first;
int64_t delta = file_size.second;
auto file = bs->FindFile(file_number).lock();
if (!file || file->is_obsolete()) {
// file has been gc out
continue;
}