forked from estraier/tkrzw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tkrzw_dbm_skip.cc
2053 lines (1923 loc) · 65.1 KB
/
tkrzw_dbm_skip.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
/*************************************************************************************************
* File database manager implementation based on skip list
*
* Copyright 2020 Google LLC
* 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
* https://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, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*************************************************************************************************/
#include "tkrzw_sys_config.h"
#include "tkrzw_dbm.h"
#include "tkrzw_dbm_common_impl.h"
#include "tkrzw_dbm_skip.h"
#include "tkrzw_dbm_skip_impl.h"
#include "tkrzw_file.h"
#include "tkrzw_file_mmap.h"
#include "tkrzw_file_pos.h"
#include "tkrzw_file_std.h"
#include "tkrzw_file_util.h"
#include "tkrzw_lib_common.h"
#include "tkrzw_str_util.h"
#include "tkrzw_thread_util.h"
#include "tkrzw_time_util.h"
namespace tkrzw {
constexpr int32_t METADATA_SIZE = 128;
const char META_MAGIC_DATA[] = "TkrzwSDB\n";
constexpr int32_t META_OFFSET_CYCLIC_MAGIC_FRONT = 9;
constexpr int32_t META_OFFSET_PKG_MAJOR_VERSION = 10;
constexpr int32_t META_OFFSET_PKG_MINOR_VERSION = 11;
constexpr int32_t META_OFFSET_OFFSET_WIDTH = 12;
constexpr int32_t META_OFFSET_STEP_UNIT = 13;
constexpr int32_t META_OFFSET_MAX_LEVEL = 14;
constexpr int32_t META_OFFSET_CLOSURE_FLAGS = 15;
constexpr int32_t META_OFFSET_NUM_RECORDS = 24;
constexpr int32_t META_OFFSET_EFF_DATA_SIZE = 32;
constexpr int32_t META_OFFSET_FILE_SIZE = 40;
constexpr int32_t META_OFFSET_MOD_TIME = 48;
constexpr int32_t META_OFFSET_DB_TYPE = 56;
constexpr int32_t META_OFFSET_OPAQUE = 62;
constexpr int32_t META_OFFSET_CYCLIC_MAGIC_BACK = 127;
constexpr int32_t MIN_OFFSET_WIDTH = 3;
constexpr int32_t MAX_OFFSET_WIDTH = 6;
constexpr int32_t MIN_STEP_UNIT = 2;
constexpr int32_t MAX_STEP_UNIT = 64;
constexpr int32_t MIN_MAX_LEVEL = 1;
constexpr int32_t MAX_MAX_LEVEL = 32;
constexpr int64_t MIN_SORT_MEM_SIZE = 1LL << 10;
constexpr int64_t MAX_SORT_MEM_SIZE = 8LL << 30;
constexpr int32_t MIN_MAX_CACHED_RECORDS = 1;
constexpr int32_t MAX_MAX_CACHED_RECORDS = 1 << 24;
constexpr int64_t MIN_DIO_BLOCK_SIZE = 512;
const char* REBUILD_FILE_SUFFIX = ".tmp.rebuild";
const char* SORTER_FILE_SUFFIX = ".tmp.sorter";
const char* SORTED_FILE_SUFFIX = ".tmp.sorted";
const char* MERGED_FILE_SUFFIX = ".tmp.merged";
enum ClosureFlag : uint8_t {
CLOSURE_FLAG_NONE = 0,
CLOSURE_FLAG_CLOSE = 1 << 0,
};
class SkipDBMImpl final {
friend class SkipDBMIteratorImpl;
typedef std::list<SkipDBMIteratorImpl*> IteratorList;
public:
SkipDBMImpl(std::unique_ptr<File> file);
~SkipDBMImpl();
Status Open(const std::string& path, bool writable,
int32_t options, const SkipDBM::TuningParameters& tuning_params);
Status Close();
Status Process(std::string_view key, DBM::RecordProcessor* proc, bool writable);
Status Insert(std::string_view key, std::string_view value);
Status GetByIndex(int64_t index, std::string* key, std::string* value);
Status ProcessMulti(
const std::vector<std::pair<std::string_view, DBM::RecordProcessor*>>& key_proc_pairs,
bool writable);
Status ProcessEach(DBM::RecordProcessor* proc, bool writable);
Status Count(int64_t* count);
Status GetFileSize(int64_t* size);
Status GetFilePath(std::string* path);
Status Clear();
Status Rebuild(const SkipDBM::TuningParameters& tuning_params);
Status ShouldBeRebuilt(bool* tobe);
Status Synchronize(bool hard, DBM::FileProcessor* proc, SkipDBM::ReducerType reducer);
std::vector<std::pair<std::string, std::string>> Inspect();
bool IsOpen();
bool IsWritable();
bool IsHealthy();
bool IsAutoRestored();
std::unique_ptr<DBM> MakeDBM();
const File* GetInternalFile();
int64_t GetEffectiveDataSize();
double GetModificationTime();
int32_t GetDatabaseType();
Status SetDatabaseTypeMetadata(uint32_t db_type);
std::string GetOpaqueMetadata();
Status SetOpaqueMetadata(const std::string& opaque);
Status Revert();
bool IsUpdated();
Status MergeSkipDatabase(const std::string& src_path);
Status ValidateRecords();
private:
void CancelIterators();
Status SaveMetadata(File* file, bool finish);
Status LoadMetadata();
Status CheckFileBeforeOpen(File* file, const std::string& path, bool writable);
Status CheckZeroRegion(int64_t offset, int64_t end_offset);
Status PadFileForDirectIO();
Status PrepareStorage();
Status FinishStorage(SkipDBM::ReducerType reducer);
Status DiscardStorage();
Status UpdateRecord(std::string_view key, std::string_view new_value);
Status WriteRecord(std::string_view key, std::string_view value, File* file);
Status ProcessImpl(std::string_view key, DBM::RecordProcessor* proc, bool writable);
bool open_;
bool writable_;
bool healthy_;
bool auto_restored_;
bool updated_;
bool removed_;
std::string path_;
int32_t cyclic_magic_;
int32_t pkg_major_version_;
int32_t pkg_minor_version_;
int32_t offset_width_;
int32_t step_unit_;
int32_t max_level_;
int32_t closure_flags_;
int64_t num_records_;
int64_t eff_data_size_;
int64_t file_size_;
int64_t mod_time_;
int32_t db_type_;
std::string opaque_;
IteratorList iterators_;
std::unique_ptr<File> file_;
std::unique_ptr<File> sorted_file_;
int64_t record_index_;
int64_t sort_mem_size_;
bool insert_in_order_;
int32_t max_cached_records_;
std::unique_ptr<RecordSorter> record_sorter_;
std::vector<int64_t> past_offsets_;
std::unique_ptr<SkipRecordCache> cache_;
int64_t old_num_records_;
int64_t old_eff_data_size_;
SpinSharedMutex mutex_;
};
class SkipDBMIteratorImpl final {
friend class SkipDBMImpl;
public:
explicit SkipDBMIteratorImpl(SkipDBMImpl* dbm);
~SkipDBMIteratorImpl();
Status First();
Status Last();
Status Jump(std::string_view key);
Status JumpLower(std::string_view key, bool inclusive);
Status JumpUpper(std::string_view key, bool inclusive);
Status Next();
Status Previous();
Status Process(DBM::RecordProcessor* proc, bool writable);
Status Get(std::string* key, std::string* value);
private:
void ClearPosition();
SkipDBMImpl* dbm_;
int64_t record_offset_;
int64_t record_index_;
int32_t record_size_;
};
SkipDBMImpl::SkipDBMImpl(std::unique_ptr<File> file)
: open_(false), writable_(false), healthy_(false), auto_restored_(false),
updated_(false), removed_(false), path_(),
cyclic_magic_(0), pkg_major_version_(0), pkg_minor_version_(0),
offset_width_(SkipDBM::DEFAULT_OFFSET_WIDTH), step_unit_(SkipDBM::DEFAULT_STEP_UNIT),
max_level_(SkipDBM::DEFAULT_MAX_LEVEL), closure_flags_(CLOSURE_FLAG_NONE),
num_records_(0), eff_data_size_(0), file_size_(0), mod_time_(0),
db_type_(0), opaque_(), iterators_(),
file_(std::move(file)), sorted_file_(nullptr), record_index_(0),
sort_mem_size_(SkipDBM::DEFAULT_SORT_MEM_SIZE), insert_in_order_(false),
max_cached_records_(SkipDBM::DEFAULT_MAX_CACHED_RECORDS),
record_sorter_(nullptr), past_offsets_(),
old_num_records_(0), old_eff_data_size_(0),
mutex_() {}
SkipDBMImpl::~SkipDBMImpl() {
if (open_) {
Close();
}
for (auto* iterator : iterators_) {
iterator->dbm_ = nullptr;
}
}
Status SkipDBMImpl::Open(const std::string& path, bool writable,
int32_t options, const SkipDBM::TuningParameters& tuning_params) {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (open_) {
return Status(Status::PRECONDITION_ERROR, "opened database");
}
const std::string norm_path = NormalizePath(path);
if (tuning_params.offset_width >= 0) {
offset_width_ = std::min(std::max(static_cast<int32_t>(
tuning_params.offset_width), MIN_OFFSET_WIDTH), MAX_OFFSET_WIDTH);
}
if (tuning_params.step_unit >= 0) {
step_unit_ = std::min(std::max(static_cast<int32_t>(
tuning_params.step_unit), MIN_STEP_UNIT), MAX_STEP_UNIT);
}
if (tuning_params.max_level >= 0) {
max_level_ = std::min(std::max(static_cast<int32_t>(
tuning_params.max_level), MIN_MAX_LEVEL), MAX_MAX_LEVEL);
}
if (tuning_params.sort_mem_size >= 0) {
sort_mem_size_ = std::min(std::max(static_cast<int64_t>(
tuning_params.sort_mem_size), MIN_SORT_MEM_SIZE), MAX_SORT_MEM_SIZE);
}
insert_in_order_ = tuning_params.insert_in_order;
if (tuning_params.max_cached_records > 0) {
max_cached_records_ = std::min(std::max(
tuning_params.max_cached_records, MIN_MAX_CACHED_RECORDS), MAX_MAX_CACHED_RECORDS);
}
Status status = CheckFileBeforeOpen(file_.get(), path, writable);
if (status != Status::SUCCESS) {
return status;
}
status = file_->Open(norm_path, writable, options);
if (status != Status::SUCCESS) {
return status;
}
if (writable && file_->GetSizeSimple() < 1) {
file_->Truncate(METADATA_SIZE);
const auto version_nums = StrSplit(PACKAGE_VERSION, '.');
pkg_major_version_ = version_nums.size() > 0 ? StrToInt(version_nums[0]) : 0;
pkg_minor_version_ = version_nums.size() > 1 ? StrToInt(version_nums[1]) : 0;
closure_flags_ |= CLOSURE_FLAG_CLOSE;
file_size_ = file_->GetSizeSimple();
mod_time_ = GetWallTime() * 1000000;
const Status status = SaveMetadata(file_.get(), true);
if (status != Status::SUCCESS) {
return status;
}
}
status = LoadMetadata();
if (status != Status::SUCCESS) {
file_->Close();
return status;
}
if (cyclic_magic_ < 0) {
file_size_ = INT64MAX;
}
bool healthy = closure_flags_ & CLOSURE_FLAG_CLOSE;
bool invalid_file_size = false;
const int64_t act_file_size = file_->GetSizeSimple();
if (file_size_ != act_file_size) {
if (file_size_ > act_file_size) {
healthy = false;
invalid_file_size = true;
} else if (file_size_ > 0) {
if (CheckZeroRegion(file_size_, act_file_size) == Status::SUCCESS) {
status = writable ? file_->Truncate(file_size_) : file_->TruncateFakely(file_size_);
if (status != Status::SUCCESS) {
healthy = false;
}
} else {
healthy = false;
invalid_file_size = true;
}
}
}
auto_restored_ = false;
if (writable && !healthy && tuning_params.restore_mode != SkipDBM::RESTORE_READ_ONLY) {
if (invalid_file_size && tuning_params.restore_mode != SkipDBM::RESTORE_NOOP) {
file_->Close();
const std::string tmp_path = norm_path + ".tmp.restore";
RemoveFile(tmp_path);
status = SkipDBM::RestoreDatabase(norm_path, tmp_path);
if (status != Status::SUCCESS) {
RemoveFile(tmp_path);
return status;
}
status = RenameFile(tmp_path, norm_path);
if (status != Status::SUCCESS) {
RemoveFile(tmp_path);
return status;
}
status = file_->Open(norm_path, writable, options);
if (status != Status::SUCCESS) {
return status;
}
status = LoadMetadata();
if (status != Status::SUCCESS) {
file_->Close();
return status;
}
} else {
closure_flags_ |= CLOSURE_FLAG_CLOSE;
}
healthy = true;
auto_restored_ = true;
}
path_ = norm_path;
if (writable && healthy) {
status = SaveMetadata(file_.get(), false);
if (status != Status::SUCCESS) {
path_ .clear();
return status;
}
status = PrepareStorage();
if (status != Status::SUCCESS) {
path_ .clear();
return status;
}
}
cache_ = std::make_unique<SkipRecordCache>(step_unit_, max_cached_records_, num_records_);
open_ = true;
writable_ = writable;
healthy_ = healthy;
updated_ = false;
removed_ = false;
return Status(Status::SUCCESS);
}
Status SkipDBMImpl::Close() {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
CancelIterators();
Status status(Status::SUCCESS);
if (writable_ && healthy_) {
if (updated_) {
status |= FinishStorage(nullptr);
} else {
status |= DiscardStorage();
file_size_ = file_->GetSizeSimple();
mod_time_ = GetWallTime() * 1000000;
status |= SaveMetadata(file_.get(), true);
}
}
status |= file_->Close();
open_ = false;
writable_ = false;
healthy_ = false;
auto_restored_ = false;
updated_ = false;
removed_ = false;
path_.clear();
pkg_major_version_ = 0;
pkg_minor_version_ = 0;
offset_width_ = SkipDBM::DEFAULT_OFFSET_WIDTH;
step_unit_ = SkipDBM::DEFAULT_STEP_UNIT;
max_level_ = SkipDBM::DEFAULT_MAX_LEVEL;
closure_flags_ = CLOSURE_FLAG_NONE;
num_records_ = 0;
eff_data_size_ = 0;
file_size_ = 0;
mod_time_ = 0;
db_type_ = 0;
opaque_.clear();
sort_mem_size_ = SkipDBM::DEFAULT_SORT_MEM_SIZE;
insert_in_order_ = false;
record_sorter_.reset(nullptr);
past_offsets_.clear();
cache_.reset(nullptr);
old_num_records_ = 0;
old_eff_data_size_ = 0;
return status;
}
Status SkipDBMImpl::Process(std::string_view key, DBM::RecordProcessor* proc, bool writable) {
if (writable) {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
if (!healthy_) {
return Status(Status::PRECONDITION_ERROR, "not healthy database");
}
Status status = ProcessImpl(key, proc, true);
if (status != Status::SUCCESS) {
return status;
}
} else {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
Status status = ProcessImpl(key, proc, false);
if (status != Status::SUCCESS) {
return status;
}
}
return Status(Status::SUCCESS);
}
Status SkipDBMImpl::Insert(std::string_view key, std::string_view value) {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
if (!healthy_) {
return Status(Status::PRECONDITION_ERROR, "not healthy database");
}
return UpdateRecord(key, value);
}
Status SkipDBMImpl::GetByIndex(int64_t index, std::string* key, std::string* value) {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
SkipRecord rec(file_.get(), offset_width_, step_unit_, max_level_);
Status status = rec.SearchByIndex(METADATA_SIZE, cache_.get(), index);
if (status != Status::SUCCESS) {
return status;
}
if (key != nullptr) {
*key = rec.GetKey();
}
if (value != nullptr) {
std::string_view rec_value = rec.GetValue();
if (rec_value.data() == nullptr) {
status = rec.ReadBody();
if (status != Status::SUCCESS) {
return status;
}
rec_value = rec.GetValue();
}
*value = rec_value;
}
return Status(Status::SUCCESS);
}
Status SkipDBMImpl::ProcessMulti(
const std::vector<std::pair<std::string_view, DBM::RecordProcessor*>>& key_proc_pairs,
bool writable) {
if (writable) {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
if (!healthy_) {
return Status(Status::PRECONDITION_ERROR, "not healthy database");
}
for (const auto& key_proc : key_proc_pairs) {
Status status = ProcessImpl(key_proc.first, key_proc.second, true);
if (status != Status::SUCCESS) {
return status;
}
}
} else {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
for (const auto& key_proc : key_proc_pairs) {
Status status = ProcessImpl(key_proc.first, key_proc.second, false);
if (status != Status::SUCCESS) {
return status;
}
}
}
return Status(Status::SUCCESS);
}
Status SkipDBMImpl::ProcessEach(DBM::RecordProcessor* proc, bool writable) {
if (writable) {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
if (!healthy_) {
return Status(Status::PRECONDITION_ERROR, "not healthy database");
}
proc->ProcessEmpty(DBM::RecordProcessor::NOOP);
const int64_t end_offset = file_->GetSizeSimple();
int64_t offset = METADATA_SIZE;
int64_t index = 0;
tkrzw::SkipRecord rec(file_.get(), offset_width_, step_unit_, max_level_);
while (offset < end_offset) {
Status status = rec.ReadMetadataKey(offset, index);
if (status != Status::SUCCESS) {
return status;
}
const std::string_view key = rec.GetKey();
std::string_view value = rec.GetValue();
if (value.data() == nullptr) {
status = rec.ReadBody();
if (status != Status::SUCCESS) {
return status;
}
value = rec.GetValue();
}
std::string_view new_value = proc->ProcessFull(key, value);
status = UpdateRecord(key, new_value);
if (status != Status::SUCCESS) {
return status;
}
offset += rec.GetWholeSize();
index++;
}
proc->ProcessEmpty(DBM::RecordProcessor::NOOP);
} else {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
proc->ProcessEmpty(DBM::RecordProcessor::NOOP);
SkipRecord rec(file_.get(), offset_width_, step_unit_, max_level_);
const int64_t end_offset = file_->GetSizeSimple();
int64_t offset = METADATA_SIZE;
int64_t index = 0;
while (offset < end_offset) {
Status status = rec.ReadMetadataKey(offset, index);
if (status != Status::SUCCESS) {
return status;
}
const std::string_view key = rec.GetKey();
std::string_view value = rec.GetValue();
if (value.data() == nullptr) {
status = rec.ReadBody();
if (status != Status::SUCCESS) {
return status;
}
value = rec.GetValue();
}
proc->ProcessFull(key, value);
offset += rec.GetWholeSize();
index++;
}
proc->ProcessEmpty(DBM::RecordProcessor::NOOP);
}
return Status(Status::SUCCESS);
}
Status SkipDBMImpl::Count(int64_t* count) {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
*count = num_records_;
return Status(Status::SUCCESS);
}
Status SkipDBMImpl::GetFileSize(int64_t* size) {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
*size = file_->GetSizeSimple();
return Status(Status::SUCCESS);
}
Status SkipDBMImpl::GetFilePath(std::string* path) {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
*path = path_;
return Status(Status::SUCCESS);
}
Status SkipDBMImpl::Clear() {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
if (updated_) {
const Status status = FinishStorage(nullptr);
if (status != Status::SUCCESS) {
return status;
}
}
if (updated_) {
const Status status = DiscardStorage();
if (status != Status::SUCCESS) {
return status;
}
}
CancelIterators();
Status status = file_->Truncate(METADATA_SIZE);
num_records_ = 0;
eff_data_size_ = 0;
file_size_ = file_->GetSizeSimple();
mod_time_ = GetWallTime() * 1000000;
status |= SaveMetadata(file_.get(), false);
status |= LoadMetadata();
status |= PrepareStorage();
cache_ = std::make_unique<SkipRecordCache>(step_unit_, max_cached_records_, num_records_);
return status;
}
Status SkipDBMImpl::Rebuild(const SkipDBM::TuningParameters& tuning_params) {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
if (updated_) {
const Status status = FinishStorage(nullptr);
if (status != Status::SUCCESS) {
return status;
}
}
int32_t step_unit = tuning_params.step_unit;
if (step_unit < static_cast<int32_t>(MIN_STEP_UNIT) ||
step_unit > static_cast<int32_t>(MAX_STEP_UNIT)) {
step_unit = SkipDBM::DEFAULT_STEP_UNIT;
}
int32_t max_level = tuning_params.max_level;
if (max_level < static_cast<int32_t>(MIN_MAX_LEVEL) ||
max_level > static_cast<int32_t>(MAX_MAX_LEVEL)) {
max_level = std::ceil(std::log(num_records_ + 1) / std::log(step_unit));
max_level = std::min(std::max(max_level, static_cast<int32_t>(MIN_MAX_LEVEL)),
static_cast<int32_t>(MAX_MAX_LEVEL));
}
int64_t num_links = 0;
for (int32_t level = 1; level <= max_level; ++level) {
num_links += num_records_ / std::pow(step_unit, level) + 1;
}
int32_t offset_width = tuning_params.offset_width;
if (offset_width < 1) {
for (offset_width = MIN_OFFSET_WIDTH;
offset_width < static_cast<int32_t>(MAX_OFFSET_WIDTH); offset_width++) {
const int64_t max_file_size = (1LL << (8 * offset_width)) * 0.8;
const int64_t expected_file_size = METADATA_SIZE + num_records_ * sizeof(uint8_t) * 6 +
num_links * offset_width + eff_data_size_;
if (expected_file_size < max_file_size) {
break;
}
}
}
SkipDBM::TuningParameters tmp_tuning_params;
tmp_tuning_params.offset_width = offset_width;
tmp_tuning_params.step_unit = step_unit;
tmp_tuning_params.max_level = max_level;
tmp_tuning_params.insert_in_order = true;
const std::string rebuild_path = path_ + REBUILD_FILE_SUFFIX;
SkipDBM tmp_dbm(file_->MakeFile());
auto CleanUp = [&]() {
tmp_dbm.Close();
RemoveFile(rebuild_path);
};
Status status =
tmp_dbm.OpenAdvanced(rebuild_path, true, File::OPEN_TRUNCATE, tmp_tuning_params);
if (status != Status::SUCCESS) {
CleanUp();
return status;
}
const int64_t end_offset = file_->GetSizeSimple();
int64_t offset = METADATA_SIZE;
int64_t index = 0;
tkrzw::SkipRecord rec(file_.get(), offset_width_, step_unit_, max_level_);
while (offset < end_offset) {
status = rec.ReadMetadataKey(offset, index);
if (status != Status::SUCCESS) {
CleanUp();
return status;
}
const std::string_view key = rec.GetKey();
std::string_view value = rec.GetValue();
if (value.data() == nullptr) {
status = rec.ReadBody();
if (status != Status::SUCCESS) {
CleanUp();
return status;
}
value = rec.GetValue();
}
status = tmp_dbm.Set(key, value);
if (status != Status::SUCCESS) {
CleanUp();
return status;
}
offset += rec.GetWholeSize();
index++;
}
status = tmp_dbm.Close();
if (status != Status::SUCCESS) {
CleanUp();
return status;
}
CancelIterators();
auto rebuild_file = file_->MakeFile();
file_->CopyProperties(rebuild_file.get());
status = rebuild_file->Open(rebuild_path, true);
if (status != Status::SUCCESS) {
CleanUp();
return status;
}
status |= file_->DisablePathOperations();
if (IS_POSIX) {
status |= rebuild_file->Rename(path_);
status |= file_->Close();
} else {
status |= file_->Close();
status |= rebuild_file->Rename(path_);
}
file_ = std::move(rebuild_file);
const uint32_t db_type = db_type_;
const std::string opaque = opaque_;
LoadMetadata();
db_type_ = db_type;
opaque_ = opaque;
file_size_ = file_->GetSizeSimple();
status |= SaveMetadata(file_.get(), false);
status |= PrepareStorage();
cache_ = std::make_unique<SkipRecordCache>(step_unit_, max_cached_records_, num_records_);
return status;
}
Status SkipDBMImpl::ShouldBeRebuilt(bool* tobe) {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
*tobe = false;
if (num_records_ > std::pow(step_unit_, max_level_ + 1)) {
*tobe = true;
}
if (offset_width_ > MIN_OFFSET_WIDTH &&
file_->GetSizeSimple() * 2 < (1LL << (8 * (offset_width_ - 1)))) {
*tobe = true;
}
return Status(Status::SUCCESS);
}
Status SkipDBMImpl::Synchronize(
bool hard, DBM::FileProcessor* proc, SkipDBM::ReducerType reducer) {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
if (!healthy_) {
return Status(Status::PRECONDITION_ERROR, "not healthy database");
}
CancelIterators();
Status status = FinishStorage(reducer);
status |= file_->Synchronize(hard);
if (proc != nullptr) {
proc->Process(path_);
}
status |= SaveMetadata(file_.get(), false);
status |= PrepareStorage();
cache_ = std::make_unique<SkipRecordCache>(step_unit_, max_cached_records_, num_records_);
return status;
}
std::vector<std::pair<std::string, std::string>> SkipDBMImpl::Inspect() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
std::vector<std::pair<std::string, std::string>> meta;
auto Add = [&](const std::string& name, const std::string& value) {
meta.emplace_back(std::make_pair(name, value));
};
Add("class", "SkipDBM");
if (open_) {
Add("healthy", ToString(healthy_));
Add("auto_restored", ToString(auto_restored_));
Add("updated", ToString(updated_));
Add("removed", ToString(removed_));
Add("path", path_);
Add("cyclic_magic", ToString(static_cast<uint8_t>(cyclic_magic_)));
Add("pkg_major_version", ToString(pkg_major_version_));
Add("pkg_minor_version", ToString(pkg_minor_version_));
Add("offset_width", ToString(offset_width_));
Add("step_unit", ToString(step_unit_));
Add("max_level", ToString(max_level_));
Add("closure_flags", ToString(closure_flags_));
Add("num_records", ToString(num_records_));
Add("eff_data_size", ToString(eff_data_size_));
Add("file_size", ToString(file_->GetSizeSimple()));
Add("mod_time", ToString(mod_time_ / 1000000.0));
Add("db_type", ToString(db_type_));
Add("sort_mem_size", ToString(sort_mem_size_));
Add("max_file_size", ToString(1LL << (offset_width_ * 8)));
Add("insert_in_order", ToString(insert_in_order_));
Add("record_base", ToString(METADATA_SIZE));
}
return meta;
}
bool SkipDBMImpl::IsOpen() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
return open_;
}
bool SkipDBMImpl::IsWritable() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
return open_ && writable_;
}
bool SkipDBMImpl::IsHealthy() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
return open_ && healthy_;
}
bool SkipDBMImpl::IsAutoRestored() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
return open_ && auto_restored_;
}
std::unique_ptr<DBM> SkipDBMImpl::MakeDBM() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
return std::make_unique<SkipDBM>(file_->MakeFile());
}
const File* SkipDBMImpl::GetInternalFile() {
return file_.get();
}
int64_t SkipDBMImpl::GetEffectiveDataSize() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return -1;
}
return eff_data_size_;
}
double SkipDBMImpl::GetModificationTime() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return -1;
}
return mod_time_ / 1000000.0;
}
int32_t SkipDBMImpl::GetDatabaseType() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return -1;
}
return db_type_;
}
Status SkipDBMImpl::SetDatabaseTypeMetadata(uint32_t db_type) {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
db_type_ = db_type;
return Status(Status::SUCCESS);
}
std::string SkipDBMImpl::GetOpaqueMetadata() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return "";
}
return opaque_;
}
Status SkipDBMImpl::SetOpaqueMetadata(const std::string& opaque) {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
opaque_ = opaque;
return Status(Status::SUCCESS);
}
Status SkipDBMImpl::Revert() {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
if (!healthy_) {
return Status(Status::PRECONDITION_ERROR, "not healthy database");
}
Status status = DiscardStorage();
status |= PrepareStorage();
return status;
}
bool SkipDBMImpl::IsUpdated() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
return open_ && updated_;
}
Status SkipDBMImpl::MergeSkipDatabase(const std::string& src_path) {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
if (!healthy_) {
return Status(Status::PRECONDITION_ERROR, "not healthy database");
}
uint32_t src_offset_width = 0;
uint32_t src_step_unit = 0;
uint32_t src_max_level = 0;
{
SkipDBMImpl src_impl(file_->MakeFile());
Status status =
src_impl.Open(src_path, false, File::OPEN_DEFAULT, SkipDBM::TuningParameters());
if (status != Status::SUCCESS) {
return status;
}
src_offset_width = src_impl.offset_width_;
src_step_unit = src_impl.step_unit_;
src_max_level = src_impl.max_level_;
status = src_impl.Close();
if (status != Status::SUCCESS) {
return status;
}
}
auto src_file = file_->MakeFile();
Status status = src_file->Open(src_path, false, File::OPEN_NO_LOCK);
if (status != Status::SUCCESS) {
return status;
}
record_sorter_->AddSkipRecord(new SkipRecord(
src_file.get(), src_offset_width, src_step_unit, src_max_level), METADATA_SIZE);
record_sorter_->TakeFileOwnership(std::move(src_file));
updated_ = true;
return Status(Status::SUCCESS);
}
Status SkipDBMImpl::ValidateRecords() {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
const int64_t end_offset = file_->GetSizeSimple();
int64_t offset = METADATA_SIZE;
int64_t index = 0;
tkrzw::SkipRecord rec(file_.get(), offset_width_, step_unit_, max_level_);
std::string last_key;
while (offset < end_offset) {
Status status = rec.ReadMetadataKey(offset, index);
if (status != Status::SUCCESS) {
return status;
}
const std::string_view key = rec.GetKey();
std::string_view value = rec.GetValue();
if (value.data() == nullptr) {
status = rec.ReadBody();
if (status != Status::SUCCESS) {
return status;
}
value = rec.GetValue();
}
offset += rec.GetWholeSize();
index++;
if (offset == end_offset || last_key != key) {
std::string tmp_key(key);
status = rec.Search(METADATA_SIZE, cache_.get(), tmp_key, false);
if (status != Status::SUCCESS) {
return status;
}
}
last_key = key;
}
return Status(Status::SUCCESS);
}
void SkipDBMImpl::CancelIterators() {