-
Notifications
You must be signed in to change notification settings - Fork 411
/
PageDirectory.cpp
1337 lines (1230 loc) · 46.3 KB
/
PageDirectory.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 PingCAP, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// 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 <Common/Exception.h>
#include <Common/FailPoint.h>
#include <Common/Logger.h>
#include <Common/assert_cast.h>
#include <Storages/Page/PageDefines.h>
#include <Storages/Page/V3/MapUtils.h>
#include <Storages/Page/V3/PageDirectory.h>
#include <Storages/Page/V3/PageEntriesEdit.h>
#include <Storages/Page/V3/PageEntry.h>
#include <Storages/Page/V3/WAL/WALReader.h>
#include <Storages/Page/V3/WAL/serialize.h>
#include <Storages/Page/V3/WALStore.h>
#include <Storages/Page/WriteBatch.h>
#include <common/logger_useful.h>
#include <memory>
#include <mutex>
#include <optional>
#include <type_traits>
#include <utility>
#ifdef FIU_ENABLE
#include <Common/randomSeed.h>
#include <pcg_random.hpp>
#include <thread>
#endif
namespace CurrentMetrics
{
extern const Metric PSMVCCSnapshotsList;
} // namespace CurrentMetrics
namespace DB
{
namespace FailPoints
{
extern const char random_slow_page_storage_remove_expired_snapshots[];
} // namespace FailPoints
namespace ErrorCodes
{
extern const int NOT_IMPLEMENTED;
extern const int PS_ENTRY_NOT_EXISTS;
extern const int PS_ENTRY_NO_VALID_VERSION;
} // namespace ErrorCodes
namespace PS::V3
{
/********************************
* VersionedPageEntries methods *
********************************/
void VersionedPageEntries::createNewEntry(const PageVersionType & ver, const PageEntryV3 & entry)
{
auto page_lock = acquireLock();
if (type == EditRecordType::VAR_DELETE)
{
type = EditRecordType::VAR_ENTRY;
entries.emplace(ver, EntryOrDelete::newNormalEntry(entry));
return;
}
if (type == EditRecordType::VAR_ENTRY)
{
auto last_iter = MapUtils::findLess(entries, PageVersionType(ver.sequence + 1, 0));
if (last_iter == entries.end())
{
entries.emplace(ver, EntryOrDelete::newNormalEntry(entry));
}
else if (last_iter->second.isDelete())
{
entries.emplace(ver, EntryOrDelete::newNormalEntry(entry));
}
else
{
assert(last_iter->second.isEntry());
// It is ok to replace the entry with same sequence and newer epoch, but not valid
// to replace the entry with newer sequence.
if (unlikely(last_iter->second.being_ref_count != 1 && last_iter->first.sequence < ver.sequence))
{
throw Exception(fmt::format(
"Try to replace normal entry with an newer seq [ver={}] [prev_ver={}] [last_entry={}]",
ver,
last_iter->first,
last_iter->second.toDebugString()));
}
// create a new version that inherit the `being_ref_count` of the last entry
entries.emplace(ver, EntryOrDelete::newRepalcingEntry(last_iter->second, entry));
}
return;
}
throw Exception(fmt::format(
"try to create entry version with invalid state "
"[ver={}] [entry={}] [state={}]",
ver,
::DB::PS::V3::toDebugString(entry),
toDebugString()));
}
// Create a new external version with version=`ver`.
// If create success, then return a shared_ptr as a holder for page_id. The holder
// will be release when this external version is totally removed.
std::shared_ptr<PageIdV3Internal> VersionedPageEntries::createNewExternal(const PageVersionType & ver)
{
auto page_lock = acquireLock();
if (type == EditRecordType::VAR_DELETE)
{
type = EditRecordType::VAR_EXTERNAL;
is_deleted = false;
create_ver = ver;
delete_ver = PageVersionType(0);
being_ref_count = 1;
// return the new created holder to caller to set the page_id
external_holder = std::make_shared<PageIdV3Internal>(0, 0);
return external_holder;
}
if (type == EditRecordType::VAR_EXTERNAL)
{
if (is_deleted)
{
// adding external after deleted should be ok
if (delete_ver <= ver)
{
is_deleted = false;
create_ver = ver;
delete_ver = PageVersionType(0);
being_ref_count = 1;
// return the new created holder to caller to set the page_id
external_holder = std::make_shared<PageIdV3Internal>(0, 0);
return external_holder;
}
else
{
// apply a external with smaller ver than delete_ver, just ignore
return nullptr;
}
}
else
{
// adding external should be idempotent, just ignore
// don't care about the `ver`
return nullptr;
}
}
throw Exception(fmt::format(
"try to create external version with invalid state "
"[ver={}] [state={}]",
ver,
toDebugString()));
}
// Create a new delete version with version=`ver`.
void VersionedPageEntries::createDelete(const PageVersionType & ver)
{
auto page_lock = acquireLock();
if (type == EditRecordType::VAR_ENTRY)
{
// ignore if the last item is already "delete"
if (entries.empty() || !entries.rbegin()->second.isDelete())
{
entries.emplace(ver, EntryOrDelete::newDelete());
}
return;
}
if (type == EditRecordType::VAR_EXTERNAL || type == EditRecordType::VAR_REF)
{
is_deleted = true;
delete_ver = ver;
return;
}
if (type == EditRecordType::VAR_DELETE)
{
// just ignore
return;
}
throw Exception(fmt::format(
"try to create delete version with invalid state "
"[ver={}] [state={}]",
ver,
toDebugString()));
}
// Create a new reference version with version=`ver` and `ori_page_id_`.
// If create success, then return true, otherwise return false.
bool VersionedPageEntries::createNewRef(const PageVersionType & ver, PageIdV3Internal ori_page_id_)
{
auto page_lock = acquireLock();
if (type == EditRecordType::VAR_DELETE)
{
type = EditRecordType::VAR_REF;
is_deleted = false;
ori_page_id = ori_page_id_;
create_ver = ver;
return true;
}
if (type == EditRecordType::VAR_REF)
{
if (is_deleted)
{
// adding ref after deleted should be ok
if (delete_ver <= ver)
{
ori_page_id = ori_page_id_;
create_ver = ver;
is_deleted = false;
delete_ver = PageVersionType(0);
return true;
}
else if (ori_page_id == ori_page_id_)
{
// apply a ref to same ori id with small ver, just ignore
return false;
}
// else adding ref to another ori id is not allow, just fallover
}
else
{
if (ori_page_id == ori_page_id_)
{
// adding ref to the same ori id should be idempotent, just ignore
return false;
}
// else adding ref to another ori id is not allow, just fallover
}
}
// adding ref to replace put/external is not allowed
throw Exception(fmt::format(
"try to create ref version with invalid state "
"[ver={}] [ori_page_id={}] [state={}]",
ver,
ori_page_id_,
toDebugString()));
}
std::shared_ptr<PageIdV3Internal> VersionedPageEntries::fromRestored(const PageEntriesEdit::EditRecord & rec)
{
auto page_lock = acquireLock();
if (rec.type == EditRecordType::VAR_REF)
{
type = EditRecordType::VAR_REF;
is_deleted = false;
create_ver = rec.version;
ori_page_id = rec.ori_page_id;
return nullptr;
}
else if (rec.type == EditRecordType::VAR_EXTERNAL)
{
type = EditRecordType::VAR_EXTERNAL;
is_deleted = false;
create_ver = rec.version;
being_ref_count = rec.being_ref_count;
external_holder = std::make_shared<PageIdV3Internal>(rec.page_id);
return external_holder;
}
else if (rec.type == EditRecordType::VAR_ENTRY)
{
type = EditRecordType::VAR_ENTRY;
entries.emplace(rec.version, EntryOrDelete::newFromRestored(rec.entry, rec.being_ref_count));
return nullptr;
}
else
{
throw Exception(fmt::format("Calling VersionedPageEntries::fromRestored with unknown type: {}", rec.type));
}
}
std::tuple<VersionedPageEntries::ResolveResult, PageIdV3Internal, PageVersionType>
VersionedPageEntries::resolveToPageId(UInt64 seq, bool check_prev, PageEntryV3 * entry)
{
auto page_lock = acquireLock();
if (type == EditRecordType::VAR_ENTRY)
{
// entries are sorted by <ver, epoch>, find the first one less than <ver+1, 0>
if (auto iter = MapUtils::findLess(entries, PageVersionType(seq + 1));
iter != entries.end())
{
// If we applied write batches like this: [ver=1]{put 10}, [ver=2]{ref 11->10, del 10}
// then by ver=2, we should not able to read 10, but able to read 11 (resolving 11 ref to 10).
// when resolving 11 to 10, we need to set `check_prev` to true
if (iter->second.isDelete() && check_prev && iter->first.sequence == seq)
{
if (iter == entries.begin())
{
return {RESOLVE_FAIL, buildV3Id(0, 0), PageVersionType(0)};
}
--iter;
// fallover the check the prev item
}
if (iter->second.isEntry())
{
if (entry != nullptr)
*entry = iter->second.entry;
return {RESOLVE_TO_NORMAL, buildV3Id(0, 0), PageVersionType(0)};
} // fallover to FAIL
}
}
else if (type == EditRecordType::VAR_EXTERNAL)
{
// We may add reference to an external id even if it is logically deleted.
bool ok = check_prev ? true : (!is_deleted || seq < delete_ver.sequence);
if (create_ver.sequence <= seq && ok)
{
return {RESOLVE_TO_NORMAL, buildV3Id(0, 0), PageVersionType(0)};
}
}
else if (type == EditRecordType::VAR_REF)
{
if (create_ver.sequence <= seq && (!is_deleted || seq < delete_ver.sequence))
{
return {RESOLVE_TO_REF, ori_page_id, create_ver};
}
}
return {RESOLVE_FAIL, buildV3Id(0, 0), PageVersionType(0)};
}
std::optional<PageEntryV3> VersionedPageEntries::getEntry(UInt64 seq) const
{
auto page_lock = acquireLock();
if (type == EditRecordType::VAR_ENTRY)
{
// entries are sorted by <ver, epoch>, find the first one less than <ver+1, 0>
if (auto iter = MapUtils::findLess(entries, PageVersionType(seq + 1));
iter != entries.end())
{
// NORMAL
if (iter->second.isEntry())
return iter->second.entry;
}
}
return std::nullopt;
}
std::optional<PageEntryV3> VersionedPageEntries::getLastEntry() const
{
auto page_lock = acquireLock();
if (type == EditRecordType::VAR_ENTRY)
{
for (auto it_r = entries.rbegin(); it_r != entries.rend(); it_r++)
{
if (it_r->second.isEntry())
{
return it_r->second.entry;
}
}
}
return std::nullopt;
}
Int64 VersionedPageEntries::incrRefCount(const PageVersionType & ver)
{
auto page_lock = acquireLock();
if (type == EditRecordType::VAR_ENTRY)
{
if (auto iter = MapUtils::findMutLess(entries, PageVersionType(ver.sequence + 1));
iter != entries.end())
{
if (iter->second.isEntry())
return ++iter->second.being_ref_count;
else
throw Exception(fmt::format("The entry to be added ref count is not normal entry [entry={}] [ver={}]", iter->second.toDebugString(), ver));
}
}
else if (type == EditRecordType::VAR_EXTERNAL)
{
if (create_ver <= ver)
{
// We may add reference to an external id even if it is logically deleted.
return ++being_ref_count;
}
}
throw Exception(fmt::format("The entry to be added ref count is not found [ver={}]", ver));
}
PageSize VersionedPageEntries::getEntriesByBlobIds(
const std::unordered_set<BlobFileId> & blob_ids,
PageIdV3Internal page_id,
std::map<BlobFileId, PageIdAndVersionedEntries> & blob_versioned_entries)
{
// blob_file_0, [<page_id_0, ver0, entry0>,
// <page_id_0, ver1, entry1>,
// <page_id_1, ver1, entry1> ]
// blob_file_1, [...]
// ...
// the total entries size taken out
PageSize total_entries_size = 0;
auto page_lock = acquireLock();
if (type == EditRecordType::VAR_ENTRY)
{
for (const auto & [versioned_type, entry_or_del] : entries)
{
if (!entry_or_del.isEntry())
{
continue;
}
const auto & entry = entry_or_del.entry;
if (blob_ids.count(entry.file_id) > 0)
{
blob_versioned_entries[entry.file_id].emplace_back(page_id, versioned_type, entry);
total_entries_size += entry.size;
}
}
}
return total_entries_size;
}
bool VersionedPageEntries::cleanOutdatedEntries(
UInt64 lowest_seq,
std::map<PageIdV3Internal, std::pair<PageVersionType, Int64>> * normal_entries_to_deref,
PageEntriesV3 & entries_removed,
const PageLock & /*page_lock*/)
{
if (type == EditRecordType::VAR_EXTERNAL)
{
return (being_ref_count == 1 && is_deleted && delete_ver.sequence <= lowest_seq);
}
else if (type == EditRecordType::VAR_REF)
{
if (!is_deleted || lowest_seq < delete_ver.sequence)
return false;
if (normal_entries_to_deref != nullptr)
{
// need to decrease the ref count by <id=iter->second.origin_page_id, ver=iter->first, num=1>
if (auto [deref_counter, new_created] = normal_entries_to_deref->emplace(std::make_pair(ori_page_id, std::make_pair(/*ver=*/create_ver, /*count=*/1))); !new_created)
{
// the id is already exist in deref map, increase the num to decrease ref count
deref_counter->second.second += 1;
}
}
return true;
}
else if (type == EditRecordType::VAR_DELETE)
{
return true;
}
else if (type != EditRecordType::VAR_ENTRY)
{
throw Exception("Invalid state");
}
// type == EditRecordType::VAR_ENTRY
if (entries.empty())
{
return true;
}
auto iter = MapUtils::findLess(entries, PageVersionType(lowest_seq + 1));
// If we can't find any seq lower than `lowest_seq` then
// all version in this list don't need gc.
if (iter == entries.begin() || iter == entries.end())
{
return false;
}
// If the first version less than <lowest_seq+1, 0> is entry / external,
// then we can remove those entries prev of it
bool keep_if_being_ref = !iter->second.isEntry();
--iter; // keep the first version less than <lowest_seq+1, 0>
while (true)
{
if (iter->second.isDelete())
{
// Already deleted
iter = entries.erase(iter);
}
else if (iter->second.isEntry())
{
if (keep_if_being_ref)
{
if (iter->second.being_ref_count == 1)
{
entries_removed.emplace_back(iter->second.entry);
iter = entries.erase(iter);
}
// The `being_ref_count` for this version is valid. While for older versions,
// theirs `being_ref_count` is invalid, don't need to be kept
keep_if_being_ref = false;
}
else
{
// else there are newer "entry" in the version list, the outdated entries should be removed
entries_removed.emplace_back(iter->second.entry);
iter = entries.erase(iter);
}
}
if (iter == entries.begin())
break;
--iter;
}
return entries.empty() || (entries.size() == 1 && entries.begin()->second.isDelete());
}
bool VersionedPageEntries::derefAndClean(UInt64 lowest_seq, PageIdV3Internal page_id, const PageVersionType & deref_ver, const Int64 deref_count, PageEntriesV3 & entries_removed)
{
auto page_lock = acquireLock();
if (type == EditRecordType::VAR_EXTERNAL)
{
if (being_ref_count <= deref_count)
{
throw Exception(fmt::format("Decreasing ref count error [page_id={}] [ver={}] [deref_count={}]", page_id, deref_ver, deref_count));
}
being_ref_count -= deref_count;
return (is_deleted && delete_ver.sequence <= lowest_seq && being_ref_count == 1);
}
else if (type == EditRecordType::VAR_ENTRY)
{
// Decrease the ref-counter. The entry may be moved to a newer entry with same sequence but higher epoch,
// so we need to find the one less than <seq+1, 0> and decrease the ref-counter of it.
auto iter = MapUtils::findMutLess(entries, PageVersionType(deref_ver.sequence + 1, 0));
if (iter == entries.end())
{
throw Exception(fmt::format("Can not find entry for decreasing ref count [page_id={}] [ver={}] [deref_count={}]", page_id, deref_ver, deref_count));
}
if (iter->second.isDelete())
{
if (iter == entries.begin())
{
throw Exception(fmt::format("Can not find entry for decreasing ref count [page_id={}] [ver={}] [deref_count={}]", page_id, deref_ver, deref_count));
}
--iter; // move to the previous entry
}
if (iter->second.being_ref_count <= deref_count)
{
throw Exception(fmt::format("Decreasing ref count error [page_id={}] [ver={}] [deref_count={}] [entry={}]", page_id, deref_ver, deref_count, iter->second.toDebugString()));
}
iter->second.being_ref_count -= deref_count;
// Clean outdated entries after decreased the ref-counter
// set `normal_entries_to_deref` to be nullptr to ignore cleaning ref-var-entries
return cleanOutdatedEntries(lowest_seq, /*normal_entries_to_deref*/ nullptr, entries_removed, page_lock);
}
throw Exception(fmt::format("calling derefAndClean with invalid state [state={}]", toDebugString()));
}
void VersionedPageEntries::collapseTo(const UInt64 seq, const PageIdV3Internal page_id, PageEntriesEdit & edit)
{
auto page_lock = acquireLock();
if (type == EditRecordType::VAR_REF)
{
if (create_ver.sequence > seq)
return;
// We need to keep the VAR_REF once create_ver > seq,
// or the being-ref entry/external won't be able to be clean
// after restore.
edit.varRef(page_id, create_ver, ori_page_id);
if (is_deleted && delete_ver.sequence <= seq)
{
edit.varDel(page_id, delete_ver);
}
return;
}
if (type == EditRecordType::VAR_EXTERNAL)
{
if (create_ver.sequence > seq)
return;
edit.varExternal(page_id, create_ver, being_ref_count);
if (is_deleted && delete_ver.sequence <= seq)
{
edit.varDel(page_id, delete_ver);
}
return;
}
if (type == EditRecordType::VAR_ENTRY)
{
// dump the latest entry if it is not a "delete"
auto last_iter = MapUtils::findLess(entries, PageVersionType(seq + 1));
if (last_iter == entries.end())
return;
if (last_iter->second.isEntry())
{
const auto & entry = last_iter->second;
edit.varEntry(page_id, /*ver*/ last_iter->first, entry.entry, entry.being_ref_count);
return;
}
else if (last_iter->second.isDelete())
{
if (last_iter == entries.begin())
{
// only delete left, then we don't need to keep this
return;
}
auto last_version = last_iter->first;
auto prev_iter = --last_iter; // Note that `last_iter` should not be used anymore
if (prev_iter->second.isEntry())
{
if (prev_iter->second.being_ref_count == 1)
return;
// It is being ref by another id, should persist the item and delete
const auto & entry = prev_iter->second;
edit.varEntry(page_id, prev_iter->first, entry.entry, entry.being_ref_count);
edit.varDel(page_id, last_version);
}
}
return;
}
if (type == EditRecordType::VAR_DELETE)
{
// just ignore
return;
}
throw Exception(fmt::format("Calling collapseTo with invalid state [state={}]", toDebugString()));
}
/**************************
* PageDirectory methods *
*************************/
PageDirectory::PageDirectory(String storage_name, WALStorePtr && wal_, UInt64 max_persisted_log_files_)
: sequence(0)
, wal(std::move(wal_))
, max_persisted_log_files(max_persisted_log_files_)
, log(Logger::get("PageDirectory", std::move(storage_name)))
{
}
PageDirectorySnapshotPtr PageDirectory::createSnapshot(const String & tracing_id) const
{
auto snap = std::make_shared<PageDirectorySnapshot>(sequence.load(), tracing_id);
{
std::lock_guard snapshots_lock(snapshots_mutex);
snapshots.emplace_back(std::weak_ptr<PageDirectorySnapshot>(snap));
}
CurrentMetrics::add(CurrentMetrics::PSMVCCSnapshotsList);
return snap;
}
SnapshotsStatistics PageDirectory::getSnapshotsStat() const
{
SnapshotsStatistics stat;
DB::Int64 num_snapshots_removed = 0;
{
std::lock_guard lock(snapshots_mutex);
for (auto iter = snapshots.begin(); iter != snapshots.end(); /* empty */)
{
auto snapshot_ptr = iter->lock();
if (!snapshot_ptr)
{
iter = snapshots.erase(iter);
num_snapshots_removed++;
}
else
{
fiu_do_on(FailPoints::random_slow_page_storage_remove_expired_snapshots, {
pcg64 rng(randomSeed());
std::chrono::milliseconds ms{std::uniform_int_distribution(0, 900)(rng)}; // 0~900 milliseconds
std::this_thread::sleep_for(ms);
});
const auto snapshot_lifetime = snapshot_ptr->elapsedSeconds();
if (snapshot_lifetime > stat.longest_living_seconds)
{
stat.longest_living_seconds = snapshot_lifetime;
stat.longest_living_from_thread_id = snapshot_ptr->create_thread;
stat.longest_living_from_tracing_id = snapshot_ptr->tracing_id;
}
stat.num_snapshots++;
++iter;
}
}
}
CurrentMetrics::sub(CurrentMetrics::PSMVCCSnapshotsList, num_snapshots_removed);
// Return some statistics of the oldest living snapshot.
return stat;
}
PageIDAndEntryV3 PageDirectory::get(PageIdV3Internal page_id, const PageDirectorySnapshotPtr & snap, bool throw_on_not_exist) const
{
PageEntryV3 entry_got;
PageIdV3Internal id_to_resolve = page_id;
PageVersionType ver_to_resolve(snap->sequence, 0);
bool ok = true;
while (ok)
{
MVCCMapType::const_iterator iter;
{
std::shared_lock read_lock(table_rw_mutex);
iter = mvcc_table_directory.find(id_to_resolve);
if (iter == mvcc_table_directory.end())
{
if (throw_on_not_exist)
{
throw Exception(fmt::format("Invalid page id, entry not exist [page_id={}] [resolve_id={}]", page_id, id_to_resolve), ErrorCodes::PS_ENTRY_NOT_EXISTS);
}
else
{
return PageIDAndEntryV3{page_id, PageEntryV3{.file_id = INVALID_BLOBFILE_ID}};
}
}
}
auto [need_collapse, next_id_to_resolve, next_ver_to_resolve] = iter->second->resolveToPageId(ver_to_resolve.sequence, id_to_resolve != page_id, &entry_got);
switch (need_collapse)
{
case VersionedPageEntries::RESOLVE_TO_NORMAL:
return PageIDAndEntryV3(page_id, entry_got);
case VersionedPageEntries::RESOLVE_FAIL:
ok = false;
break;
case VersionedPageEntries::RESOLVE_TO_REF:
if (id_to_resolve == next_id_to_resolve)
{
ok = false;
break;
}
id_to_resolve = next_id_to_resolve;
ver_to_resolve = next_ver_to_resolve;
break; // continue the resolving
}
}
throw Exception(fmt::format("Fail to get entry [page_id={}] [seq={}] [resolve_id={}] [resolve_ver={}]", page_id, snap->sequence, id_to_resolve, ver_to_resolve), ErrorCodes::PS_ENTRY_NO_VALID_VERSION);
}
std::pair<PageIDAndEntriesV3, PageIds> PageDirectory::get(const PageIdV3Internals & page_ids, const PageDirectorySnapshotPtr & snap, bool throw_on_not_exist) const
{
PageEntryV3 entry_got;
PageIds page_not_found = {};
const PageVersionType init_ver_to_resolve(snap->sequence, 0);
auto get_one = [&entry_got, init_ver_to_resolve, throw_on_not_exist, this](PageIdV3Internal page_id, PageVersionType ver_to_resolve, size_t idx) {
PageIdV3Internal id_to_resolve = page_id;
bool ok = true;
while (ok)
{
MVCCMapType::const_iterator iter;
{
std::shared_lock read_lock(table_rw_mutex);
iter = mvcc_table_directory.find(id_to_resolve);
if (iter == mvcc_table_directory.end())
{
if (throw_on_not_exist)
{
throw Exception(fmt::format("Invalid page id, entry not exist [page_id={}] [resolve_id={}]", page_id, id_to_resolve), ErrorCodes::PS_ENTRY_NOT_EXISTS);
}
else
{
return false;
}
}
}
auto [need_collapse, next_id_to_resolve, next_ver_to_resolve] = iter->second->resolveToPageId(ver_to_resolve.sequence, id_to_resolve != page_id, &entry_got);
switch (need_collapse)
{
case VersionedPageEntries::RESOLVE_TO_NORMAL:
return true;
case VersionedPageEntries::RESOLVE_FAIL:
ok = false;
break;
case VersionedPageEntries::RESOLVE_TO_REF:
if (id_to_resolve == next_id_to_resolve)
{
ok = false;
break;
}
id_to_resolve = next_id_to_resolve;
ver_to_resolve = next_ver_to_resolve;
break; // continue the resolving
}
}
throw Exception(fmt::format("Fail to get entry [page_id={}] [ver={}] [resolve_id={}] [resolve_ver={}] [idx={}]", page_id, init_ver_to_resolve, id_to_resolve, ver_to_resolve, idx), ErrorCodes::PS_ENTRY_NO_VALID_VERSION);
};
PageIDAndEntriesV3 id_entries;
for (size_t idx = 0; idx < page_ids.size(); ++idx)
{
if (auto ok = get_one(page_ids[idx], init_ver_to_resolve, idx); ok)
{
id_entries.emplace_back(page_ids[idx], entry_got);
}
else
{
page_not_found.emplace_back(page_ids[idx]);
}
}
return std::make_pair(id_entries, page_not_found);
}
PageIdV3Internal PageDirectory::getNormalPageId(PageIdV3Internal page_id, const PageDirectorySnapshotPtr & snap, bool throw_on_not_exist) const
{
PageIdV3Internal id_to_resolve = page_id;
PageVersionType ver_to_resolve(snap->sequence, 0);
bool keep_resolve = true;
while (keep_resolve)
{
MVCCMapType::const_iterator iter;
{
std::shared_lock read_lock(table_rw_mutex);
iter = mvcc_table_directory.find(id_to_resolve);
if (iter == mvcc_table_directory.end())
{
if (throw_on_not_exist)
{
throw Exception(fmt::format("Invalid page id [page_id={}] [resolve_id={}]", page_id, id_to_resolve));
}
else
{
return PageIdV3Internal(0, INVALID_PAGE_ID);
}
}
}
auto [need_collapse, next_id_to_resolve, next_ver_to_resolve] = iter->second->resolveToPageId(ver_to_resolve.sequence, id_to_resolve != page_id, nullptr);
switch (need_collapse)
{
case VersionedPageEntries::RESOLVE_TO_NORMAL:
return id_to_resolve;
case VersionedPageEntries::RESOLVE_FAIL:
// resolve failed
keep_resolve = false;
break;
case VersionedPageEntries::RESOLVE_TO_REF:
if (id_to_resolve == next_id_to_resolve)
{
// dead-loop, so break the `while(keep_resolve)`
keep_resolve = false;
break;
}
id_to_resolve = next_id_to_resolve;
ver_to_resolve = next_ver_to_resolve;
break; // continue the resolving
}
}
if (throw_on_not_exist)
{
throw Exception(fmt::format(
"fail to get normal id [page_id={}] [seq={}] [resolve_id={}] [resolve_ver={}]",
page_id,
snap->sequence,
id_to_resolve,
ver_to_resolve));
}
else
{
return PageIdV3Internal(0, INVALID_PAGE_ID);
}
}
PageId PageDirectory::getMaxId(NamespaceId ns_id) const
{
std::shared_lock read_lock(table_rw_mutex);
PageIdV3Internal upper_bound = buildV3Id(ns_id, UINT64_MAX);
auto iter = mvcc_table_directory.upper_bound(upper_bound);
if (iter == mvcc_table_directory.begin())
{
// The smallest page id is greater than the target page id or mvcc_table_directory is empty,
// and it means no page id is less than or equal to the target page id, return 0.
return 0;
}
else
{
// iter is not at the beginning and mvcc_table_directory is not empty,
// so iter-- must be a valid iterator, and it's the largest page id which is smaller than the target page id.
iter--;
if (iter->first.high == ns_id)
return iter->first.low;
else
return 0;
}
}
std::set<PageIdV3Internal> PageDirectory::getAllPageIds()
{
std::set<PageIdV3Internal> page_ids;
std::shared_lock read_lock(table_rw_mutex);
for (auto & [page_id, versioned] : mvcc_table_directory)
{
(void)versioned;
page_ids.insert(page_id);
}
return page_ids;
}
void PageDirectory::applyRefEditRecord(
MVCCMapType & mvcc_table_directory,
const VersionedPageEntriesPtr & version_list,
const PageEntriesEdit::EditRecord & rec,
const PageVersionType & version)
{
// applying ref 3->2, existing ref 2->1, normal entry 1, then we should collapse
// the ref to be 3->1, increase the refcounting of normale entry 1
auto [resolve_success, resolved_id, resolved_ver] = [&mvcc_table_directory](PageIdV3Internal id_to_resolve, PageVersionType ver_to_resolve)
-> std::tuple<bool, PageIdV3Internal, PageVersionType> {
while (true)
{
auto resolve_ver_iter = mvcc_table_directory.find(id_to_resolve);
if (resolve_ver_iter == mvcc_table_directory.end())
return {false, buildV3Id(0, 0), PageVersionType(0)};
const VersionedPageEntriesPtr & resolve_version_list = resolve_ver_iter->second;
// If we already hold the lock from `id_to_resolve`, then we should not request it again.
// This can happen when `id_to_resolve` have other operating in current writebatch
auto [need_collapse, next_id_to_resolve, next_ver_to_resolve] = resolve_version_list->resolveToPageId(
ver_to_resolve.sequence,
/*check_prev=*/true,
nullptr);
switch (need_collapse)
{
case VersionedPageEntries::RESOLVE_FAIL:
return {false, id_to_resolve, ver_to_resolve};
case VersionedPageEntries::RESOLVE_TO_NORMAL:
return {true, id_to_resolve, ver_to_resolve};
case VersionedPageEntries::RESOLVE_TO_REF:
if (id_to_resolve == next_id_to_resolve)
{
return {false, next_id_to_resolve, next_ver_to_resolve};
}
id_to_resolve = next_id_to_resolve;
ver_to_resolve = next_ver_to_resolve;
break; // continue the resolving
}
}
}(rec.ori_page_id, version);
if (!resolve_success)
{
throw Exception(fmt::format(
"Trying to add ref to non-exist page [page_id={}] [ori_id={}] [ver={}] [resolve_id={}] [resolve_ver={}]",
rec.page_id,
rec.ori_page_id,
version,
resolved_id,
resolved_ver));
}
// use the resolved_id to collapse ref chain 3->2, 2->1 ==> 3->1
bool is_ref_created = version_list->createNewRef(version, resolved_id);
if (is_ref_created)
{
// Add the ref-count of being-ref entry
if (auto resolved_iter = mvcc_table_directory.find(resolved_id); resolved_iter != mvcc_table_directory.end())
{
resolved_iter->second->incrRefCount(resolved_ver);
}
else
{
throw Exception(fmt::format(
"The ori page id is not found [page_id={}] [ori_id={}] [ver={}] [resolved_id={}] [resolved_ver={}]",
rec.page_id,
rec.ori_page_id,
version,
resolved_id,
resolved_ver));
}
}
}
void PageDirectory::apply(PageEntriesEdit && edit, const WriteLimiterPtr & write_limiter)
{
// Note that we need to make sure increasing `sequence` in order, so it
// also needs to be protected by `write_lock` throughout the `apply`
// TODO: It is totally serialized, make it a pipeline
std::unique_lock write_lock(table_rw_mutex);
UInt64 last_sequence = sequence.load();
PageVersionType new_version(last_sequence + 1, 0);
// stage 1, persisted the changes to WAL with version [seq=last_seq + 1, epoch=0]
wal->apply(edit, new_version, write_limiter);
// stage 2, create entry version list for page_id.
for (const auto & r : edit.getRecords())
{
auto [iter, created] = mvcc_table_directory.insert(std::make_pair(r.page_id, nullptr));