forked from estraier/tkrzw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tkrzw_dbm_hash.cc
2733 lines (2601 loc) · 92.8 KB
/
tkrzw_dbm_hash.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 hash table
*
* 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_compress.h"
#include "tkrzw_dbm.h"
#include "tkrzw_dbm_common_impl.h"
#include "tkrzw_dbm_hash.h"
#include "tkrzw_dbm_hash_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[] = "TkrzwHDB\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_STATIC_FLAGS = 12;
constexpr int32_t META_OFFSET_OFFSET_WIDTH = 13;
constexpr int32_t META_OFFSET_ALIGN_POW = 14;
constexpr int32_t META_OFFSET_CLOSURE_FLAGS = 15;
constexpr int32_t META_OFFSET_NUM_BUCKETS = 16;
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 FBP_SECTION_SIZE = 1008;
constexpr int32_t RECORD_BASE_HEADER_SIZE = 16;
const char RECORD_BASE_MAGIC_DATA[] = "TkrzwREC\n";
constexpr int32_t RECHEAD_OFFSET_STATIC_FLAGS = 9;
constexpr int32_t RECHEAD_OFFSET_OFFSET_WIDTH = 10;
constexpr int32_t RECHEAD_OFFSET_ALIGN_POW = 11;
constexpr int32_t RECORD_MUTEX_NUM_SLOTS = 256;
constexpr int32_t RECORD_BASE_ALIGN = 4096;
constexpr int32_t MIN_OFFSET_WIDTH = 3;
constexpr int32_t MAX_OFFSET_WIDTH = 6;
constexpr int32_t MAX_ALIGN_POW = 16;
constexpr int64_t MAX_NUM_BUCKETS = 1099511627689LL;
constexpr int32_t REBUILD_NONBLOCKING_MAX_TRIES = 3;
constexpr int64_t REBUILD_BLOCKING_ALLOWANCE = 65536;
constexpr int64_t MIN_DIO_BLOCK_SIZE = 512;
enum StaticFlag : uint8_t {
STATIC_FLAG_NONE = 0,
STATIC_FLAG_UPDATE_IN_PLACE = 1 << 0,
STATIC_FLAG_UPDATE_APPENDING = 1 << 1,
STATIC_FLAG_RECORD_CRC_8 = 1 << 2,
STATIC_FLAG_RECORD_CRC_16 = 1 << 3,
STATIC_FLAG_RECORD_CRC_32 = (1 << 2) | (1 << 3),
STATIC_FLAG_RECORD_COMP_ZLIB = 1 << 4,
STATIC_FLAG_RECORD_COMP_ZSTD = 1 << 5,
STATIC_FLAG_RECORD_COMP_LZ4 = (1 << 4) | (1 << 5),
STATIC_FLAG_RECORD_COMP_LZMA = 1 << 6,
STATIC_FLAG_RECORD_COMP_EXTRA = (1 << 4) | (1 << 5) | (1 << 6),
};
enum ClosureFlag : uint8_t {
CLOSURE_FLAG_NONE = 0,
CLOSURE_FLAG_CLOSE = 1 << 0,
};
class HashDBMImpl final {
friend class HashDBMIteratorImpl;
typedef std::list<HashDBMIteratorImpl*> IteratorList;
public:
HashDBMImpl(std::unique_ptr<File> file);
~HashDBMImpl();
Status Open(const std::string& path, bool writable,
int32_t options, const HashDBM::TuningParameters& tuning_params);
Status Close();
Status Process(
std::string_view key, DBM::RecordProcessor* proc, bool readable, bool writable);
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 HashDBM::TuningParameters& tuning_params, bool skip_broken_records);
Status ShouldBeRebuilt(bool* tobe);
Status Synchronize(bool hard, DBM::FileProcessor* proc);
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);
int64_t CountBuckets();
int64_t CountUsedBuckets();
HashDBM::UpdateMode GetUpdateMode();
Status SetUpdateModeAppending();
Status ImportFromFileForward(
const std::string& path, bool skip_broken_records,
int64_t record_base, int64_t end_offset);
Status ImportFromFileForward(
File* file, bool skip_broken_records,
int64_t record_base, int64_t end_offset);
Status ImportFromFileBackward(
const std::string& path, bool skip_broken_records,
int64_t record_base, int64_t end_offset);
Status ImportFromFileBackward(
File* file, bool skip_broken_records,
int64_t record_base, int64_t end_offset);
Status ValidateRecords(int64_t record_base, int64_t end_offset);
Status CheckZeroRegion(int64_t offset, int64_t end_offset);
Status CheckHashChain(int64_t offset, const HashRecord& rec, int64_t bucket_index);
private:
void SetTuning(const HashDBM::TuningParameters& tuning_params);
Status OpenImpl(bool writable);
Status CloseImpl();
void CancelIterators();
Status SaveMetadata(bool finish);
Status LoadMetadata();
void SetRecordBase();
Status CheckFileBeforeOpen(File* file, const std::string& path, bool writable);
Status TuneFileAfterOpen();
Status InitializeBuckets();
Status SaveFBP();
Status LoadFBP();
Status ProcessImpl(
std::string_view key, int64_t bucket_index, DBM::RecordProcessor* proc,
bool readable, bool writable);
Status GetBucketValue(int64_t bucket_index, int64_t* value);
Status SetBucketValue(int64_t bucket_index, int64_t value);
Status RebuildImpl(const HashDBM::TuningParameters& tuning_params, bool skip_broken_records);
Status ReadNextBucketRecords(HashDBMIteratorImpl* iter);
Status ImportFromFileForwardImpl(
File* file, bool skip_broken_records,
int64_t record_base, int64_t end_offset);
Status ImportFromFileBackwardImpl(
File* file, bool skip_broken_records,
int64_t record_base, int64_t end_offset,
const std::string& offset_path, const std::string& dead_path);
Status ValidateRecordsImpl(int64_t record_base, int64_t end_offset,
int64_t* null_end_offset, int64_t* count, int64_t* eff_data_size);
bool open_;
bool writable_;
bool healthy_;
bool auto_restored_;
std::string path_;
int32_t cyclic_magic_;
int32_t pkg_major_version_;
int32_t pkg_minor_version_;
int32_t static_flags_;
int32_t crc_width_;
std::unique_ptr<Compressor> compressor_;
int32_t offset_width_;
int32_t align_pow_;
int32_t closure_flags_;
int64_t num_buckets_;
std::atomic_int64_t num_records_;
std::atomic_int64_t eff_data_size_;
int64_t file_size_;
int64_t mod_time_;
int32_t db_type_;
std::string opaque_;
int64_t record_base_;
IteratorList iterators_;
FreeBlockPool fbp_;
int32_t min_read_size_;
bool lock_mem_buckets_;
bool cache_buckets_;
std::unique_ptr<File> file_;
SpinSharedMutex mutex_;
HashMutex<SpinSharedMutex> record_mutex_;
SpinMutex rebuild_mutex_;
};
class HashDBMIteratorImpl final {
friend class HashDBMImpl;
public:
explicit HashDBMIteratorImpl(HashDBMImpl* dbm);
~HashDBMIteratorImpl();
Status First();
Status Jump(std::string_view key);
Status Next();
Status Process(DBM::RecordProcessor* proc, bool writable);
private:
Status ReadKeys();
HashDBMImpl* dbm_;
std::atomic_int64_t bucket_index_;
std::set<std::string> keys_;
};
HashDBMImpl::HashDBMImpl(std::unique_ptr<File> file)
: open_(false), writable_(false), healthy_(false), auto_restored_(false), path_(),
cyclic_magic_(0), pkg_major_version_(0), pkg_minor_version_(0),
static_flags_(STATIC_FLAG_NONE), crc_width_(0), compressor_(nullptr),
offset_width_(HashDBM::DEFAULT_OFFSET_WIDTH), align_pow_(HashDBM::DEFAULT_ALIGN_POW),
closure_flags_(CLOSURE_FLAG_NONE),
num_buckets_(HashDBM::DEFAULT_NUM_BUCKETS),
num_records_(0), eff_data_size_(0), file_size_(0), mod_time_(0),
db_type_(0), opaque_(),
record_base_(0), iterators_(),
fbp_(HashDBM::DEFAULT_FBP_CAPACITY), min_read_size_(0),
lock_mem_buckets_(false), cache_buckets_(false),
file_(std::move(file)),
mutex_(), record_mutex_(RECORD_MUTEX_NUM_SLOTS, 1, PrimaryHash),
rebuild_mutex_() {}
HashDBMImpl::~HashDBMImpl() {
if (open_) {
Close();
}
for (auto* iterator : iterators_) {
iterator->dbm_ = nullptr;
}
}
Status HashDBMImpl::Open(const std::string& path, bool writable,
int32_t options, const HashDBM::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);
SetTuning(tuning_params);
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;
}
path_ = norm_path;
status = OpenImpl(writable);
if (status != Status::SUCCESS) {
file_->Close();
return status;
}
const int64_t act_file_size = file_->GetSizeSimple();
int64_t null_end_offset = 0;
int64_t act_count = 0;
int64_t act_eff_data_size = 0;
auto_restored_ = false;
if (writable && !healthy_ && tuning_params.restore_mode != HashDBM::RESTORE_READ_ONLY) {
if (tuning_params.restore_mode == HashDBM::RESTORE_NOOP) {
healthy_ = true;
closure_flags_ |= CLOSURE_FLAG_CLOSE;
} else if ((static_flags_ & STATIC_FLAG_UPDATE_APPENDING) &&
file_size_ == act_file_size) {
healthy_ = true;
closure_flags_ |= CLOSURE_FLAG_CLOSE;
} else if (tuning_params.restore_mode == HashDBM::RESTORE_DEFAULT &&
(static_flags_ & STATIC_FLAG_UPDATE_IN_PLACE) &&
file_size_ <= act_file_size &&
ValidateRecordsImpl(record_base_, act_file_size,
&null_end_offset, &act_count, &act_eff_data_size) ==
Status::SUCCESS) {
num_records_.store(act_count);
eff_data_size_.store(act_eff_data_size);
if (null_end_offset > 0) {
status = file_->Truncate(null_end_offset);
if (status != Status::SUCCESS) {
file_->Close();
return status;
}
}
healthy_ = true;
closure_flags_ |= CLOSURE_FLAG_CLOSE;
auto_restored_ = true;
} else if (tuning_params.restore_mode == HashDBM::RESTORE_DEFAULT &&
(static_flags_ & STATIC_FLAG_UPDATE_APPENDING) &&
file_size_ <= act_file_size &&
ValidateRecordsImpl(file_size_, act_file_size,
&null_end_offset, &act_count, &act_eff_data_size) ==
Status::SUCCESS) {
num_records_.fetch_add(act_count);
if (null_end_offset > 0) {
status = file_->Truncate(null_end_offset);
if (status != Status::SUCCESS) {
file_->Close();
return status;
}
}
healthy_ = true;
closure_flags_ |= CLOSURE_FLAG_CLOSE;
auto_restored_ = true;
} else {
CloseImpl();
file_->Close();
const std::string tmp_path = path_ + ".tmp.restore";
const int64_t end_offset = tuning_params.restore_mode == HashDBM::RESTORE_SYNC ? 0 : -1;
RemoveFile(tmp_path);
status = HashDBM::RestoreDatabase(path_, tmp_path, end_offset);
if (status != Status::SUCCESS) {
RemoveFile(tmp_path);
return status;
}
status = RenameFile(tmp_path, path_);
if (status != Status::SUCCESS) {
RemoveFile(tmp_path);
return status;
}
SetTuning(tuning_params);
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;
}
status = OpenImpl(writable);
if (status != Status::SUCCESS) {
file_->Close();
return status;
}
auto_restored_ = true;
}
}
return Status(Status::SUCCESS);
}
Status HashDBMImpl::Close() {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
CancelIterators();
Status status(Status::SUCCESS);
status |= CloseImpl();
status |= file_->Close();
path_.clear();
return status;
}
Status HashDBMImpl::Process(
std::string_view key, DBM::RecordProcessor* proc, bool readable, bool writable) {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (writable) {
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
if (!healthy_) {
return Status(Status::PRECONDITION_ERROR, "not healthy database");
}
}
ScopedHashLock record_lock(record_mutex_, key, writable);
const int64_t bucket_index = record_lock.GetBucketIndex();
return ProcessImpl(key, bucket_index, proc, readable, writable);
}
Status HashDBMImpl::ProcessMulti(
const std::vector<std::pair<std::string_view, DBM::RecordProcessor*>>& key_proc_pairs,
bool writable) {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (writable) {
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
if (!healthy_) {
return Status(Status::PRECONDITION_ERROR, "not healthy database");
}
}
std::vector<std::string_view> keys;
keys.reserve(key_proc_pairs.size());
for (const auto& pair : key_proc_pairs) {
keys.emplace_back(pair.first);
}
ScopedHashLockMulti record_lock(record_mutex_, keys, writable);
const std::vector<int64_t>& bucket_indices = record_lock.GetBucketIndices();
for (size_t i = 0; i < key_proc_pairs.size(); i++) {
const auto& key_proc = key_proc_pairs[i];
const int64_t bucket_index = bucket_indices[i];
const Status status =
ProcessImpl(key_proc.first, bucket_index, key_proc.second, true, writable);
if (status != Status::SUCCESS) {
return status;
}
}
return Status(Status::SUCCESS);
}
Status HashDBMImpl::ProcessEach(DBM::RecordProcessor* proc, bool writable) {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (writable) {
if (!writable_) {
return Status(Status::PRECONDITION_ERROR, "not writable database");
}
if (!healthy_) {
return Status(Status::PRECONDITION_ERROR, "not healthy database");
}
}
if (!writable && (static_flags_ & STATIC_FLAG_UPDATE_IN_PLACE)) {
ScopedHashLock record_lock(record_mutex_, writable);
proc->ProcessEmpty(DBM::RecordProcessor::NOOP);
const int64_t end_offset = file_->GetSizeSimple();
int64_t offset = record_base_;
HashRecord rec(file_.get(), crc_width_, offset_width_, align_pow_);
ScopedStringView comp_data_placeholder;
while (offset < end_offset) {
Status status = rec.ReadMetadataKey(offset, min_read_size_);
if (status != Status::SUCCESS) {
return status;
}
const std::string_view key = rec.GetKey();
if (rec.GetOperationType() == HashRecord::OP_SET ||
rec.GetOperationType() == HashRecord::OP_ADD) {
std::string_view value = rec.GetValue();
if (value.data() == nullptr) {
status = rec.ReadBody();
if (status != Status::SUCCESS) {
return status;
}
value = rec.GetValue();
}
const std::string_view new_value = CallRecordProcessFull(
proc, key, value, compressor_.get(), &comp_data_placeholder);
if (new_value.data() == nullptr) {
return Status(Status::BROKEN_DATA_ERROR, "record processing failed");
}
}
offset += rec.GetWholeSize();
}
proc->ProcessEmpty(DBM::RecordProcessor::NOOP);
return Status(Status::SUCCESS);
}
ScopedHashLock record_lock(record_mutex_, writable);
proc->ProcessEmpty(DBM::RecordProcessor::NOOP);
for (int64_t bucket_index = 0; bucket_index < num_buckets_; bucket_index++) {
int64_t current_offset = 0;
Status status = GetBucketValue(bucket_index, ¤t_offset);
if (status != Status::SUCCESS) {
return status;
}
if (current_offset == 0) {
continue;
}
std::set<std::string> keys, dead_keys;
while (current_offset > 0) {
HashRecord rec(file_.get(), crc_width_, offset_width_, align_pow_);
ScopedStringView comp_data_placeholder;
status = rec.ReadMetadataKey(current_offset, min_read_size_);
if (status != Status::SUCCESS) {
return status;
}
current_offset = rec.GetChildOffset();
const std::string key(rec.GetKey());
if (CheckSet(keys, key) || CheckSet(dead_keys, key)) {
continue;
}
switch (rec.GetOperationType()) {
case HashRecord::OP_SET:
case HashRecord::OP_ADD:
if (!writable) {
std::string_view value = rec.GetValue();
if (value.data() == nullptr) {
status = rec.ReadBody();
if (status != Status::SUCCESS) {
return status;
}
value = rec.GetValue();
}
const std::string_view new_value = CallRecordProcessFull(
proc, key, value, compressor_.get(), &comp_data_placeholder);
if (new_value.data() == nullptr) {
return Status(Status::BROKEN_DATA_ERROR, "record processing failed");
}
}
keys.emplace(std::move(key));
break;
case HashRecord::OP_REMOVE:
dead_keys.emplace(std::move(key));
break;
default:
break;
}
}
if (writable) {
for (const auto& key : keys) {
status = ProcessImpl(key, bucket_index, proc, true, true);
if (status != Status::SUCCESS) {
return status;
}
}
}
}
proc->ProcessEmpty(DBM::RecordProcessor::NOOP);
return Status(Status::SUCCESS);
}
Status HashDBMImpl::Count(int64_t* count) {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
*count = num_records_.load();
return Status(Status::SUCCESS);
}
Status HashDBMImpl::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 HashDBMImpl::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 HashDBMImpl::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");
}
const uint32_t static_flags = static_flags_;
const int32_t offset_width = offset_width_;
const int32_t align_pow = align_pow_;
const int64_t num_buckets = num_buckets_;
const int32_t min_read_size = min_read_size_;
const bool lock_mem_buckets = lock_mem_buckets_;
const bool cache_buckets = cache_buckets_;
const uint32_t db_type = db_type_;
const std::string opaque = opaque_;
CancelIterators();
Status status = CloseImpl();
status |= file_->Truncate(0);
static_flags_ = static_flags;
offset_width_ = offset_width;
align_pow_ = align_pow;
num_buckets_ = num_buckets;
min_read_size_ = min_read_size;
lock_mem_buckets_ = lock_mem_buckets;
cache_buckets_ = cache_buckets;
db_type_ = db_type;
opaque_ = opaque;
status |= OpenImpl(true);
return status;
}
Status HashDBMImpl::Rebuild(
const HashDBM::TuningParameters& tuning_params, bool skip_broken_records) {
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 (!rebuild_mutex_.try_lock()) {
return Status(Status::SUCCESS);
}
const Status status = RebuildImpl(tuning_params, skip_broken_records);
rebuild_mutex_.unlock();
return status;
}
Status HashDBMImpl::ShouldBeRebuilt(bool* tobe) {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (writable_) {
if (!rebuild_mutex_.try_lock()) {
*tobe = false;
return Status(Status::SUCCESS);
}
rebuild_mutex_.unlock();
}
const int64_t record_section_size = file_->GetSizeSimple() - record_base_;
const int64_t min_record_size = sizeof(uint8_t) + offset_width_ + sizeof(uint8_t) * 3;
const int64_t total_record_size = eff_data_size_.load() + min_record_size * num_records_.load();
const int64_t aligned_min_size = (1 << align_pow_) * num_records_.load();
const int64_t minimum_total_size = total_record_size + aligned_min_size;
if (record_section_size > minimum_total_size * 2) {
*tobe = true;
}
if (num_records_.load() > num_buckets_) {
*tobe = true;
}
return Status(Status::SUCCESS);
}
Status HashDBMImpl::Synchronize(bool hard, DBM::FileProcessor* proc) {
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");
}
file_size_ = file_->GetSizeSimple();
mod_time_ = GetWallTime() * 1000000;
Status status(Status::SUCCESS);
if (hard) {
status |= file_->Synchronize(true, record_base_, 0);
status |= SaveMetadata(true);
status |= file_->Synchronize(true, 0, record_base_);
} else {
status |= SaveMetadata(true);
status |= file_->Synchronize(false);
}
if (proc != nullptr) {
proc->Process(path_);
}
status |= SaveMetadata(false);
return status;
}
std::vector<std::pair<std::string, std::string>> HashDBMImpl::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", "HashDBM");
if (open_) {
Add("healthy", ToString(healthy_));
Add("auto_restored", ToString(auto_restored_));
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("static_flags", ToString(static_flags_));
Add("offset_width", ToString(offset_width_));
Add("align_pow", ToString(align_pow_));
Add("closure_flags", ToString(closure_flags_));
Add("num_buckets", ToString(num_buckets_));
Add("num_records", ToString(num_records_.load()));
Add("eff_data_size", ToString(eff_data_size_.load()));
Add("file_size", ToString(file_->GetSizeSimple()));
Add("mod_time", ToString(mod_time_ / 1000000.0));
Add("db_type", ToString(db_type_));
Add("max_file_size", ToString(1LL << (offset_width_ * 8 + align_pow_)));
Add("record_base", ToString(record_base_));
const char* update_mode = "unknown";
if (static_flags_ & STATIC_FLAG_UPDATE_IN_PLACE) {
update_mode = "in-place";
} else if (static_flags_ & STATIC_FLAG_UPDATE_APPENDING) {
update_mode = "appending";
}
Add("update_mode", update_mode);
const char* record_crc_mode = "none";
if (crc_width_ == 1) {
record_crc_mode = "crc-8";
} else if (crc_width_ == 2) {
record_crc_mode = "crc-16";
} else if (crc_width_ == 4) {
record_crc_mode = "crc-32";
}
Add("record_crc_mode", record_crc_mode);
const char* record_comp_mode = "none";
if (compressor_ != nullptr) {
const auto& comp_type = compressor_->GetType();
if (comp_type == typeid(ZLibCompressor)) {
record_comp_mode = "zlib";
} else if (comp_type == typeid(ZStdCompressor)) {
record_comp_mode = "zstd";
} else if (comp_type == typeid(LZ4Compressor)) {
record_comp_mode = "lz4";
} else if (comp_type == typeid(LZMACompressor)) {
record_comp_mode = "lzma";
} else {
record_comp_mode = "unknown";
}
}
Add("record_comp_mode", record_comp_mode);
}
return meta;
}
bool HashDBMImpl::IsOpen() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
return open_;
}
bool HashDBMImpl::IsWritable() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
return open_ && writable_;
}
bool HashDBMImpl::IsHealthy() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
return open_ && healthy_;
}
bool HashDBMImpl::IsAutoRestored() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
return open_ && auto_restored_;
}
std::unique_ptr<DBM> HashDBMImpl::MakeDBM() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
return std::make_unique<HashDBM>(file_->MakeFile());
}
const File* HashDBMImpl::GetInternalFile() {
return file_.get();
}
int64_t HashDBMImpl::GetEffectiveDataSize() {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return -1;
}
return eff_data_size_.load();
}
double HashDBMImpl::GetModificationTime() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return -1;
}
return mod_time_ / 1000000.0;
}
int32_t HashDBMImpl::GetDatabaseType() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return -1;
}
return db_type_;
}
Status HashDBMImpl::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 HashDBMImpl::GetOpaqueMetadata() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return "";
}
return opaque_;
}
Status HashDBMImpl::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);
}
int64_t HashDBMImpl::CountBuckets() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return -1;
}
return num_buckets_;
}
int64_t HashDBMImpl::CountUsedBuckets() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return -1;
}
int64_t num_used = 0;
int64_t bucket_index = 0;
while (bucket_index < num_buckets_) {
ScopedHashLock record_lock(record_mutex_, bucket_index, false);
if (record_lock.GetBucketIndex() < 0) {
num_used = 0;
bucket_index = 0;
continue;
}
int64_t offset = 0;
const Status status = GetBucketValue(bucket_index, &offset);
if (status != Status::SUCCESS) {
return -1;
}
if (offset != 0) {
num_used++;
}
bucket_index++;
}
return num_used;
}
HashDBM::UpdateMode HashDBMImpl::GetUpdateMode() {
std::shared_lock<SpinSharedMutex> lock(mutex_);
if (!open_) {
return HashDBM::UPDATE_DEFAULT;
}
HashDBM::UpdateMode mode = HashDBM::UPDATE_DEFAULT;
if (static_flags_ & STATIC_FLAG_UPDATE_IN_PLACE) {
mode = HashDBM::UPDATE_IN_PLACE;
} else if (static_flags_ & STATIC_FLAG_UPDATE_APPENDING) {
mode = HashDBM::UPDATE_APPENDING;
}
return mode;
}
Status HashDBMImpl::SetUpdateModeAppending() {
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");
}
static_flags_ &= ~STATIC_FLAG_UPDATE_IN_PLACE;
static_flags_ |= STATIC_FLAG_UPDATE_APPENDING;
return Status(Status::SUCCESS);
}
Status HashDBMImpl::ImportFromFileForward(
const std::string& path, bool skip_broken_records,
int64_t record_base, int64_t end_offset) {
{
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");
}
}
auto file = file_->MakeFile();
Status status = file->Open(path, false, File::OPEN_NO_LOCK);
if (status != Status::SUCCESS) {
return status;
}
status |= ImportFromFileForwardImpl(file.get(), skip_broken_records, record_base, end_offset);
status |= file->Close();
return status;
}
Status HashDBMImpl::ImportFromFileForward(
File* file, bool skip_broken_records,
int64_t record_base, int64_t end_offset) {
{
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");
}
}
return ImportFromFileForwardImpl(file, skip_broken_records, record_base, end_offset);
}
Status HashDBMImpl::ImportFromFileBackward(
const std::string& path, bool skip_broken_records,
int64_t record_base, int64_t end_offset) {
std::string offset_path, dead_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");
}
offset_path = path_ + ".tmp.offset";
dead_path = path_ + ".tmp.dead";
}
auto file = file_->MakeFile();
Status status = file->Open(path, false, File::OPEN_NO_LOCK);
if (status != Status::SUCCESS) {
return status;
}
status = ImportFromFileBackwardImpl(
file.get(), skip_broken_records, record_base, end_offset, offset_path, dead_path);
status |= file->Close();
return status;
}
Status HashDBMImpl::ImportFromFileBackward(
File* file, bool skip_broken_records,
int64_t record_base, int64_t end_offset) {
std::string offset_path, dead_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");
}
offset_path = path_ + ".tmp.offset";
dead_path = path_ + ".tmp.dead";
}
return ImportFromFileBackwardImpl(file, skip_broken_records, record_base, end_offset,
offset_path, dead_path);
}
Status HashDBMImpl::ValidateRecords(int64_t record_base, int64_t end_offset) {
std::lock_guard<SpinSharedMutex> lock(mutex_);
if (!open_) {
return Status(Status::PRECONDITION_ERROR, "not opened database");
}
if (record_base < 0) {
record_base = record_base_;
} else if (record_base == 0) {
record_base = file_size_;
}
if (end_offset < 0) {
end_offset = INT64MAX;
} else if (end_offset == 0) {
end_offset = file_size_;
}
const int64_t act_file_size = file_->GetSizeSimple();
end_offset = std::min(end_offset, act_file_size);
int64_t null_end_offset = 0;
int64_t act_count = 0;
int64_t act_eff_data_size = 0;
const Status status = ValidateRecordsImpl(
record_base, end_offset, &null_end_offset, &act_count, &act_eff_data_size);
if (status != Status::SUCCESS) {
return status;
}
if (record_base == record_base_ && end_offset == act_file_size) {
if (act_count != num_records_.load()) {
return Status(Status::BROKEN_DATA_ERROR,"inconsistent number of records");
}
if ((static_flags_ & STATIC_FLAG_UPDATE_IN_PLACE) &&
act_eff_data_size != eff_data_size_.load()) {
return Status(Status::BROKEN_DATA_ERROR,"inconsistent effective data size");
}
}
return Status(Status::SUCCESS);
}