-
Notifications
You must be signed in to change notification settings - Fork 411
/
BlobStore.cpp
1529 lines (1317 loc) · 50.8 KB
/
BlobStore.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/Checksum.h>
#include <Common/CurrentMetrics.h>
#include <Common/FailPoint.h>
#include <Common/Logger.h>
#include <Common/ProfileEvents.h>
#include <Common/StringUtils/StringUtils.h>
#include <Common/TiFlashMetrics.h>
#include <Poco/File.h>
#include <Storages/Page/FileUsage.h>
#include <Storages/Page/PageDefines.h>
#include <Storages/Page/V3/BlobStore.h>
#include <Storages/Page/V3/PageDirectory.h>
#include <Storages/Page/V3/PageEntriesEdit.h>
#include <Storages/Page/V3/PageEntry.h>
#include <common/logger_useful.h>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <ext/scope_guard.h>
#include <iterator>
#include <mutex>
namespace ProfileEvents
{
extern const Event PSMWritePages;
extern const Event PSMReadPages;
extern const Event PSV3MBlobExpansion;
extern const Event PSV3MBlobReused;
} // namespace ProfileEvents
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int CHECKSUM_DOESNT_MATCH;
} // namespace ErrorCodes
namespace FailPoints
{
extern const char force_change_all_blobs_to_read_only[];
} // namespace FailPoints
namespace PS::V3
{
static constexpr bool BLOBSTORE_CHECKSUM_ON_READ = true;
using BlobStat = BlobStore::BlobStats::BlobStat;
using BlobStatPtr = BlobStore::BlobStats::BlobStatPtr;
using ChecksumClass = Digest::CRC64;
/**********************
* BlobStore methods *
*********************/
BlobStore::BlobStore(String storage_name, const FileProviderPtr & file_provider_, PSDiskDelegatorPtr delegator_, const BlobStore::Config & config_)
: delegator(std::move(delegator_))
, file_provider(file_provider_)
, config(config_)
, log(Logger::get("BlobStore", std::move(storage_name)))
, blob_stats(log, delegator, config_)
, cached_files(config.cached_fd_size)
{
}
void BlobStore::registerPaths()
{
for (const auto & path : delegator->listPaths())
{
Poco::File store_path(path);
if (!store_path.exists())
{
continue;
}
std::vector<String> file_list;
store_path.list(file_list);
for (const auto & blob_name : file_list)
{
const auto & [blob_id, err_msg] = BlobStats::getBlobIdFromName(blob_name);
auto lock_stats = blob_stats.lock();
if (blob_id != INVALID_BLOBFILE_ID)
{
Poco::File blob(fmt::format("{}/{}", path, blob_name));
auto blob_size = blob.getSize();
delegator->addPageFileUsedSize({blob_id, 0}, blob_size, path, true);
if (blob_size > config.file_limit_size)
{
blob_stats.createBigPageStatNotChecking(blob_id, lock_stats);
}
else
{
blob_stats.createStatNotChecking(blob_id, lock_stats);
}
}
else
{
LOG_FMT_INFO(log, "Ignore not blob file [dir={}] [file={}] [err_msg={}]", path, blob_name, err_msg);
}
}
}
}
FileUsageStatistics BlobStore::getFileUsageStatistics() const
{
FileUsageStatistics usage;
// Get a copy of stats map to avoid the big lock on stats map
const auto stats_list = blob_stats.getStats();
for (const auto & [path, stats] : stats_list)
{
(void)path;
for (const auto & stat : stats)
{
// We can access to these type without any locking.
if (stat->isReadOnly() || stat->isBigBlob())
{
usage.total_disk_size += stat->sm_total_size;
usage.total_valid_size += stat->sm_valid_size;
}
else
{
// Else the stat may being updated, acquire a lock to avoid data race.
auto lock = stat->lock();
usage.total_disk_size += stat->sm_total_size;
usage.total_valid_size += stat->sm_valid_size;
}
}
usage.total_file_num += stats.size();
}
return usage;
}
PageEntriesEdit BlobStore::handleLargeWrite(DB::WriteBatch & wb, const WriteLimiterPtr & write_limiter)
{
auto ns_id = wb.getNamespaceId();
PageEntriesEdit edit;
for (auto & write : wb.getWrites())
{
switch (write.type)
{
case WriteBatch::WriteType::PUT:
{
ChecksumClass digest;
PageEntryV3 entry;
auto [blob_id, offset_in_file] = getPosFromStats(write.size);
entry.file_id = blob_id;
entry.size = write.size;
entry.tag = write.tag;
entry.offset = offset_in_file;
// padding size won't work on big write batch
entry.padded_size = 0;
BufferBase::Buffer data_buf = write.read_buffer->buffer();
digest.update(data_buf.begin(), write.size);
entry.checksum = digest.checksum();
UInt64 field_begin, field_end;
for (size_t i = 0; i < write.offsets.size(); ++i)
{
ChecksumClass field_digest;
field_begin = write.offsets[i].first;
field_end = (i == write.offsets.size() - 1) ? write.size : write.offsets[i + 1].first;
field_digest.update(data_buf.begin() + field_begin, field_end - field_begin);
write.offsets[i].second = field_digest.checksum();
}
if (!write.offsets.empty())
{
// we can swap from WriteBatch instead of copying
entry.field_offsets.swap(write.offsets);
}
try
{
auto blob_file = getBlobFile(blob_id);
blob_file->write(data_buf.begin(), offset_in_file, write.size, write_limiter);
}
catch (DB::Exception & e)
{
removePosFromStats(blob_id, offset_in_file, write.size);
LOG_FMT_ERROR(log, "[blob_id={}] [offset_in_file={}] [size={}] write failed.", blob_id, offset_in_file, write.size);
throw e;
}
edit.put(buildV3Id(ns_id, write.page_id), entry);
break;
}
case WriteBatch::WriteType::DEL:
{
edit.del(buildV3Id(ns_id, write.page_id));
break;
}
case WriteBatch::WriteType::REF:
{
edit.ref(buildV3Id(ns_id, write.page_id), buildV3Id(ns_id, write.ori_page_id));
break;
}
case WriteBatch::WriteType::PUT_EXTERNAL:
edit.putExternal(buildV3Id(ns_id, write.page_id));
break;
case WriteBatch::WriteType::UPSERT:
throw Exception(fmt::format("Unknown write type: {}", write.type));
}
}
return edit;
}
PageEntriesEdit BlobStore::write(DB::WriteBatch & wb, const WriteLimiterPtr & write_limiter)
{
ProfileEvents::increment(ProfileEvents::PSMWritePages, wb.putWriteCount());
const size_t all_page_data_size = wb.getTotalDataSize();
if (all_page_data_size > config.file_limit_size)
{
return handleLargeWrite(wb, write_limiter);
}
PageEntriesEdit edit;
auto ns_id = wb.getNamespaceId();
if (all_page_data_size == 0)
{
// Shortcut for WriteBatch that don't need to persist blob data.
for (auto & write : wb.getWrites())
{
switch (write.type)
{
case WriteBatch::WriteType::DEL:
{
edit.del(buildV3Id(ns_id, write.page_id));
break;
}
case WriteBatch::WriteType::REF:
{
edit.ref(buildV3Id(ns_id, write.page_id), buildV3Id(ns_id, write.ori_page_id));
break;
}
case WriteBatch::WriteType::PUT_EXTERNAL:
{
// putExternal won't have data.
edit.putExternal(buildV3Id(ns_id, write.page_id));
break;
}
case WriteBatch::WriteType::PUT:
case WriteBatch::WriteType::UPSERT:
throw Exception(fmt::format("write batch have a invalid total size [write_type={}]", static_cast<Int32>(write.type)),
ErrorCodes::LOGICAL_ERROR);
}
}
return edit;
}
char * buffer = static_cast<char *>(alloc(all_page_data_size));
SCOPE_EXIT({
free(buffer, all_page_data_size);
});
char * buffer_pos = buffer;
// Calculate alignment space
size_t replenish_size = 0;
if (config.block_alignment_bytes != 0 && all_page_data_size % config.block_alignment_bytes != 0)
{
replenish_size = config.block_alignment_bytes - all_page_data_size % config.block_alignment_bytes;
}
size_t actually_allocated_size = all_page_data_size + replenish_size;
auto [blob_id, offset_in_file] = getPosFromStats(actually_allocated_size);
size_t offset_in_allocated = 0;
for (auto & write : wb.getWrites())
{
switch (write.type)
{
case WriteBatch::WriteType::PUT:
{
ChecksumClass digest;
PageEntryV3 entry;
write.read_buffer->readStrict(buffer_pos, write.size);
entry.file_id = blob_id;
entry.size = write.size;
entry.tag = write.tag;
entry.offset = offset_in_file + offset_in_allocated;
offset_in_allocated += write.size;
// The last put write
if (offset_in_allocated == all_page_data_size)
{
entry.padded_size = replenish_size;
}
digest.update(buffer_pos, write.size);
entry.checksum = digest.checksum();
UInt64 field_begin, field_end;
for (size_t i = 0; i < write.offsets.size(); ++i)
{
ChecksumClass field_digest;
field_begin = write.offsets[i].first;
field_end = (i == write.offsets.size() - 1) ? write.size : write.offsets[i + 1].first;
field_digest.update(buffer_pos + field_begin, field_end - field_begin);
write.offsets[i].second = field_digest.checksum();
}
if (!write.offsets.empty())
{
// we can swap from WriteBatch instead of copying
entry.field_offsets.swap(write.offsets);
}
buffer_pos += write.size;
edit.put(buildV3Id(ns_id, write.page_id), entry);
break;
}
case WriteBatch::WriteType::DEL:
{
edit.del(buildV3Id(ns_id, write.page_id));
break;
}
case WriteBatch::WriteType::REF:
{
edit.ref(buildV3Id(ns_id, write.page_id), buildV3Id(ns_id, write.ori_page_id));
break;
}
case WriteBatch::WriteType::PUT_EXTERNAL:
edit.putExternal(buildV3Id(ns_id, write.page_id));
break;
case WriteBatch::WriteType::UPSERT:
throw Exception(fmt::format("Unknown write type: {}", write.type));
}
}
if (buffer_pos != buffer + all_page_data_size)
{
removePosFromStats(blob_id, offset_in_file, actually_allocated_size);
throw Exception(
fmt::format(
"write batch have a invalid total size, or something wrong in parse write batch "
"[expect_offset={}] [actual_offset={}] [actually_allocated_size={}]",
all_page_data_size,
(buffer_pos - buffer),
actually_allocated_size),
ErrorCodes::LOGICAL_ERROR);
}
try
{
auto blob_file = getBlobFile(blob_id);
blob_file->write(buffer, offset_in_file, all_page_data_size, write_limiter);
}
catch (DB::Exception & e)
{
removePosFromStats(blob_id, offset_in_file, actually_allocated_size);
LOG_FMT_ERROR(log, "[blob_id={}] [offset_in_file={}] [size={}] [actually_allocated_size={}] write failed [error={}]", blob_id, offset_in_file, all_page_data_size, actually_allocated_size, e.message());
throw e;
}
return edit;
}
void BlobStore::remove(const PageEntriesV3 & del_entries)
{
std::set<BlobFileId> blob_updated;
for (const auto & entry : del_entries)
{
blob_updated.insert(entry.file_id);
// External page size is 0
if (entry.size == 0)
{
continue;
}
try
{
removePosFromStats(entry.file_id, entry.offset, entry.getTotalSize());
}
catch (DB::Exception & e)
{
e.addMessage(fmt::format("while removing entry [entry={}]", toDebugString(entry)));
e.rethrow();
}
}
// After we remove postion of blob, we need recalculate the blob.
for (const auto & blob_id : blob_updated)
{
const auto & stat = blob_stats.blobIdToStat(blob_id,
/*ignore_not_exist*/ true);
// Some of blob may been removed.
// So if we can't use id find blob, just ignore it.
if (stat)
{
{
auto lock = stat->lock();
stat->recalculateCapacity();
}
LOG_FMT_TRACE(log, "Blob recalculated capability [blob_id={}] [max_cap={}] "
"[total_size={}] [valid_size={}] [valid_rate={}]",
blob_id,
stat->sm_max_caps,
stat->sm_total_size,
stat->sm_valid_size,
stat->sm_valid_rate);
}
}
}
std::pair<BlobFileId, BlobFileOffset> BlobStore::getPosFromStats(size_t size)
{
BlobStatPtr stat;
auto lock_stat = [size, this, &stat]() {
auto lock_stats = blob_stats.lock();
if (size > config.file_limit_size)
{
auto blob_file_id = blob_stats.chooseBigStat(lock_stats);
stat = blob_stats.createBigStat(blob_file_id, lock_stats);
return stat->lock();
}
else
{
BlobFileId blob_file_id = INVALID_BLOBFILE_ID;
std::tie(stat, blob_file_id) = blob_stats.chooseStat(size, lock_stats);
if (stat == nullptr)
{
// No valid stat for puting data with `size`, create a new one
stat = blob_stats.createStat(blob_file_id, lock_stats);
}
// We must get the lock from BlobStat under the BlobStats lock
// to ensure that BlobStat updates are serialized.
// Otherwise it may cause stat to fail to get the span for writing
// and throwing exception.
return stat->lock();
}
}();
// We need to assume that this insert will reduce max_cap.
// Because other threads may also be waiting for BlobStats to chooseStat during this time.
// If max_cap is not reduced, it may cause the same BlobStat to accept multiple buffers and exceed its max_cap.
// After the BlobStore records the buffer size, max_caps will also get an accurate update.
// So there won't get problem in reducing max_caps here.
stat->sm_max_caps -= size;
// Get Postion from single stat
auto old_max_cap = stat->sm_max_caps;
BlobFileOffset offset = stat->getPosFromStat(size, lock_stat);
// Can't insert into this spacemap
if (offset == INVALID_BLOBFILE_OFFSET)
{
stat->smap->logDebugString();
throw Exception(fmt::format("Get postion from BlobStat failed, it may caused by `sm_max_caps` is no correct. [size={}] [old_max_caps={}] [max_caps={}] [blob_id={}]",
size,
old_max_cap,
stat->sm_max_caps,
stat->id),
ErrorCodes::LOGICAL_ERROR);
}
return std::make_pair(stat->id, offset);
}
void BlobStore::removePosFromStats(BlobFileId blob_id, BlobFileOffset offset, size_t size)
{
bool need_remove_stat = false;
const auto & stat = blob_stats.blobIdToStat(blob_id);
{
auto lock = stat->lock();
need_remove_stat = stat->removePosFromStat(offset, size, lock);
}
// We don't need hold the BlobStat lock(Also can't do that).
// Because once BlobStat become Read-Only type, Then valid size won't increase.
if (need_remove_stat)
{
LOG_FMT_INFO(log, "Removing BlobFile [blob_id={}]", blob_id);
auto lock_stats = blob_stats.lock();
blob_stats.eraseStat(std::move(stat), lock_stats);
getBlobFile(blob_id)->remove();
cached_files.remove(blob_id);
}
}
void BlobStore::read(PageIDAndEntriesV3 & entries, const PageHandler & handler, const ReadLimiterPtr & read_limiter)
{
if (entries.empty())
{
return;
}
ProfileEvents::increment(ProfileEvents::PSMReadPages, entries.size());
// Sort in ascending order by offset in file.
std::sort(entries.begin(), entries.end(), [](const PageIDAndEntryV3 & a, const PageIDAndEntryV3 & b) {
return a.second.offset < b.second.offset;
});
// allocate data_buf that can hold all pages
size_t buf_size = 0;
for (const auto & p : entries)
buf_size = std::max(buf_size, p.second.size);
// When we read `WriteBatch` which is `WriteType::PUT_EXTERNAL`.
// The `buf_size` will be 0, we need avoid calling malloc/free with size 0.
if (buf_size == 0)
{
for (const auto & [page_id_v3, entry] : entries)
{
(void)entry;
LOG_FMT_DEBUG(log, "Read entry [page_id={}] without entry size.", page_id_v3);
Page page;
page.page_id = page_id_v3.low;
handler(page_id_v3.low, page);
}
return;
}
char * data_buf = static_cast<char *>(alloc(buf_size));
MemHolder mem_holder = createMemHolder(data_buf, [&, buf_size](char * p) {
free(p, buf_size);
});
for (const auto & [page_id_v3, entry] : entries)
{
auto blob_file = read(entry.file_id, entry.offset, data_buf, entry.size, read_limiter);
if constexpr (BLOBSTORE_CHECKSUM_ON_READ)
{
ChecksumClass digest;
digest.update(data_buf, entry.size);
auto checksum = digest.checksum();
if (unlikely(entry.size != 0 && checksum != entry.checksum))
{
throw Exception(
fmt::format("Reading with entries meet checksum not match [page_id={}] [expected=0x{:X}] [actual=0x{:X}] [entry={}] [file={}]",
page_id_v3,
entry.checksum,
checksum,
toDebugString(entry),
blob_file->getPath()),
ErrorCodes::CHECKSUM_DOESNT_MATCH);
}
}
Page page;
page.page_id = page_id_v3.low;
page.data = ByteBuffer(data_buf, data_buf + entry.size);
page.mem_holder = mem_holder;
handler(page_id_v3.low, page);
}
}
PageMap BlobStore::read(FieldReadInfos & to_read, const ReadLimiterPtr & read_limiter)
{
if (to_read.empty())
{
return {};
}
ProfileEvents::increment(ProfileEvents::PSMReadPages, to_read.size());
// Sort in ascending order by offset in file.
std::sort(
to_read.begin(),
to_read.end(),
[](const FieldReadInfo & a, const FieldReadInfo & b) { return a.entry.offset < b.entry.offset; });
// allocate data_buf that can hold all pages with specify fields
size_t buf_size = 0;
for (auto & [page_id, entry, fields] : to_read)
{
(void)page_id;
// Sort fields to get better read on disk
std::sort(fields.begin(), fields.end());
for (const auto field_index : fields)
{
buf_size += entry.getFieldSize(field_index);
}
}
// Read with `FieldReadInfos`, buf_size must not be 0.
if (buf_size == 0)
{
throw Exception("Reading with fields but entry size is 0.", ErrorCodes::LOGICAL_ERROR);
}
char * data_buf = static_cast<char *>(alloc(buf_size));
MemHolder mem_holder = createMemHolder(data_buf, [&, buf_size](char * p) {
free(p, buf_size);
});
std::set<Page::FieldOffset> fields_offset_in_page;
char * pos = data_buf;
PageMap page_map;
for (const auto & [page_id_v3, entry, fields] : to_read)
{
size_t read_size_this_entry = 0;
char * write_offset = pos;
for (const auto field_index : fields)
{
// TODO: Continuously fields can read by one system call.
const auto [beg_offset, end_offset] = entry.getFieldOffsets(field_index);
const auto size_to_read = end_offset - beg_offset;
auto blob_file = read(entry.file_id, entry.offset + beg_offset, write_offset, size_to_read, read_limiter);
fields_offset_in_page.emplace(field_index, read_size_this_entry);
if constexpr (BLOBSTORE_CHECKSUM_ON_READ)
{
const auto expect_checksum = entry.field_offsets[field_index].second;
ChecksumClass digest;
digest.update(write_offset, size_to_read);
auto field_checksum = digest.checksum();
if (unlikely(entry.size != 0 && field_checksum != expect_checksum))
{
throw Exception(
fmt::format("Reading with fields meet checksum not match "
"[page_id={}] [expected=0x{:X}] [actual=0x{:X}] "
"[field_index={}] [field_offset={}] [field_size={}] "
"[entry={}] [file={}]",
page_id_v3,
expect_checksum,
field_checksum,
field_index,
beg_offset,
size_to_read,
toDebugString(entry),
blob_file->getPath()),
ErrorCodes::CHECKSUM_DOESNT_MATCH);
}
}
read_size_this_entry += size_to_read;
write_offset += size_to_read;
}
Page page;
page.page_id = page_id_v3.low;
page.data = ByteBuffer(pos, write_offset);
page.mem_holder = mem_holder;
page.field_offsets.swap(fields_offset_in_page);
fields_offset_in_page.clear();
page_map.emplace(page_id_v3.low, std::move(page));
pos = write_offset;
}
if (unlikely(pos != data_buf + buf_size))
throw Exception(fmt::format("[end_position={}] not match the [current_position={}]",
data_buf + buf_size,
pos),
ErrorCodes::LOGICAL_ERROR);
return page_map;
}
PageMap BlobStore::read(PageIDAndEntriesV3 & entries, const ReadLimiterPtr & read_limiter)
{
if (entries.empty())
{
return {};
}
ProfileEvents::increment(ProfileEvents::PSMReadPages, entries.size());
// Sort in ascending order by offset in file.
std::sort(entries.begin(), entries.end(), [](const PageIDAndEntryV3 & a, const PageIDAndEntryV3 & b) {
return a.second.offset < b.second.offset;
});
// allocate data_buf that can hold all pages
size_t buf_size = 0;
for (const auto & p : entries)
{
buf_size += p.second.size;
}
// When we read `WriteBatch` which is `WriteType::PUT_EXTERNAL`.
// The `buf_size` will be 0, we need avoid calling malloc/free with size 0.
if (buf_size == 0)
{
PageMap page_map;
for (const auto & [page_id_v3, entry] : entries)
{
(void)entry;
LOG_FMT_DEBUG(log, "Read entry [page_id={}] without entry size.", page_id_v3);
Page page;
page.page_id = page_id_v3.low;
page_map.emplace(page_id_v3.low, page);
}
return page_map;
}
char * data_buf = static_cast<char *>(alloc(buf_size));
MemHolder mem_holder = createMemHolder(data_buf, [&, buf_size](char * p) {
free(p, buf_size);
});
char * pos = data_buf;
PageMap page_map;
for (const auto & [page_id_v3, entry] : entries)
{
auto blob_file = read(entry.file_id, entry.offset, pos, entry.size, read_limiter);
if constexpr (BLOBSTORE_CHECKSUM_ON_READ)
{
ChecksumClass digest;
digest.update(pos, entry.size);
auto checksum = digest.checksum();
if (unlikely(entry.size != 0 && checksum != entry.checksum))
{
throw Exception(
fmt::format("Reading with entries meet checksum not match [page_id={}] [expected=0x{:X}] [actual=0x{:X}] [entry={}] [file={}]",
page_id_v3,
entry.checksum,
checksum,
toDebugString(entry),
blob_file->getPath()),
ErrorCodes::CHECKSUM_DOESNT_MATCH);
}
}
Page page;
page.page_id = page_id_v3.low;
page.data = ByteBuffer(pos, pos + entry.size);
page.mem_holder = mem_holder;
page_map.emplace(page_id_v3.low, page);
pos += entry.size;
}
if (unlikely(pos != data_buf + buf_size))
throw Exception(fmt::format("[end_position={}] not match the [current_position={}]",
data_buf + buf_size,
pos),
ErrorCodes::LOGICAL_ERROR);
return page_map;
}
Page BlobStore::read(const PageIDAndEntryV3 & id_entry, const ReadLimiterPtr & read_limiter)
{
if (!id_entry.second.isValid())
{
Page page_not_found;
page_not_found.page_id = INVALID_PAGE_ID;
return page_not_found;
}
const auto & [page_id_v3, entry] = id_entry;
const size_t buf_size = entry.size;
// When we read `WriteBatch` which is `WriteType::PUT_EXTERNAL`.
// The `buf_size` will be 0, we need avoid calling malloc/free with size 0.
if (buf_size == 0)
{
LOG_FMT_DEBUG(log, "Read entry [page_id={}] without entry size.", page_id_v3);
Page page;
page.page_id = page_id_v3.low;
return page;
}
char * data_buf = static_cast<char *>(alloc(buf_size));
MemHolder mem_holder = createMemHolder(data_buf, [&, buf_size](char * p) {
free(p, buf_size);
});
auto blob_file = read(entry.file_id, entry.offset, data_buf, buf_size, read_limiter);
if constexpr (BLOBSTORE_CHECKSUM_ON_READ)
{
ChecksumClass digest;
digest.update(data_buf, entry.size);
auto checksum = digest.checksum();
if (unlikely(entry.size != 0 && checksum != entry.checksum))
{
throw Exception(
fmt::format("Reading with entries meet checksum not match [page_id={}] [expected=0x{:X}] [actual=0x{:X}] [entry={}] [file={}]",
page_id_v3,
entry.checksum,
checksum,
toDebugString(entry),
blob_file->getPath()),
ErrorCodes::CHECKSUM_DOESNT_MATCH);
}
}
Page page;
page.page_id = page_id_v3.low;
page.data = ByteBuffer(data_buf, data_buf + buf_size);
page.mem_holder = mem_holder;
return page;
}
BlobFilePtr BlobStore::read(BlobFileId blob_id, BlobFileOffset offset, char * buffers, size_t size, const ReadLimiterPtr & read_limiter, bool background)
{
assert(buffers != nullptr);
auto blob_file = getBlobFile(blob_id);
blob_file->read(buffers, offset, size, read_limiter, background);
return blob_file;
}
struct BlobStoreGCInfo
{
String toString() const
{
return fmt::format("{}. {}. {}. {}. {}.",
toTypeString("Read-Only Blob", 0),
toTypeString("No GC Blob", 1),
toTypeString("Full GC Blob", 2),
toTypeString("Truncated Blob", 3),
toTypeString("Big Blob", 4));
}
void appendToReadOnlyBlob(const BlobFileId blob_id, double valid_rate)
{
blob_gc_info[0].emplace_back(std::make_pair(blob_id, valid_rate));
}
void appendToNoNeedGCBlob(const BlobFileId blob_id, double valid_rate)
{
blob_gc_info[1].emplace_back(std::make_pair(blob_id, valid_rate));
}
void appendToNeedGCBlob(const BlobFileId blob_id, double valid_rate)
{
blob_gc_info[2].emplace_back(std::make_pair(blob_id, valid_rate));
}
void appendToTruncatedBlob(const BlobFileId blob_id, double valid_rate)
{
blob_gc_info[3].emplace_back(std::make_pair(blob_id, valid_rate));
}
void appendToBigBlob(const BlobFileId blob_id, double valid_rate)
{
blob_gc_info[4].emplace_back(std::make_pair(blob_id, valid_rate));
}
private:
// 1. read only blob
// 2. no need gc blob
// 3. full gc blob
// 4. need truncate blob
// 5. big blob
std::vector<std::pair<BlobFileId, double>> blob_gc_info[5];
String toTypeString(const std::string_view prefix, const size_t index) const
{
FmtBuffer fmt_buf;
if (blob_gc_info[index].empty())
{
fmt_buf.fmtAppend("{}: [null]", prefix);
}
else
{
fmt_buf.fmtAppend("{}: [", prefix);
fmt_buf.joinStr(
blob_gc_info[index].begin(),
blob_gc_info[index].end(),
[](const auto arg, FmtBuffer & fb) {
fb.fmtAppend("{}/{:.2f}", arg.first, arg.second);
},
", ");
fmt_buf.append("]");
}
return fmt_buf.toString();
}
};
std::vector<BlobFileId> BlobStore::getGCStats()
{
// Get a copy of stats map to avoid the big lock on stats map
const auto stats_list = blob_stats.getStats();
std::vector<BlobFileId> blob_need_gc;
BlobStoreGCInfo blobstore_gc_info;
fiu_do_on(FailPoints::force_change_all_blobs_to_read_only,
{
for (const auto & [path, stats] : stats_list)
{
(void)path;
for (const auto & stat : stats)
{
stat->changeToReadOnly();
}
}
LOG_FMT_WARNING(log, "enabled force_change_all_blobs_to_read_only. All of BlobStat turn to READ-ONLY");
});
for (const auto & [path, stats] : stats_list)
{
(void)path;
for (const auto & stat : stats)
{
if (stat->isReadOnly())
{
blobstore_gc_info.appendToReadOnlyBlob(stat->id, stat->sm_valid_rate);
LOG_FMT_TRACE(log, "Current [blob_id={}] is read-only", stat->id);
continue;
}
if (stat->isBigBlob())
{
blobstore_gc_info.appendToBigBlob(stat->id, stat->sm_valid_rate);
LOG_FMT_TRACE(log, "Current [blob_id={}] is big-blob", stat->id);
continue;
}
auto lock = stat->lock();
auto right_margin = stat->smap->getRightMargin();
// Avoid divide by zero
if (right_margin == 0)
{
if (unlikely(stat->sm_valid_rate != 0))
{
throw Exception(fmt::format("Current blob is empty, but valid rate is not 0. [blob_id={}][valid_size={}][valid_rate={}]",
stat->id,
stat->sm_valid_size,
stat->sm_valid_rate));
}
LOG_FMT_TRACE(log, "Current blob is empty [blob_id={}, total size(all invalid)={}] [valid_rate={}].", stat->id, stat->sm_total_size, stat->sm_valid_rate);
// If current blob empty, the size of in disk blob may not empty
// So we need truncate current blob, and let it be reused.
auto blobfile = getBlobFile(stat->id);
LOG_FMT_TRACE(log, "Truncate empty blob file [blob_id={}] to 0.", stat->id);
blobfile->truncate(right_margin);
blobstore_gc_info.appendToTruncatedBlob(stat->id, stat->sm_valid_rate);
continue;
}
stat->sm_valid_rate = stat->sm_valid_size * 1.0 / right_margin;
if (stat->sm_valid_rate > 1.0)
{
LOG_FMT_ERROR(
log,
"Current blob got an invalid rate {:.2f}, total size is {}, valid size is {}, right margin is {} [blob_id={}]",
stat->sm_valid_rate,
stat->sm_total_size,
stat->sm_valid_size,
right_margin,
stat->id);
assert(false);
continue;
}
// Check if GC is required
if (stat->sm_valid_rate <= config.heavy_gc_valid_rate)
{
LOG_FMT_TRACE(log, "Current [blob_id={}] valid rate is {:.2f}, Need do compact GC", stat->id, stat->sm_valid_rate);
blob_need_gc.emplace_back(stat->id);
// Change current stat to read only
stat->changeToReadOnly();
blobstore_gc_info.appendToNeedGCBlob(stat->id, stat->sm_valid_rate);
}
else
{
blobstore_gc_info.appendToNoNeedGCBlob(stat->id, stat->sm_valid_rate);
LOG_FMT_TRACE(log, "Current [blob_id={}] valid rate is {:.2f}, No need to GC.", stat->id, stat->sm_valid_rate);
}