block_based_table_reader.cc 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. #include "table/block_based/block_based_table_reader.h"
  10. #include <algorithm>
  11. #include <array>
  12. #include <atomic>
  13. #include <cstdint>
  14. #include <limits>
  15. #include <memory>
  16. #include <string>
  17. #include <unordered_set>
  18. #include <utility>
  19. #include <vector>
  20. #include "block_cache.h"
  21. #include "cache/cache_entry_roles.h"
  22. #include "cache/cache_key.h"
  23. #include "db/compaction/compaction_picker.h"
  24. #include "db/dbformat.h"
  25. #include "db/pinned_iterators_manager.h"
  26. #include "file/file_prefetch_buffer.h"
  27. #include "file/file_util.h"
  28. #include "file/random_access_file_reader.h"
  29. #include "logging/logging.h"
  30. #include "monitoring/perf_context_imp.h"
  31. #include "parsed_full_filter_block.h"
  32. #include "port/lang.h"
  33. #include "rocksdb/cache.h"
  34. #include "rocksdb/comparator.h"
  35. #include "rocksdb/convenience.h"
  36. #include "rocksdb/env.h"
  37. #include "rocksdb/file_system.h"
  38. #include "rocksdb/filter_policy.h"
  39. #include "rocksdb/iterator.h"
  40. #include "rocksdb/options.h"
  41. #include "rocksdb/snapshot.h"
  42. #include "rocksdb/statistics.h"
  43. #include "rocksdb/system_clock.h"
  44. #include "rocksdb/table.h"
  45. #include "rocksdb/table_properties.h"
  46. #include "rocksdb/trace_record.h"
  47. #include "rocksdb/user_defined_index.h"
  48. #include "table/block_based/binary_search_index_reader.h"
  49. #include "table/block_based/block.h"
  50. #include "table/block_based/block_based_table_factory.h"
  51. #include "table/block_based/block_based_table_iterator.h"
  52. #include "table/block_based/block_prefix_index.h"
  53. #include "table/block_based/block_type.h"
  54. #include "table/block_based/filter_block.h"
  55. #include "table/block_based/filter_policy_internal.h"
  56. #include "table/block_based/full_filter_block.h"
  57. #include "table/block_based/hash_index_reader.h"
  58. #include "table/block_based/partitioned_filter_block.h"
  59. #include "table/block_based/partitioned_index_reader.h"
  60. #include "table/block_based/user_defined_index_wrapper.h"
  61. #include "table/block_fetcher.h"
  62. #include "table/format.h"
  63. #include "table/get_context.h"
  64. #include "table/internal_iterator.h"
  65. #include "table/meta_blocks.h"
  66. #include "table/multiget_context.h"
  67. #include "table/persistent_cache_helper.h"
  68. #include "table/persistent_cache_options.h"
  69. #include "table/sst_file_writer_collectors.h"
  70. #include "table/two_level_iterator.h"
  71. #include "test_util/sync_point.h"
  72. #include "util/coding.h"
  73. #include "util/crc32c.h"
  74. #include "util/stop_watch.h"
  75. #include "util/string_util.h"
  76. namespace ROCKSDB_NAMESPACE {
  77. namespace {
  78. CacheAllocationPtr CopyBufferToHeap(MemoryAllocator* allocator, Slice& buf) {
  79. CacheAllocationPtr heap_buf;
  80. heap_buf = AllocateBlock(buf.size(), allocator);
  81. memcpy(heap_buf.get(), buf.data(), buf.size());
  82. return heap_buf;
  83. }
  84. } // namespace
  85. // Explicitly instantiate templates for each "blocklike" type we use (and
  86. // before implicit specialization).
  87. // This makes it possible to keep the template definitions in the .cc file.
  88. #define INSTANTIATE_BLOCKLIKE_TEMPLATES(T) \
  89. template Status BlockBasedTable::RetrieveBlock<T>( \
  90. FilePrefetchBuffer * prefetch_buffer, const ReadOptions& ro, \
  91. const BlockHandle& handle, UnownedPtr<Decompressor> decomp, \
  92. CachableEntry<T>* out_parsed_block, GetContext* get_context, \
  93. BlockCacheLookupContext* lookup_context, bool for_compaction, \
  94. bool use_cache, bool async_read, bool use_block_cache_for_lookup) const; \
  95. template Status BlockBasedTable::MaybeReadBlockAndLoadToCache<T>( \
  96. FilePrefetchBuffer * prefetch_buffer, const ReadOptions& ro, \
  97. const BlockHandle& handle, UnownedPtr<Decompressor> decomp, \
  98. bool for_compaction, CachableEntry<T>* block_entry, \
  99. GetContext* get_context, BlockCacheLookupContext* lookup_context, \
  100. BlockContents* contents, bool async_read, \
  101. bool use_block_cache_for_lookup) const; \
  102. template Status BlockBasedTable::LookupAndPinBlocksInCache<T>( \
  103. const ReadOptions& ro, const BlockHandle& handle, \
  104. CachableEntry<T>* out_parsed_block) const; \
  105. template Status BlockBasedTable::CreateAndPinBlockInCache<T>( \
  106. const ReadOptions& ro, const BlockHandle& handle, \
  107. UnownedPtr<Decompressor> decomp, BlockContents* block_contents, \
  108. CachableEntry<T>* out_parsed_block) const;
  109. INSTANTIATE_BLOCKLIKE_TEMPLATES(ParsedFullFilterBlock);
  110. INSTANTIATE_BLOCKLIKE_TEMPLATES(DecompressorDict);
  111. INSTANTIATE_BLOCKLIKE_TEMPLATES(Block_kData);
  112. INSTANTIATE_BLOCKLIKE_TEMPLATES(Block_kIndex);
  113. INSTANTIATE_BLOCKLIKE_TEMPLATES(Block_kFilterPartitionIndex);
  114. INSTANTIATE_BLOCKLIKE_TEMPLATES(Block_kRangeDeletion);
  115. INSTANTIATE_BLOCKLIKE_TEMPLATES(Block_kMetaIndex);
  116. INSTANTIATE_BLOCKLIKE_TEMPLATES(Block_kUserDefinedIndex);
  117. } // namespace ROCKSDB_NAMESPACE
  118. // Generate the regular and coroutine versions of some methods by
  119. // including block_based_table_reader_sync_and_async.h twice
  120. // Macros in the header will expand differently based on whether
  121. // WITH_COROUTINES or WITHOUT_COROUTINES is defined
  122. // clang-format off
  123. #define WITHOUT_COROUTINES
  124. #include "table/block_based/block_based_table_reader_sync_and_async.h"
  125. #undef WITHOUT_COROUTINES
  126. #define WITH_COROUTINES
  127. #include "table/block_based/block_based_table_reader_sync_and_async.h"
  128. #undef WITH_COROUTINES
  129. // clang-format on
  130. namespace ROCKSDB_NAMESPACE {
  131. extern const uint64_t kBlockBasedTableMagicNumber;
  132. extern const std::string kHashIndexPrefixesBlock;
  133. extern const std::string kHashIndexPrefixesMetadataBlock;
  134. BlockBasedTable::~BlockBasedTable() {
  135. auto ua = rep_->uncache_aggressiveness.LoadRelaxed();
  136. // NOTE: there is an undiagnosed incompatibility with mmap reads,
  137. // where attempting to read the index below can result in bus error.
  138. // In theory the mmap should remain in place until destruction of
  139. // rep_, so even a page fault should be satisfiable. But also, combining
  140. // mmap reads with block cache is weird, so it's not a concerning loss.
  141. if (ua > 0 && rep_->table_options.block_cache &&
  142. !rep_->ioptions.allow_mmap_reads) {
  143. if (rep_->filter) {
  144. rep_->filter->EraseFromCacheBeforeDestruction(ua);
  145. }
  146. if (rep_->index_reader) {
  147. {
  148. // TODO: Also uncache data blocks known after any gaps in partitioned
  149. // index. Right now the iterator errors out as soon as there's an
  150. // index partition not in cache.
  151. IndexBlockIter iiter_on_stack;
  152. ReadOptions ropts;
  153. ropts.read_tier = kBlockCacheTier; // No I/O
  154. auto iiter = NewIndexIterator(
  155. ropts, /*disable_prefix_seek=*/false, &iiter_on_stack,
  156. /*get_context=*/nullptr, /*lookup_context=*/nullptr);
  157. std::unique_ptr<InternalIteratorBase<IndexValue>> iiter_unique_ptr;
  158. if (iiter != &iiter_on_stack) {
  159. iiter_unique_ptr.reset(iiter);
  160. }
  161. // Un-cache the data blocks the index iterator with tell us about
  162. // without I/O. (NOTE: It's extremely unlikely that a data block
  163. // will be in block cache without the index block pointing to it
  164. // also in block cache.)
  165. UncacheAggressivenessAdvisor advisor(ua);
  166. for (iiter->SeekToFirst(); iiter->Valid() && advisor.ShouldContinue();
  167. iiter->Next()) {
  168. bool erased = EraseFromCache(iiter->value().handle);
  169. advisor.Report(erased);
  170. }
  171. iiter->status().PermitUncheckedError();
  172. }
  173. // Un-cache the index block(s)
  174. rep_->index_reader->EraseFromCacheBeforeDestruction(ua);
  175. }
  176. }
  177. delete rep_;
  178. }
  179. namespace {
  180. // Read the block identified by "handle" from "file".
  181. // The only relevant option is options.verify_checksums for now.
  182. // On failure return non-OK.
  183. // On success fill *result and return OK - caller owns *result
  184. // @param uncompression_dict Data for presetting the compression library's
  185. // dictionary.
  186. template <typename TBlocklike>
  187. Status ReadAndParseBlockFromFile(
  188. RandomAccessFileReader* file, FilePrefetchBuffer* prefetch_buffer,
  189. const Footer& footer, const ReadOptions& options, const BlockHandle& handle,
  190. std::unique_ptr<TBlocklike>* result, const ImmutableOptions& ioptions,
  191. BlockCreateContext& create_context, bool maybe_compressed,
  192. UnownedPtr<Decompressor> decomp,
  193. const PersistentCacheOptions& cache_options,
  194. MemoryAllocator* memory_allocator, bool for_compaction, bool async_read) {
  195. assert(result);
  196. BlockContents contents;
  197. BlockFetcher block_fetcher(
  198. file, prefetch_buffer, footer, options, handle, &contents, ioptions,
  199. /*do_uncompress*/ maybe_compressed, maybe_compressed,
  200. TBlocklike::kBlockType, decomp, cache_options, memory_allocator, nullptr,
  201. for_compaction);
  202. Status s;
  203. // If prefetch_buffer is not allocated, it will fallback to synchronous
  204. // reading of block contents.
  205. if (async_read && prefetch_buffer != nullptr) {
  206. s = block_fetcher.ReadAsyncBlockContents();
  207. if (!s.ok()) {
  208. return s;
  209. }
  210. } else {
  211. s = block_fetcher.ReadBlockContents();
  212. }
  213. if (s.ok()) {
  214. create_context.Create(result, std::move(contents));
  215. }
  216. return s;
  217. }
  218. // For hash based index, return false if table_properties->prefix_extractor_name
  219. // and prefix_extractor both exist and match, otherwise true.
  220. inline bool PrefixExtractorChangedHelper(
  221. const TableProperties* table_properties,
  222. const SliceTransform* prefix_extractor) {
  223. // BlockBasedTableOptions::kHashSearch requires prefix_extractor to be set.
  224. // Turn off hash index in prefix_extractor is not set; if prefix_extractor
  225. // is set but prefix_extractor_block is not set, also disable hash index
  226. if (prefix_extractor == nullptr || table_properties == nullptr ||
  227. table_properties->prefix_extractor_name.empty()) {
  228. return true;
  229. }
  230. // prefix_extractor and prefix_extractor_block are both non-empty
  231. if (table_properties->prefix_extractor_name != prefix_extractor->AsString()) {
  232. return true;
  233. } else {
  234. return false;
  235. }
  236. }
  237. template <typename TBlocklike>
  238. uint32_t GetBlockNumRestarts(const TBlocklike& block) {
  239. if constexpr (std::is_convertible_v<const TBlocklike&, const Block&>) {
  240. const Block& b = block;
  241. return b.NumRestarts();
  242. } else {
  243. return 0;
  244. }
  245. }
  246. } // namespace
  247. void BlockBasedTable::UpdateCacheHitMetrics(BlockType block_type,
  248. GetContext* get_context,
  249. size_t usage) const {
  250. Statistics* const statistics = rep_->ioptions.stats;
  251. PERF_COUNTER_ADD(block_cache_hit_count, 1);
  252. PERF_COUNTER_ADD(block_cache_read_byte, usage);
  253. PERF_COUNTER_BY_LEVEL_ADD(block_cache_hit_count, 1,
  254. static_cast<uint32_t>(rep_->level));
  255. if (get_context) {
  256. ++get_context->get_context_stats_.num_cache_hit;
  257. get_context->get_context_stats_.num_cache_bytes_read += usage;
  258. } else {
  259. RecordTick(statistics, BLOCK_CACHE_HIT);
  260. RecordTick(statistics, BLOCK_CACHE_BYTES_READ, usage);
  261. }
  262. switch (block_type) {
  263. case BlockType::kFilter:
  264. case BlockType::kFilterPartitionIndex:
  265. PERF_COUNTER_ADD(block_cache_filter_hit_count, 1);
  266. PERF_COUNTER_ADD(block_cache_filter_read_byte, usage);
  267. if (get_context) {
  268. ++get_context->get_context_stats_.num_cache_filter_hit;
  269. } else {
  270. RecordTick(statistics, BLOCK_CACHE_FILTER_HIT);
  271. }
  272. break;
  273. case BlockType::kCompressionDictionary:
  274. // TODO: introduce perf counter for compression dictionary hit count
  275. PERF_COUNTER_ADD(block_cache_compression_dict_read_byte, usage);
  276. if (get_context) {
  277. ++get_context->get_context_stats_.num_cache_compression_dict_hit;
  278. } else {
  279. RecordTick(statistics, BLOCK_CACHE_COMPRESSION_DICT_HIT);
  280. }
  281. break;
  282. case BlockType::kIndex:
  283. PERF_COUNTER_ADD(block_cache_index_hit_count, 1);
  284. PERF_COUNTER_ADD(block_cache_index_read_byte, usage);
  285. if (get_context) {
  286. ++get_context->get_context_stats_.num_cache_index_hit;
  287. } else {
  288. RecordTick(statistics, BLOCK_CACHE_INDEX_HIT);
  289. }
  290. break;
  291. default:
  292. // TODO: introduce dedicated tickers/statistics/counters
  293. // for range tombstones
  294. if (get_context) {
  295. ++get_context->get_context_stats_.num_cache_data_hit;
  296. } else {
  297. RecordTick(statistics, BLOCK_CACHE_DATA_HIT);
  298. }
  299. break;
  300. }
  301. }
  302. void BlockBasedTable::UpdateCacheMissMetrics(BlockType block_type,
  303. GetContext* get_context) const {
  304. Statistics* const statistics = rep_->ioptions.stats;
  305. // TODO: introduce aggregate (not per-level) block cache miss count
  306. PERF_COUNTER_BY_LEVEL_ADD(block_cache_miss_count, 1,
  307. static_cast<uint32_t>(rep_->level));
  308. if (get_context) {
  309. ++get_context->get_context_stats_.num_cache_miss;
  310. } else {
  311. RecordTick(statistics, BLOCK_CACHE_MISS);
  312. }
  313. // TODO: introduce perf counters for misses per block type
  314. switch (block_type) {
  315. case BlockType::kFilter:
  316. case BlockType::kFilterPartitionIndex:
  317. if (get_context) {
  318. ++get_context->get_context_stats_.num_cache_filter_miss;
  319. } else {
  320. RecordTick(statistics, BLOCK_CACHE_FILTER_MISS);
  321. }
  322. break;
  323. case BlockType::kCompressionDictionary:
  324. if (get_context) {
  325. ++get_context->get_context_stats_.num_cache_compression_dict_miss;
  326. } else {
  327. RecordTick(statistics, BLOCK_CACHE_COMPRESSION_DICT_MISS);
  328. }
  329. break;
  330. case BlockType::kIndex:
  331. if (get_context) {
  332. ++get_context->get_context_stats_.num_cache_index_miss;
  333. } else {
  334. RecordTick(statistics, BLOCK_CACHE_INDEX_MISS);
  335. }
  336. break;
  337. default:
  338. // TODO: introduce dedicated tickers/statistics/counters
  339. // for range tombstones
  340. if (get_context) {
  341. ++get_context->get_context_stats_.num_cache_data_miss;
  342. } else {
  343. RecordTick(statistics, BLOCK_CACHE_DATA_MISS);
  344. }
  345. break;
  346. }
  347. }
  348. void BlockBasedTable::UpdateCacheInsertionMetrics(
  349. BlockType block_type, GetContext* get_context, size_t usage, bool redundant,
  350. Statistics* const statistics) {
  351. // TODO: introduce perf counters for block cache insertions
  352. if (get_context) {
  353. ++get_context->get_context_stats_.num_cache_add;
  354. if (redundant) {
  355. ++get_context->get_context_stats_.num_cache_add_redundant;
  356. }
  357. get_context->get_context_stats_.num_cache_bytes_write += usage;
  358. } else {
  359. RecordTick(statistics, BLOCK_CACHE_ADD);
  360. if (redundant) {
  361. RecordTick(statistics, BLOCK_CACHE_ADD_REDUNDANT);
  362. }
  363. RecordTick(statistics, BLOCK_CACHE_BYTES_WRITE, usage);
  364. }
  365. switch (block_type) {
  366. case BlockType::kFilter:
  367. case BlockType::kFilterPartitionIndex:
  368. if (get_context) {
  369. ++get_context->get_context_stats_.num_cache_filter_add;
  370. if (redundant) {
  371. ++get_context->get_context_stats_.num_cache_filter_add_redundant;
  372. }
  373. get_context->get_context_stats_.num_cache_filter_bytes_insert += usage;
  374. } else {
  375. RecordTick(statistics, BLOCK_CACHE_FILTER_ADD);
  376. if (redundant) {
  377. RecordTick(statistics, BLOCK_CACHE_FILTER_ADD_REDUNDANT);
  378. }
  379. RecordTick(statistics, BLOCK_CACHE_FILTER_BYTES_INSERT, usage);
  380. }
  381. break;
  382. case BlockType::kCompressionDictionary:
  383. if (get_context) {
  384. ++get_context->get_context_stats_.num_cache_compression_dict_add;
  385. if (redundant) {
  386. ++get_context->get_context_stats_
  387. .num_cache_compression_dict_add_redundant;
  388. }
  389. get_context->get_context_stats_
  390. .num_cache_compression_dict_bytes_insert += usage;
  391. } else {
  392. RecordTick(statistics, BLOCK_CACHE_COMPRESSION_DICT_ADD);
  393. if (redundant) {
  394. RecordTick(statistics, BLOCK_CACHE_COMPRESSION_DICT_ADD_REDUNDANT);
  395. }
  396. RecordTick(statistics, BLOCK_CACHE_COMPRESSION_DICT_BYTES_INSERT,
  397. usage);
  398. }
  399. break;
  400. case BlockType::kIndex:
  401. if (get_context) {
  402. ++get_context->get_context_stats_.num_cache_index_add;
  403. if (redundant) {
  404. ++get_context->get_context_stats_.num_cache_index_add_redundant;
  405. }
  406. get_context->get_context_stats_.num_cache_index_bytes_insert += usage;
  407. } else {
  408. RecordTick(statistics, BLOCK_CACHE_INDEX_ADD);
  409. if (redundant) {
  410. RecordTick(statistics, BLOCK_CACHE_INDEX_ADD_REDUNDANT);
  411. }
  412. RecordTick(statistics, BLOCK_CACHE_INDEX_BYTES_INSERT, usage);
  413. }
  414. break;
  415. default:
  416. // TODO: introduce dedicated tickers/statistics/counters
  417. // for range tombstones
  418. if (get_context) {
  419. ++get_context->get_context_stats_.num_cache_data_add;
  420. if (redundant) {
  421. ++get_context->get_context_stats_.num_cache_data_add_redundant;
  422. }
  423. get_context->get_context_stats_.num_cache_data_bytes_insert += usage;
  424. } else {
  425. RecordTick(statistics, BLOCK_CACHE_DATA_ADD);
  426. if (redundant) {
  427. RecordTick(statistics, BLOCK_CACHE_DATA_ADD_REDUNDANT);
  428. }
  429. RecordTick(statistics, BLOCK_CACHE_DATA_BYTES_INSERT, usage);
  430. }
  431. break;
  432. }
  433. }
  434. namespace {
  435. // Return True if table_properties has `user_prop_name` has a `true` value
  436. // or it doesn't contain this property (for backward compatible).
  437. bool IsFeatureSupported(const TableProperties& table_properties,
  438. const std::string& user_prop_name, Logger* info_log) {
  439. auto& props = table_properties.user_collected_properties;
  440. auto pos = props.find(user_prop_name);
  441. // Older version doesn't have this value set. Skip this check.
  442. if (pos != props.end()) {
  443. if (pos->second == kPropFalse) {
  444. return false;
  445. } else if (pos->second != kPropTrue) {
  446. ROCKS_LOG_WARN(info_log, "Property %s has invalidate value %s",
  447. user_prop_name.c_str(), pos->second.c_str());
  448. }
  449. }
  450. return true;
  451. }
  452. // Caller has to ensure seqno is not nullptr.
  453. // Set *seqno to the global sequence number for reading this file.
  454. Status GetGlobalSequenceNumber(const TableProperties& table_properties,
  455. SequenceNumber largest_seqno,
  456. SequenceNumber* seqno) {
  457. const auto& props = table_properties.user_collected_properties;
  458. const auto version_pos = props.find(ExternalSstFilePropertyNames::kVersion);
  459. const auto seqno_pos = props.find(ExternalSstFilePropertyNames::kGlobalSeqno);
  460. *seqno = kDisableGlobalSequenceNumber;
  461. if (version_pos == props.end()) {
  462. if (seqno_pos != props.end()) {
  463. std::array<char, 200> msg_buf;
  464. // This is not an external sst file, global_seqno is not supported.
  465. snprintf(
  466. msg_buf.data(), msg_buf.max_size(),
  467. "A non-external sst file have global seqno property with value %s",
  468. seqno_pos->second.c_str());
  469. return Status::Corruption(msg_buf.data());
  470. }
  471. return Status::OK();
  472. }
  473. uint32_t version = DecodeFixed32(version_pos->second.c_str());
  474. if (version != 2) {
  475. std::array<char, 200> msg_buf;
  476. if (version != 1) {
  477. snprintf(msg_buf.data(), msg_buf.max_size(),
  478. "An external sst file has corrupted version %u.", version);
  479. return Status::Corruption(msg_buf.data());
  480. }
  481. if (seqno_pos != props.end()) {
  482. // This is a v1 external sst file, global_seqno is not supported.
  483. snprintf(msg_buf.data(), msg_buf.max_size(),
  484. "An external sst file with version %u has global seqno "
  485. "property with value %s",
  486. version, seqno_pos->second.c_str());
  487. return Status::Corruption(msg_buf.data());
  488. }
  489. return Status::OK();
  490. }
  491. // Since we have a plan to deprecate global_seqno, we do not return failure
  492. // if seqno_pos == props.end(). We rely on version_pos to detect whether the
  493. // SST is external.
  494. SequenceNumber global_seqno(0);
  495. if (seqno_pos != props.end()) {
  496. global_seqno = DecodeFixed64(seqno_pos->second.c_str());
  497. }
  498. // SstTableReader open table reader with kMaxSequenceNumber as largest_seqno
  499. // to denote it is unknown.
  500. if (largest_seqno < kMaxSequenceNumber) {
  501. if (global_seqno == 0) {
  502. global_seqno = largest_seqno;
  503. }
  504. if (global_seqno != largest_seqno) {
  505. std::array<char, 200> msg_buf;
  506. snprintf(
  507. msg_buf.data(), msg_buf.max_size(),
  508. "An external sst file with version %u have global seqno property "
  509. "with value %s, while largest seqno in the file is %llu",
  510. version, seqno_pos->second.c_str(),
  511. static_cast<unsigned long long>(largest_seqno));
  512. return Status::Corruption(msg_buf.data());
  513. }
  514. }
  515. *seqno = global_seqno;
  516. if (global_seqno > kMaxSequenceNumber) {
  517. std::array<char, 200> msg_buf;
  518. snprintf(msg_buf.data(), msg_buf.max_size(),
  519. "An external sst file with version %u have global seqno property "
  520. "with value %llu, which is greater than kMaxSequenceNumber",
  521. version, static_cast<unsigned long long>(global_seqno));
  522. return Status::Corruption(msg_buf.data());
  523. }
  524. return Status::OK();
  525. }
  526. Status GetDecompressor(const std::string& compression_name,
  527. UnownedPtr<CompressionManager> compression_manager,
  528. uint32_t table_format_version,
  529. std::shared_ptr<Decompressor>* out_decompressor) {
  530. if (compression_name.empty()) {
  531. // Very old file (before RocksDB 4.9.0) that might contain compressed
  532. // blocks. Get a general decompressor for the format version.
  533. auto mgr_to_use = GetBuiltinCompressionManager(
  534. GetCompressFormatForVersion(table_format_version));
  535. *out_decompressor = mgr_to_use->GetDecompressor();
  536. return Status::OK();
  537. }
  538. if (FormatVersionUsesCompressionManagerName(table_format_version)) {
  539. constexpr char kFieldSep = ';';
  540. size_t separator_pos = compression_name.find_first_of(kFieldSep);
  541. if (separator_pos == std::string::npos) {
  542. return Status::Corruption(
  543. "Missing separator in compression_name property");
  544. }
  545. // Built with explicit CompressionManager and schema support for
  546. // identifying its compatibility name, which is the first field here.
  547. Slice compatibility_name(compression_name.data(), separator_pos);
  548. std::shared_ptr<CompressionManager> mgr_to_use;
  549. if (compression_manager) {
  550. // First attempt to go through the compression manager configured for
  551. // writing new files, for efficiency (usually correct) and not forcing
  552. // use of ObjectLibrary registration (dependency injection).
  553. mgr_to_use = compression_manager->FindCompatibleCompressionManager(
  554. compatibility_name);
  555. }
  556. if (mgr_to_use == nullptr) {
  557. ConfigOptions strict;
  558. strict.ignore_unknown_options = false;
  559. strict.ignore_unsupported_options = false;
  560. Status s = CompressionManager::CreateFromString(
  561. strict, compatibility_name.ToString(), &mgr_to_use);
  562. // Even though we might be able to recover from "not found" if only
  563. // built-in compression types are used (would be checked below), it
  564. // would provide misleading or unreliable success to allow that to
  565. // succeed.
  566. if (!s.ok()) {
  567. return s;
  568. }
  569. assert(mgr_to_use || compatibility_name == kNullptrString ||
  570. compatibility_name.empty());
  571. }
  572. // Second field is set of compression types actually used in the file
  573. size_t start_pos = separator_pos + 1;
  574. separator_pos = compression_name.find_first_of(kFieldSep, start_pos);
  575. if (UNLIKELY(separator_pos == std::string::npos)) {
  576. return Status::Corruption("Missing second field from compression_name");
  577. }
  578. if (UNLIKELY((separator_pos - start_pos) & 1)) {
  579. return Status::Corruption(
  580. "Second field of compression_name has odd size");
  581. }
  582. size_t count = (separator_pos - start_pos) / 2;
  583. auto ctypes = std::make_unique<CompressionType[]>(count);
  584. const char* ptr = compression_name.data() + start_pos;
  585. for (size_t i = 0; i < count; ++i) {
  586. uint64_t val = 0;
  587. bool success = ParseBaseChars<16>(&ptr, 2, &val);
  588. if (UNLIKELY(!success || val == kNoCompression ||
  589. val >= kDisableCompressionOption)) {
  590. return Status::Corruption(
  591. "Error parsing second field of compression_name");
  592. }
  593. ctypes[i] = static_cast<CompressionType>(val);
  594. }
  595. if (mgr_to_use) {
  596. *out_decompressor = mgr_to_use->GetDecompressorForTypes(
  597. ctypes.get(), ctypes.get() + count);
  598. assert(*out_decompressor || count == 0);
  599. } else {
  600. // Compression/decompression disabled
  601. *out_decompressor = nullptr;
  602. assert(count == 0);
  603. }
  604. // Can ignore possible additional future fields
  605. } else {
  606. // No explicit CompressionManager, e.g. legacy file support where
  607. // decompressing with built-in CompressionManager works.
  608. CompressionType saved_comp_type =
  609. CompressionTypeFromString(compression_name);
  610. if (saved_comp_type == kDisableCompressionOption) {
  611. // Unrecognized. For RocksDB versions able to read format_version=7,
  612. // this is considered an error so that we can continue to evolve the
  613. // schema of the compression_name property and report good error
  614. // messages.
  615. return Status::Corruption("Unrecognized compression_name: " +
  616. compression_name);
  617. } else if (saved_comp_type != kNoCompression) {
  618. // Use built-in compression manager
  619. auto mgr_to_use = GetBuiltinCompressionManager(
  620. GetCompressFormatForVersion(table_format_version));
  621. *out_decompressor =
  622. mgr_to_use->GetDecompressorOptimizeFor(saved_comp_type);
  623. } else {
  624. // No compression -> decompressor not needed
  625. *out_decompressor = nullptr;
  626. }
  627. }
  628. return Status::OK();
  629. }
  630. } // namespace
  631. void BlockBasedTable::SetupBaseCacheKey(const TableProperties* properties,
  632. const std::string& cur_db_session_id,
  633. uint64_t cur_file_number,
  634. OffsetableCacheKey* out_base_cache_key,
  635. bool* out_is_stable) {
  636. // Use a stable cache key if sufficient data is in table properties
  637. std::string db_session_id;
  638. uint64_t file_num;
  639. std::string db_id;
  640. if (properties && !properties->db_session_id.empty() &&
  641. properties->orig_file_number > 0) {
  642. // (Newer SST file case)
  643. // We must have both properties to get a stable unique id because
  644. // CreateColumnFamilyWithImport or IngestExternalFiles can change the
  645. // file numbers on a file.
  646. db_session_id = properties->db_session_id;
  647. file_num = properties->orig_file_number;
  648. // Less critical, populated in earlier release than above
  649. db_id = properties->db_id;
  650. if (out_is_stable) {
  651. *out_is_stable = true;
  652. }
  653. } else {
  654. // (Old SST file case)
  655. // We use (unique) cache keys based on current identifiers. These are at
  656. // least stable across table file close and re-open, but not across
  657. // different DBs nor DB close and re-open.
  658. db_session_id = cur_db_session_id;
  659. file_num = cur_file_number;
  660. // Plumbing through the DB ID to here would be annoying, and of limited
  661. // value because of the case of VersionSet::Recover opening some table
  662. // files and later setting the DB ID. So we just rely on uniqueness
  663. // level provided by session ID.
  664. db_id = "unknown";
  665. if (out_is_stable) {
  666. *out_is_stable = false;
  667. }
  668. }
  669. // Too many tests to update to get these working
  670. // assert(file_num > 0);
  671. // assert(!db_session_id.empty());
  672. // assert(!db_id.empty());
  673. // Minimum block size is 5 bytes; therefore we can trim off two lower bits
  674. // from offsets. See GetCacheKey.
  675. *out_base_cache_key = OffsetableCacheKey(db_id, db_session_id, file_num);
  676. }
  677. CacheKey BlockBasedTable::GetCacheKey(const OffsetableCacheKey& base_cache_key,
  678. const BlockHandle& handle) {
  679. // Minimum block size is 5 bytes; therefore we can trim off two lower bits
  680. // from offet.
  681. return base_cache_key.WithOffset(handle.offset() >> 2);
  682. }
  683. Status BlockBasedTable::Open(
  684. const ReadOptions& read_options, const ImmutableOptions& ioptions,
  685. const EnvOptions& env_options, const BlockBasedTableOptions& table_options,
  686. const InternalKeyComparator& internal_comparator,
  687. std::unique_ptr<RandomAccessFileReader>&& file, uint64_t file_size,
  688. uint8_t block_protection_bytes_per_key,
  689. std::unique_ptr<TableReader>* table_reader, uint64_t tail_size,
  690. std::shared_ptr<CacheReservationManager> table_reader_cache_res_mgr,
  691. const std::shared_ptr<const SliceTransform>& prefix_extractor,
  692. UnownedPtr<CompressionManager> compression_manager,
  693. const bool prefetch_index_and_filter_in_cache, const bool skip_filters,
  694. const int level, const bool immortal_table,
  695. const SequenceNumber largest_seqno, const bool force_direct_prefetch,
  696. TailPrefetchStats* tail_prefetch_stats,
  697. BlockCacheTracer* const block_cache_tracer,
  698. size_t max_file_size_for_l0_meta_pin, const std::string& cur_db_session_id,
  699. uint64_t cur_file_num, UniqueId64x2 expected_unique_id,
  700. const bool user_defined_timestamps_persisted) {
  701. table_reader->reset();
  702. Status s;
  703. Footer footer;
  704. std::unique_ptr<FilePrefetchBuffer> prefetch_buffer;
  705. // From read_options, retain deadline, io_timeout, rate_limiter_priority, and
  706. // verify_checksums. In future, we may retain more options.
  707. // TODO: audit more ReadOptions and do this in a way that brings attention
  708. // on new ReadOptions?
  709. ReadOptions ro;
  710. ro.deadline = read_options.deadline;
  711. ro.io_timeout = read_options.io_timeout;
  712. ro.rate_limiter_priority = read_options.rate_limiter_priority;
  713. ro.verify_checksums = read_options.verify_checksums;
  714. ro.io_activity = read_options.io_activity;
  715. ro.fill_cache = read_options.fill_cache;
  716. // prefetch both index and filters, down to all partitions
  717. const bool prefetch_all = prefetch_index_and_filter_in_cache || level == 0;
  718. const bool preload_all = !table_options.cache_index_and_filter_blocks;
  719. if (!ioptions.allow_mmap_reads && !env_options.use_mmap_reads) {
  720. s = PrefetchTail(ro, ioptions, file.get(), file_size, force_direct_prefetch,
  721. tail_prefetch_stats, prefetch_all, preload_all,
  722. &prefetch_buffer, ioptions.stats, tail_size,
  723. ioptions.logger);
  724. // Return error in prefetch path to users.
  725. if (!s.ok()) {
  726. return s;
  727. }
  728. } else {
  729. // Should not prefetch for mmap mode.
  730. prefetch_buffer.reset(new FilePrefetchBuffer(
  731. ReadaheadParams(), false /* enable */, true /* track_min_offset */));
  732. }
  733. // Read in the following order:
  734. // 1. Footer
  735. // 2. [metaindex block]
  736. // 3. [meta block: properties]
  737. // 4. [meta block: range deletion tombstone]
  738. // 5. [meta block: compression dictionary]
  739. // 6. [meta block: index]
  740. // 7. [meta block: filter]
  741. IOOptions opts;
  742. IODebugContext dbg;
  743. s = file->PrepareIOOptions(ro, opts, &dbg);
  744. if (s.ok()) {
  745. s = ReadFooterFromFile(opts, file.get(), *ioptions.fs,
  746. prefetch_buffer.get(), file_size, &footer,
  747. kBlockBasedTableMagicNumber, ioptions.stats);
  748. }
  749. if (!s.ok()) {
  750. if (s.IsCorruption()) {
  751. RecordTick(ioptions.statistics.get(), SST_FOOTER_CORRUPTION_COUNT);
  752. }
  753. return s;
  754. }
  755. if (!IsSupportedFormatVersion(footer.format_version()) &&
  756. !TEST_AllowUnsupportedFormatVersion()) {
  757. return Status::Corruption(
  758. "Unknown Footer version. Maybe this file was created with newer "
  759. "version of RocksDB?");
  760. }
  761. BlockCacheLookupContext lookup_context{TableReaderCaller::kPrefetch};
  762. Rep* rep = new BlockBasedTable::Rep(
  763. ioptions, env_options, table_options, internal_comparator, skip_filters,
  764. file_size, level, immortal_table, user_defined_timestamps_persisted);
  765. rep->file = std::move(file);
  766. rep->footer = footer;
  767. // Some ancient versions (~2.5 - 2.7, format_version=1) could compress the
  768. // metaindex block, so we need to allow for that
  769. if (footer.format_version() < 2) {
  770. auto mgr = GetBuiltinCompressionManager(/*compression_format_version=*/1);
  771. rep->decompressor = mgr->GetDecompressor();
  772. }
  773. // For fully portable/stable cache keys, we need to read the properties
  774. // block before setting up cache keys. TODO: consider setting up a bootstrap
  775. // cache key for PersistentCache to use for metaindex and properties blocks.
  776. rep->persistent_cache_options = PersistentCacheOptions();
  777. // Meta-blocks are not dictionary compressed. Explicitly set the dictionary
  778. // handle to null, otherwise it may be seen as uninitialized during the below
  779. // meta-block reads.
  780. rep->compression_dict_handle = BlockHandle::NullBlockHandle();
  781. rep->create_context.protection_bytes_per_key = block_protection_bytes_per_key;
  782. // Read metaindex
  783. std::unique_ptr<BlockBasedTable> new_table(
  784. new BlockBasedTable(rep, block_cache_tracer));
  785. std::unique_ptr<Block> metaindex;
  786. std::unique_ptr<InternalIterator> metaindex_iter;
  787. s = new_table->ReadMetaIndexBlock(ro, prefetch_buffer.get(), &metaindex,
  788. &metaindex_iter);
  789. if (!s.ok()) {
  790. return s;
  791. }
  792. // Populates table_properties and some fields that depend on it,
  793. // such as index_type.
  794. s = new_table->ReadPropertiesBlock(ro, prefetch_buffer.get(),
  795. metaindex_iter.get(), largest_seqno);
  796. if (!s.ok()) {
  797. return s;
  798. }
  799. // Read compression metadata and configure decompressor
  800. s = GetDecompressor(
  801. rep->table_properties ? rep->table_properties->compression_name
  802. : std::string{},
  803. compression_manager, footer.format_version(), &rep->decompressor);
  804. if (!s.ok()) {
  805. return s;
  806. }
  807. // Populate BlockCreateContext
  808. rep->create_context = BlockCreateContext(
  809. &rep->table_options, &rep->ioptions, rep->ioptions.stats,
  810. rep->decompressor.get(), block_protection_bytes_per_key,
  811. rep->internal_comparator.user_comparator(), rep->index_value_is_full,
  812. rep->index_has_first_key);
  813. // Check expected unique id if provided
  814. if (expected_unique_id != kNullUniqueId64x2) {
  815. auto props = rep->table_properties;
  816. if (!props) {
  817. return Status::Corruption("Missing table properties on file " +
  818. std::to_string(cur_file_num) +
  819. " with known unique ID");
  820. }
  821. UniqueId64x2 actual_unique_id{};
  822. s = GetSstInternalUniqueId(props->db_id, props->db_session_id,
  823. props->orig_file_number, &actual_unique_id,
  824. /*force*/ true);
  825. assert(s.ok()); // because force=true
  826. if (expected_unique_id != actual_unique_id) {
  827. return Status::Corruption(
  828. "Mismatch in unique ID on table file " +
  829. std::to_string(cur_file_num) +
  830. ". Expected: " + InternalUniqueIdToHumanString(&expected_unique_id) +
  831. " Actual: " + InternalUniqueIdToHumanString(&actual_unique_id));
  832. }
  833. TEST_SYNC_POINT_CALLBACK("BlockBasedTable::Open::PassedVerifyUniqueId",
  834. &actual_unique_id);
  835. } else {
  836. TEST_SYNC_POINT_CALLBACK("BlockBasedTable::Open::SkippedVerifyUniqueId",
  837. nullptr);
  838. if (ioptions.verify_sst_unique_id_in_manifest && ioptions.logger) {
  839. // A crude but isolated way of reporting unverified files. This should not
  840. // be an ongoing concern so doesn't deserve a place in Statistics IMHO.
  841. static std::atomic<uint64_t> unverified_count{0};
  842. auto prev_count =
  843. unverified_count.fetch_add(1, std::memory_order_relaxed);
  844. if (prev_count == 0) {
  845. ROCKS_LOG_WARN(
  846. ioptions.logger,
  847. "At least one SST file opened without unique ID to verify: %" PRIu64
  848. ".sst",
  849. cur_file_num);
  850. } else if (prev_count % 1000 == 0) {
  851. ROCKS_LOG_WARN(
  852. ioptions.logger,
  853. "Another ~1000 SST files opened without unique ID to verify");
  854. }
  855. }
  856. }
  857. // Set up prefix extracto as needed
  858. bool force_null_table_prefix_extractor = false;
  859. TEST_SYNC_POINT_CALLBACK(
  860. "BlockBasedTable::Open::ForceNullTablePrefixExtractor",
  861. &force_null_table_prefix_extractor);
  862. if (force_null_table_prefix_extractor) {
  863. assert(!rep->table_prefix_extractor);
  864. } else if (!PrefixExtractorChangedHelper(rep->table_properties.get(),
  865. prefix_extractor.get())) {
  866. // Establish fast path for unchanged prefix_extractor
  867. rep->table_prefix_extractor = prefix_extractor;
  868. } else {
  869. // Current prefix_extractor doesn't match table
  870. if (rep->table_properties) {
  871. //**TODO: If/When the DBOptions has a registry in it, the ConfigOptions
  872. // will need to use it
  873. ConfigOptions config_options;
  874. Status st = SliceTransform::CreateFromString(
  875. config_options, rep->table_properties->prefix_extractor_name,
  876. &(rep->table_prefix_extractor));
  877. if (!st.ok()) {
  878. //**TODO: Should this be error be returned or swallowed?
  879. ROCKS_LOG_ERROR(rep->ioptions.logger,
  880. "Failed to create prefix extractor[%s]: %s",
  881. rep->table_properties->prefix_extractor_name.c_str(),
  882. st.ToString().c_str());
  883. }
  884. }
  885. }
  886. // With properties loaded, we can set up portable/stable cache keys
  887. SetupBaseCacheKey(rep->table_properties.get(), cur_db_session_id,
  888. cur_file_num, &rep->base_cache_key);
  889. rep->persistent_cache_options =
  890. PersistentCacheOptions(rep->table_options.persistent_cache,
  891. rep->base_cache_key, rep->ioptions.stats);
  892. s = new_table->ReadRangeDelBlock(ro, prefetch_buffer.get(),
  893. metaindex_iter.get(), internal_comparator,
  894. &lookup_context);
  895. if (!s.ok()) {
  896. return s;
  897. }
  898. rep->verify_checksum_set_on_open = ro.verify_checksums;
  899. s = new_table->PrefetchIndexAndFilterBlocks(
  900. ro, prefetch_buffer.get(), metaindex_iter.get(), new_table.get(),
  901. prefetch_all, table_options, level, file_size,
  902. max_file_size_for_l0_meta_pin, &lookup_context);
  903. if (s.ok()) {
  904. // Update tail prefetch stats
  905. assert(prefetch_buffer.get() != nullptr);
  906. if (tail_prefetch_stats != nullptr) {
  907. assert(prefetch_buffer->min_offset_read() < file_size);
  908. tail_prefetch_stats->RecordEffectiveSize(
  909. static_cast<size_t>(file_size) - prefetch_buffer->min_offset_read());
  910. }
  911. }
  912. if (s.ok() && table_reader_cache_res_mgr) {
  913. std::size_t mem_usage = new_table->ApproximateMemoryUsage();
  914. s = table_reader_cache_res_mgr->MakeCacheReservation(
  915. mem_usage, &(rep->table_reader_cache_res_handle));
  916. if (s.IsMemoryLimit()) {
  917. s = Status::MemoryLimit(
  918. "Can't allocate " +
  919. kCacheEntryRoleToCamelString[static_cast<std::uint32_t>(
  920. CacheEntryRole::kBlockBasedTableReader)] +
  921. " due to memory limit based on "
  922. "cache capacity for memory allocation");
  923. }
  924. }
  925. if (s.ok()) {
  926. *table_reader = std::move(new_table);
  927. }
  928. return s;
  929. }
  930. Status BlockBasedTable::PrefetchTail(
  931. const ReadOptions& ro, const ImmutableOptions& ioptions,
  932. RandomAccessFileReader* file, uint64_t file_size,
  933. bool force_direct_prefetch, TailPrefetchStats* tail_prefetch_stats,
  934. const bool prefetch_all, const bool preload_all,
  935. std::unique_ptr<FilePrefetchBuffer>* prefetch_buffer, Statistics* stats,
  936. uint64_t tail_size, Logger* const logger) {
  937. assert(tail_size <= file_size);
  938. size_t tail_prefetch_size = 0;
  939. if (tail_size != 0) {
  940. tail_prefetch_size = tail_size;
  941. } else {
  942. // Fallback for SST files, for which tail size is not recorded in the
  943. // manifest. Eventually, this fallback might be removed, so it's
  944. // better to make sure that such SST files get compacted.
  945. // See https://github.com/facebook/rocksdb/issues/12664
  946. if (tail_prefetch_stats != nullptr) {
  947. // Multiple threads may get a 0 (no history) when running in parallel,
  948. // but it will get cleared after the first of them finishes.
  949. tail_prefetch_size = tail_prefetch_stats->GetSuggestedPrefetchSize();
  950. }
  951. if (tail_prefetch_size == 0) {
  952. // Before read footer, readahead backwards to prefetch data. Do more
  953. // readahead if we're going to read index/filter.
  954. // TODO: This may incorrectly select small readahead in case partitioned
  955. // index/filter is enabled and top-level partition pinning is enabled.
  956. // That's because we need to issue readahead before we read the
  957. // properties, at which point we don't yet know the index type.
  958. tail_prefetch_size = prefetch_all || preload_all ? 512 * 1024 : 4 * 1024;
  959. ROCKS_LOG_WARN(
  960. logger,
  961. "[%s] Tail prefetch size %zu is calculated based on heuristics.",
  962. file->file_name().c_str(), tail_prefetch_size);
  963. } else {
  964. ROCKS_LOG_WARN(logger,
  965. "[%s] Tail prefetch size %zu is calculated based on "
  966. "TailPrefetchStats.",
  967. file->file_name().c_str(), tail_prefetch_size);
  968. }
  969. TEST_SYNC_POINT("BlockBasedTable::PrefetchTail::TaiSizeNotRecorded");
  970. }
  971. size_t prefetch_off;
  972. size_t prefetch_len;
  973. if (file_size < tail_prefetch_size) {
  974. prefetch_off = 0;
  975. prefetch_len = static_cast<size_t>(file_size);
  976. } else {
  977. prefetch_off = static_cast<size_t>(file_size - tail_prefetch_size);
  978. prefetch_len = tail_prefetch_size;
  979. }
  980. #ifndef NDEBUG
  981. std::pair<size_t*, size_t*> prefetch_off_len_pair = {&prefetch_off,
  982. &prefetch_len};
  983. TEST_SYNC_POINT_CALLBACK("BlockBasedTable::Open::TailPrefetchLen",
  984. &prefetch_off_len_pair);
  985. #endif // NDEBUG
  986. IOOptions opts;
  987. IODebugContext dbg;
  988. Status s = file->PrepareIOOptions(ro, opts, &dbg);
  989. // Try file system prefetch
  990. if (s.ok() && !file->use_direct_io() && !force_direct_prefetch) {
  991. if (!file->Prefetch(opts, prefetch_off, prefetch_len).IsNotSupported()) {
  992. prefetch_buffer->reset(new FilePrefetchBuffer(
  993. ReadaheadParams(), false /* enable */, true /* track_min_offset */));
  994. return Status::OK();
  995. }
  996. }
  997. // Use `FilePrefetchBuffer`
  998. prefetch_buffer->reset(new FilePrefetchBuffer(
  999. ReadaheadParams(), true /* enable */, true /* track_min_offset */,
  1000. ioptions.fs.get() /* fs */, nullptr /* clock */, stats,
  1001. /* readahead_cb */ nullptr,
  1002. FilePrefetchBufferUsage::kTableOpenPrefetchTail));
  1003. if (s.ok()) {
  1004. s = (*prefetch_buffer)->Prefetch(opts, file, prefetch_off, prefetch_len);
  1005. }
  1006. return s;
  1007. }
  1008. Status BlockBasedTable::ReadPropertiesBlock(
  1009. const ReadOptions& ro, FilePrefetchBuffer* prefetch_buffer,
  1010. InternalIterator* meta_iter, const SequenceNumber largest_seqno) {
  1011. Status s;
  1012. BlockHandle handle;
  1013. s = FindOptionalMetaBlock(meta_iter, kPropertiesBlockName, &handle);
  1014. if (!s.ok()) {
  1015. ROCKS_LOG_WARN(rep_->ioptions.logger,
  1016. "Error when seeking to properties block from file: %s",
  1017. s.ToString().c_str());
  1018. } else if (!handle.IsNull()) {
  1019. s = meta_iter->status();
  1020. std::unique_ptr<TableProperties> table_properties;
  1021. if (s.ok()) {
  1022. s = ReadTablePropertiesHelper(
  1023. ro, handle, rep_->file.get(), prefetch_buffer, rep_->footer,
  1024. rep_->ioptions, &table_properties, nullptr /* memory_allocator */);
  1025. }
  1026. IGNORE_STATUS_IF_ERROR(s);
  1027. if (!s.ok()) {
  1028. ROCKS_LOG_WARN(rep_->ioptions.logger,
  1029. "Encountered error while reading data from properties "
  1030. "block %s",
  1031. s.ToString().c_str());
  1032. } else {
  1033. assert(table_properties != nullptr);
  1034. rep_->table_properties = std::move(table_properties);
  1035. if (s.ok()) {
  1036. s = rep_->seqno_to_time_mapping.DecodeFrom(
  1037. rep_->table_properties->seqno_to_time_mapping);
  1038. }
  1039. if (!s.ok()) {
  1040. ROCKS_LOG_WARN(
  1041. rep_->ioptions.logger,
  1042. "Problem reading or processing seqno-to-time mapping: %s",
  1043. s.ToString().c_str());
  1044. }
  1045. }
  1046. } else {
  1047. ROCKS_LOG_ERROR(rep_->ioptions.logger,
  1048. "Cannot find Properties block from file.");
  1049. }
  1050. // Read the table properties, if provided.
  1051. if (rep_->table_properties) {
  1052. rep_->whole_key_filtering &=
  1053. IsFeatureSupported(*(rep_->table_properties),
  1054. BlockBasedTablePropertyNames::kWholeKeyFiltering,
  1055. rep_->ioptions.logger);
  1056. rep_->prefix_filtering &= IsFeatureSupported(
  1057. *(rep_->table_properties),
  1058. BlockBasedTablePropertyNames::kPrefixFiltering, rep_->ioptions.logger);
  1059. rep_->index_key_includes_seq =
  1060. rep_->table_properties->index_key_is_user_key == 0;
  1061. rep_->index_value_is_full =
  1062. rep_->table_properties->index_value_is_delta_encoded == 0;
  1063. // Update index_type with the true type.
  1064. // If table properties don't contain index type, we assume that the table
  1065. // is in very old format and has kBinarySearch index type.
  1066. auto& props = rep_->table_properties->user_collected_properties;
  1067. auto index_type_pos = props.find(BlockBasedTablePropertyNames::kIndexType);
  1068. if (index_type_pos != props.end()) {
  1069. rep_->index_type = static_cast<BlockBasedTableOptions::IndexType>(
  1070. DecodeFixed32(index_type_pos->second.c_str()));
  1071. }
  1072. auto min_ts_pos = props.find("rocksdb.timestamp_min");
  1073. if (min_ts_pos != props.end()) {
  1074. rep_->min_timestamp = Slice(min_ts_pos->second);
  1075. }
  1076. auto max_ts_pos = props.find("rocksdb.timestamp_max");
  1077. if (max_ts_pos != props.end()) {
  1078. rep_->max_timestamp = Slice(max_ts_pos->second);
  1079. }
  1080. rep_->index_has_first_key =
  1081. rep_->index_type == BlockBasedTableOptions::kBinarySearchWithFirstKey;
  1082. s = GetGlobalSequenceNumber(*(rep_->table_properties), largest_seqno,
  1083. &(rep_->global_seqno));
  1084. if (!s.ok()) {
  1085. ROCKS_LOG_ERROR(rep_->ioptions.logger, "%s", s.ToString().c_str());
  1086. }
  1087. }
  1088. return s;
  1089. }
  1090. Status BlockBasedTable::ReadRangeDelBlock(
  1091. const ReadOptions& read_options, FilePrefetchBuffer* prefetch_buffer,
  1092. InternalIterator* meta_iter,
  1093. const InternalKeyComparator& internal_comparator,
  1094. BlockCacheLookupContext* lookup_context) {
  1095. Status s;
  1096. BlockHandle range_del_handle;
  1097. s = FindOptionalMetaBlock(meta_iter, kRangeDelBlockName, &range_del_handle);
  1098. if (!s.ok()) {
  1099. ROCKS_LOG_WARN(
  1100. rep_->ioptions.logger,
  1101. "Error when seeking to range delete tombstones block from file: %s",
  1102. s.ToString().c_str());
  1103. } else if (!range_del_handle.IsNull()) {
  1104. Status tmp_status;
  1105. std::unique_ptr<InternalIterator> iter(NewDataBlockIterator<DataBlockIter>(
  1106. read_options, range_del_handle,
  1107. /*input_iter=*/nullptr, BlockType::kRangeDeletion,
  1108. /*get_context=*/nullptr, lookup_context, prefetch_buffer,
  1109. /*for_compaction= */ false, /*async_read= */ false, tmp_status,
  1110. /*use_block_cache_for_lookup=*/true));
  1111. assert(iter != nullptr);
  1112. s = iter->status();
  1113. if (!s.ok()) {
  1114. ROCKS_LOG_WARN(
  1115. rep_->ioptions.logger,
  1116. "Encountered error while reading data from range del block %s",
  1117. s.ToString().c_str());
  1118. IGNORE_STATUS_IF_ERROR(s);
  1119. } else {
  1120. std::vector<SequenceNumber> snapshots;
  1121. // When user defined timestamps are not persisted, the range tombstone end
  1122. // key read from the data block doesn't include user timestamp.
  1123. // The range tombstone start key should already include user timestamp as
  1124. // it's handled at block parsing level in the same way as the other data
  1125. // blocks.
  1126. rep_->fragmented_range_dels =
  1127. std::make_shared<FragmentedRangeTombstoneList>(
  1128. std::move(iter), internal_comparator, false /*for_compaction=*/,
  1129. snapshots, rep_->user_defined_timestamps_persisted);
  1130. }
  1131. }
  1132. return s;
  1133. }
  1134. Status BlockBasedTable::PrefetchIndexAndFilterBlocks(
  1135. const ReadOptions& ro, FilePrefetchBuffer* prefetch_buffer,
  1136. InternalIterator* meta_iter, BlockBasedTable* new_table, bool prefetch_all,
  1137. const BlockBasedTableOptions& table_options, const int level,
  1138. size_t file_size, size_t max_file_size_for_l0_meta_pin,
  1139. BlockCacheLookupContext* lookup_context) {
  1140. // Find filter handle and filter type
  1141. if (rep_->filter_policy) {
  1142. auto name = rep_->filter_policy->CompatibilityName();
  1143. for (const auto& [filter_type, prefix] :
  1144. {std::make_pair(Rep::FilterType::kFullFilter, kFullFilterBlockPrefix),
  1145. std::make_pair(Rep::FilterType::kPartitionedFilter,
  1146. kPartitionedFilterBlockPrefix),
  1147. std::make_pair(Rep::FilterType::kNoFilter,
  1148. kObsoleteFilterBlockPrefix)}) {
  1149. std::string filter_block_key = prefix + name;
  1150. if (FindMetaBlock(meta_iter, filter_block_key, &rep_->filter_handle)
  1151. .ok()) {
  1152. rep_->filter_type = filter_type;
  1153. if (filter_type == Rep::FilterType::kNoFilter) {
  1154. ROCKS_LOG_WARN(
  1155. rep_->ioptions.logger,
  1156. "Detected obsolete filter type in %s. Read performance might "
  1157. "suffer until DB is fully re-compacted.",
  1158. rep_->file->file_name().c_str());
  1159. }
  1160. break;
  1161. }
  1162. }
  1163. }
  1164. // Partition filters cannot be enabled without partition indexes
  1165. assert(rep_->filter_type != Rep::FilterType::kPartitionedFilter ||
  1166. rep_->index_type == BlockBasedTableOptions::kTwoLevelIndexSearch);
  1167. // Find compression dictionary handle
  1168. Status s = FindOptionalMetaBlock(meta_iter, kCompressionDictBlockName,
  1169. &rep_->compression_dict_handle);
  1170. if (!s.ok()) {
  1171. return s;
  1172. }
  1173. BlockBasedTableOptions::IndexType index_type = rep_->index_type;
  1174. const bool use_cache = table_options.cache_index_and_filter_blocks;
  1175. const bool maybe_flushed =
  1176. level == 0 && file_size <= max_file_size_for_l0_meta_pin;
  1177. std::function<bool(PinningTier, PinningTier)> is_pinned =
  1178. [maybe_flushed, &is_pinned](PinningTier pinning_tier,
  1179. PinningTier fallback_pinning_tier) {
  1180. // Fallback to fallback would lead to infinite recursion. Disallow it.
  1181. assert(fallback_pinning_tier != PinningTier::kFallback);
  1182. switch (pinning_tier) {
  1183. case PinningTier::kFallback:
  1184. return is_pinned(fallback_pinning_tier,
  1185. PinningTier::kNone /* fallback_pinning_tier */);
  1186. case PinningTier::kNone:
  1187. return false;
  1188. case PinningTier::kFlushedAndSimilar:
  1189. return maybe_flushed;
  1190. case PinningTier::kAll:
  1191. return true;
  1192. };
  1193. // In GCC, this is needed to suppress `control reaches end of non-void
  1194. // function [-Werror=return-type]`.
  1195. assert(false);
  1196. return false;
  1197. };
  1198. const bool pin_top_level_index = is_pinned(
  1199. table_options.metadata_cache_options.top_level_index_pinning,
  1200. table_options.pin_top_level_index_and_filter ? PinningTier::kAll
  1201. : PinningTier::kNone);
  1202. const bool pin_partition =
  1203. is_pinned(table_options.metadata_cache_options.partition_pinning,
  1204. table_options.pin_l0_filter_and_index_blocks_in_cache
  1205. ? PinningTier::kFlushedAndSimilar
  1206. : PinningTier::kNone);
  1207. const bool pin_unpartitioned =
  1208. is_pinned(table_options.metadata_cache_options.unpartitioned_pinning,
  1209. table_options.pin_l0_filter_and_index_blocks_in_cache
  1210. ? PinningTier::kFlushedAndSimilar
  1211. : PinningTier::kNone);
  1212. // pin the first level of index
  1213. const bool pin_index =
  1214. index_type == BlockBasedTableOptions::kTwoLevelIndexSearch
  1215. ? pin_top_level_index
  1216. : pin_unpartitioned;
  1217. // prefetch the first level of index
  1218. // WART: this might be redundant (unnecessary cache hit) if !pin_index,
  1219. // depending on prepopulate_block_cache option
  1220. const bool prefetch_index = prefetch_all || pin_index;
  1221. std::unique_ptr<IndexReader> index_reader;
  1222. s = new_table->CreateIndexReader(ro, prefetch_buffer, meta_iter, use_cache,
  1223. prefetch_index, pin_index, lookup_context,
  1224. &index_reader);
  1225. if (!s.ok()) {
  1226. return s;
  1227. }
  1228. if (table_options.user_defined_index_factory != nullptr) {
  1229. std::string udi_name(table_options.user_defined_index_factory->Name());
  1230. BlockHandle udi_block_handle;
  1231. // Should we use FindOptionalMetaBlock here?
  1232. s = FindMetaBlock(meta_iter, kUserDefinedIndexPrefix + udi_name,
  1233. &udi_block_handle);
  1234. if (!s.ok()) {
  1235. RecordTick(rep_->ioptions.statistics.get(),
  1236. SST_USER_DEFINED_INDEX_LOAD_FAIL_COUNT);
  1237. if (table_options.fail_if_no_udi_on_open) {
  1238. ROCKS_LOG_ERROR(rep_->ioptions.logger,
  1239. "Failed to find the the UDI block %s in file %s; %s",
  1240. udi_name.c_str(), rep_->file->file_name().c_str(),
  1241. s.ToString().c_str());
  1242. // MAke the status more informative
  1243. s = Status::Corruption(s.ToString(), rep_->file->file_name());
  1244. return s;
  1245. } else {
  1246. // Emit a warning, but ignore the error status
  1247. ROCKS_LOG_WARN(rep_->ioptions.logger,
  1248. "Failed to find the the UDI block %s in file %s; %s",
  1249. udi_name.c_str(), rep_->file->file_name().c_str(),
  1250. s.ToString().c_str());
  1251. s = Status::OK();
  1252. }
  1253. }
  1254. // If the UDI block size is 0, that means there's effectively no user
  1255. // defined index. In that case, skip setting up the reader.
  1256. if (udi_block_handle.size() > 0) {
  1257. // Read the block, and allocate on heap or pin in cache. The UDI block is
  1258. // not compressed. RetrieveBlock will verify the checksum.
  1259. if (s.ok()) {
  1260. s = RetrieveBlock(prefetch_buffer, ro, udi_block_handle,
  1261. rep_->decompressor.get(), &rep_->udi_block,
  1262. /*get_context=*/nullptr, lookup_context,
  1263. /*for_compaction=*/false, use_cache,
  1264. /*async_read=*/false,
  1265. /*use_block_cache_for_lookup=*/false);
  1266. }
  1267. if (s.ok()) {
  1268. assert(!rep_->udi_block.IsEmpty());
  1269. std::unique_ptr<UserDefinedIndexReader> udi_reader;
  1270. UserDefinedIndexOption udi_option;
  1271. udi_option.comparator = rep_->internal_comparator.user_comparator();
  1272. s = table_options.user_defined_index_factory->NewReader(
  1273. udi_option, rep_->udi_block.GetValue()->data, udi_reader);
  1274. if (s.ok()) {
  1275. if (udi_reader) {
  1276. index_reader = std::make_unique<UserDefinedIndexReaderWrapper>(
  1277. udi_name, std::move(index_reader), std::move(udi_reader));
  1278. } else {
  1279. s = Status::Corruption("Failed to create UDI reader for " +
  1280. udi_name + " in file " +
  1281. rep_->file->file_name());
  1282. }
  1283. }
  1284. }
  1285. }
  1286. }
  1287. rep_->index_reader = std::move(index_reader);
  1288. // The partitions of partitioned index are always stored in cache. They
  1289. // are hence follow the configuration for pin and prefetch regardless of
  1290. // the value of cache_index_and_filter_blocks
  1291. if (s.ok() && (prefetch_all || pin_partition)) {
  1292. s = rep_->index_reader->CacheDependencies(ro, pin_partition,
  1293. prefetch_buffer);
  1294. }
  1295. if (!s.ok()) {
  1296. return s;
  1297. }
  1298. // pin the first level of filter
  1299. const bool pin_filter =
  1300. rep_->filter_type == Rep::FilterType::kPartitionedFilter
  1301. ? pin_top_level_index
  1302. : pin_unpartitioned;
  1303. // prefetch the first level of filter
  1304. // WART: this might be redundant (unnecessary cache hit) if !pin_filter,
  1305. // depending on prepopulate_block_cache option
  1306. const bool prefetch_filter = prefetch_all || pin_filter;
  1307. if (rep_->filter_policy) {
  1308. auto filter = new_table->CreateFilterBlockReader(
  1309. ro, prefetch_buffer, use_cache, prefetch_filter, pin_filter,
  1310. lookup_context);
  1311. if (filter) {
  1312. // Refer to the comment above about paritioned indexes always being cached
  1313. if (prefetch_all || pin_partition) {
  1314. s = filter->CacheDependencies(ro, pin_partition, prefetch_buffer);
  1315. if (!s.ok()) {
  1316. return s;
  1317. }
  1318. }
  1319. rep_->filter = std::move(filter);
  1320. }
  1321. }
  1322. // NOTE: before the fix to https://github.com/facebook/rocksdb/issues/12409, a
  1323. // file could have a (de)compression dictionary block without a configured
  1324. // compression, so we need to ignore the dictionary in that case.
  1325. if (!rep_->compression_dict_handle.IsNull() && rep_->decompressor) {
  1326. std::unique_ptr<UncompressionDictReader> uncompression_dict_reader;
  1327. s = UncompressionDictReader::Create(
  1328. this, ro, prefetch_buffer, use_cache, prefetch_all || pin_unpartitioned,
  1329. pin_unpartitioned, lookup_context, &uncompression_dict_reader);
  1330. if (!s.ok()) {
  1331. return s;
  1332. }
  1333. rep_->uncompression_dict_reader = std::move(uncompression_dict_reader);
  1334. }
  1335. assert(s.ok());
  1336. return s;
  1337. }
  1338. void BlockBasedTable::SetupForCompaction() {}
  1339. std::shared_ptr<const TableProperties> BlockBasedTable::GetTableProperties()
  1340. const {
  1341. return rep_->table_properties;
  1342. }
  1343. const SeqnoToTimeMapping& BlockBasedTable::GetSeqnoToTimeMapping() const {
  1344. return rep_->seqno_to_time_mapping;
  1345. }
  1346. size_t BlockBasedTable::ApproximateMemoryUsage() const {
  1347. size_t usage = 0;
  1348. if (rep_) {
  1349. usage += rep_->ApproximateMemoryUsage();
  1350. } else {
  1351. return usage;
  1352. }
  1353. if (rep_->filter) {
  1354. usage += rep_->filter->ApproximateMemoryUsage();
  1355. }
  1356. if (rep_->index_reader) {
  1357. usage += rep_->index_reader->ApproximateMemoryUsage();
  1358. }
  1359. if (rep_->uncompression_dict_reader) {
  1360. usage += rep_->uncompression_dict_reader->ApproximateMemoryUsage();
  1361. }
  1362. if (rep_->table_properties) {
  1363. usage += rep_->table_properties->ApproximateMemoryUsage();
  1364. }
  1365. return usage;
  1366. }
  1367. // Load the meta-index-block from the file. On success, return the loaded
  1368. // metaindex
  1369. // block and its iterator.
  1370. Status BlockBasedTable::ReadMetaIndexBlock(
  1371. const ReadOptions& ro, FilePrefetchBuffer* prefetch_buffer,
  1372. std::unique_ptr<Block>* metaindex_block,
  1373. std::unique_ptr<InternalIterator>* iter) {
  1374. // TODO(sanjay): Skip this if footer.metaindex_handle() size indicates
  1375. // it is an empty block.
  1376. std::unique_ptr<Block_kMetaIndex> metaindex;
  1377. Status s = ReadAndParseBlockFromFile(
  1378. rep_->file.get(), prefetch_buffer, rep_->footer, ro,
  1379. rep_->footer.metaindex_handle(), &metaindex, rep_->ioptions,
  1380. rep_->create_context, true /*maybe_compressed*/, rep_->decompressor.get(),
  1381. rep_->persistent_cache_options, GetMemoryAllocator(rep_->table_options),
  1382. false /* for_compaction */, false /* async_read */);
  1383. if (!s.ok()) {
  1384. ROCKS_LOG_ERROR(rep_->ioptions.logger,
  1385. "Encountered error while reading data from properties"
  1386. " block %s",
  1387. s.ToString().c_str());
  1388. return s;
  1389. }
  1390. *metaindex_block = std::move(metaindex);
  1391. // meta block uses bytewise comparator.
  1392. iter->reset(metaindex_block->get()->NewMetaIterator());
  1393. return Status::OK();
  1394. }
  1395. template <typename TBlocklike>
  1396. Cache::Priority BlockBasedTable::GetCachePriority() const {
  1397. // Here we treat the legacy name "...index_and_filter_blocks..." to mean all
  1398. // metadata blocks that might go into block cache, EXCEPT only those needed
  1399. // for the read path (Get, etc.). TableProperties should not be needed on the
  1400. // read path (prefix extractor setting is an O(1) size special case that we
  1401. // are working not to require from TableProperties), so it is not given
  1402. // high-priority treatment if it should go into BlockCache.
  1403. if constexpr (TBlocklike::kBlockType == BlockType::kData ||
  1404. TBlocklike::kBlockType == BlockType::kProperties) {
  1405. return Cache::Priority::LOW;
  1406. } else if (rep_->table_options
  1407. .cache_index_and_filter_blocks_with_high_priority) {
  1408. return Cache::Priority::HIGH;
  1409. } else {
  1410. return Cache::Priority::LOW;
  1411. }
  1412. }
  1413. template <typename TBlocklike>
  1414. WithBlocklikeCheck<Status, TBlocklike> BlockBasedTable::GetDataBlockFromCache(
  1415. const Slice& cache_key, BlockCacheInterface<TBlocklike> block_cache,
  1416. CachableEntry<TBlocklike>* out_parsed_block, GetContext* get_context,
  1417. UnownedPtr<Decompressor> decomp) const {
  1418. assert(out_parsed_block);
  1419. assert(out_parsed_block->IsEmpty());
  1420. Status s;
  1421. Statistics* statistics = rep_->ioptions.statistics.get();
  1422. // Lookup uncompressed cache first
  1423. if (block_cache) {
  1424. assert(!cache_key.empty());
  1425. typename BlockCacheInterface<TBlocklike>::TypedHandle* cache_handle;
  1426. if (decomp.get() != rep_->decompressor.get() && decomp) {
  1427. // `decomp` must be a dictionary-aware decompressor, which is only
  1428. // available in the block cache (so that dictionaries can be evicted
  1429. // from memory) and can't live in the table reader.
  1430. // NOTE: inefficient BlockCreateContext copy for dict-aware decompressor
  1431. // (see TODO in block_cache.h)
  1432. BlockCreateContext create_ctx = rep_->create_context;
  1433. create_ctx.decompressor = decomp.get();
  1434. cache_handle = block_cache.LookupFull(
  1435. cache_key, &create_ctx, GetCachePriority<TBlocklike>(), statistics,
  1436. rep_->ioptions.lowest_used_cache_tier);
  1437. } else {
  1438. cache_handle = block_cache.LookupFull(
  1439. cache_key, &rep_->create_context, GetCachePriority<TBlocklike>(),
  1440. statistics, rep_->ioptions.lowest_used_cache_tier);
  1441. }
  1442. // Avoid updating metrics here if the handle is not complete yet. This
  1443. // happens with MultiGet and secondary cache. So update the metrics only
  1444. // if its a miss, or a hit and value is ready
  1445. if (!cache_handle) {
  1446. UpdateCacheMissMetrics(TBlocklike::kBlockType, get_context);
  1447. } else {
  1448. TBlocklike* value = block_cache.Value(cache_handle);
  1449. if (value) {
  1450. UpdateCacheHitMetrics(TBlocklike::kBlockType, get_context,
  1451. block_cache.get()->GetUsage(cache_handle));
  1452. }
  1453. out_parsed_block->SetCachedValue(value, block_cache.get(), cache_handle);
  1454. return s;
  1455. }
  1456. }
  1457. // If not found, search from the compressed block cache.
  1458. assert(out_parsed_block->IsEmpty());
  1459. return s;
  1460. }
  1461. template <typename TBlocklike>
  1462. WithBlocklikeCheck<Status, TBlocklike> BlockBasedTable::PutDataBlockToCache(
  1463. const Slice& cache_key, BlockCacheInterface<TBlocklike> block_cache,
  1464. CachableEntry<TBlocklike>* out_parsed_block,
  1465. BlockContents&& uncompressed_block_contents,
  1466. BlockContents&& compressed_block_contents, CompressionType block_comp_type,
  1467. UnownedPtr<Decompressor> decomp, MemoryAllocator* memory_allocator,
  1468. GetContext* get_context) const {
  1469. const ImmutableOptions& ioptions = rep_->ioptions;
  1470. assert(out_parsed_block);
  1471. assert(out_parsed_block->IsEmpty());
  1472. Status s;
  1473. Statistics* statistics = ioptions.stats;
  1474. std::unique_ptr<TBlocklike> block_holder;
  1475. if (block_comp_type != kNoCompression &&
  1476. uncompressed_block_contents.data.empty()) {
  1477. assert(compressed_block_contents.data.data());
  1478. // Retrieve the uncompressed contents into a new buffer
  1479. s = DecompressBlockData(
  1480. compressed_block_contents.data.data(),
  1481. compressed_block_contents.data.size(), block_comp_type, *decomp,
  1482. &uncompressed_block_contents, ioptions, memory_allocator);
  1483. if (!s.ok()) {
  1484. return s;
  1485. }
  1486. }
  1487. rep_->create_context.Create(&block_holder,
  1488. std::move(uncompressed_block_contents));
  1489. // insert into uncompressed block cache
  1490. if (block_cache && block_holder->own_bytes()) {
  1491. size_t charge = block_holder->ApproximateMemoryUsage();
  1492. BlockCacheTypedHandle<TBlocklike>* cache_handle = nullptr;
  1493. s = block_cache.InsertFull(cache_key, block_holder.get(), charge,
  1494. &cache_handle, GetCachePriority<TBlocklike>(),
  1495. rep_->ioptions.lowest_used_cache_tier,
  1496. compressed_block_contents.data, block_comp_type);
  1497. if (s.ok()) {
  1498. assert(cache_handle != nullptr);
  1499. out_parsed_block->SetCachedValue(block_holder.release(),
  1500. block_cache.get(), cache_handle);
  1501. UpdateCacheInsertionMetrics(TBlocklike::kBlockType, get_context, charge,
  1502. s.IsOkOverwritten(), rep_->ioptions.stats);
  1503. } else {
  1504. RecordTick(statistics, BLOCK_CACHE_ADD_FAILURES);
  1505. }
  1506. } else {
  1507. out_parsed_block->SetOwnedValue(std::move(block_holder));
  1508. }
  1509. return s;
  1510. }
  1511. std::unique_ptr<FilterBlockReader> BlockBasedTable::CreateFilterBlockReader(
  1512. const ReadOptions& ro, FilePrefetchBuffer* prefetch_buffer, bool use_cache,
  1513. bool prefetch, bool pin, BlockCacheLookupContext* lookup_context) {
  1514. auto& rep = rep_;
  1515. auto filter_type = rep->filter_type;
  1516. if (filter_type == Rep::FilterType::kNoFilter) {
  1517. return std::unique_ptr<FilterBlockReader>();
  1518. }
  1519. assert(rep->filter_policy);
  1520. switch (filter_type) {
  1521. case Rep::FilterType::kPartitionedFilter:
  1522. return PartitionedFilterBlockReader::Create(
  1523. this, ro, prefetch_buffer, use_cache, prefetch, pin, lookup_context);
  1524. case Rep::FilterType::kFullFilter:
  1525. return FullFilterBlockReader::Create(this, ro, prefetch_buffer, use_cache,
  1526. prefetch, pin, lookup_context);
  1527. default:
  1528. // filter_type is either kNoFilter (exited the function at the first if),
  1529. // or it must be covered in this switch block
  1530. assert(false);
  1531. return std::unique_ptr<FilterBlockReader>();
  1532. }
  1533. }
  1534. // disable_prefix_seek should be set to true when prefix_extractor found in SST
  1535. // differs from the one in mutable_cf_options and index type is HashBasedIndex
  1536. InternalIteratorBase<IndexValue>* BlockBasedTable::NewIndexIterator(
  1537. const ReadOptions& read_options, bool disable_prefix_seek,
  1538. IndexBlockIter* input_iter, GetContext* get_context,
  1539. BlockCacheLookupContext* lookup_context) const {
  1540. assert(rep_ != nullptr);
  1541. assert(rep_->index_reader != nullptr);
  1542. // We don't return pinned data from index blocks, so no need
  1543. // to set `block_contents_pinned`.
  1544. return rep_->index_reader->NewIterator(read_options, disable_prefix_seek,
  1545. input_iter, get_context,
  1546. lookup_context);
  1547. }
  1548. // TODO?
  1549. template <>
  1550. DataBlockIter* BlockBasedTable::InitBlockIterator<DataBlockIter>(
  1551. const Rep* rep, Block* block, BlockType block_type,
  1552. DataBlockIter* input_iter, bool block_contents_pinned) {
  1553. return block->NewDataIterator(rep->internal_comparator.user_comparator(),
  1554. rep->get_global_seqno(block_type), input_iter,
  1555. rep->ioptions.stats, block_contents_pinned,
  1556. rep->user_defined_timestamps_persisted);
  1557. }
  1558. // TODO?
  1559. template <>
  1560. IndexBlockIter* BlockBasedTable::InitBlockIterator<IndexBlockIter>(
  1561. const Rep* rep, Block* block, BlockType block_type,
  1562. IndexBlockIter* input_iter, bool block_contents_pinned) {
  1563. return block->NewIndexIterator(
  1564. rep->internal_comparator.user_comparator(),
  1565. rep->get_global_seqno(block_type), input_iter, rep->ioptions.stats,
  1566. /* total_order_seek */ true, rep->index_has_first_key,
  1567. rep->index_key_includes_seq, rep->index_value_is_full,
  1568. block_contents_pinned, rep->user_defined_timestamps_persisted);
  1569. }
  1570. // Right now only called for Data blocks.
  1571. template <typename TBlocklike>
  1572. Status BlockBasedTable::LookupAndPinBlocksInCache(
  1573. const ReadOptions& ro, const BlockHandle& handle,
  1574. CachableEntry<TBlocklike>* out_parsed_block) const {
  1575. BlockCacheInterface<TBlocklike> block_cache{
  1576. rep_->table_options.block_cache.get()};
  1577. assert(block_cache);
  1578. Status s;
  1579. CachableEntry<DecompressorDict> cached_dict;
  1580. if (rep_->uncompression_dict_reader) {
  1581. s = rep_->uncompression_dict_reader->GetOrReadUncompressionDictionary(
  1582. /* prefetch_buffer= */ nullptr, ro,
  1583. /* get_context= */ nullptr, /* lookup_context= */ nullptr,
  1584. &cached_dict);
  1585. if (!s.ok()) {
  1586. return s;
  1587. }
  1588. if (!cached_dict.GetValue()) {
  1589. return Status::Corruption("Success but no dictionary read");
  1590. }
  1591. }
  1592. // Do the lookup.
  1593. CacheKey key_data = GetCacheKey(rep_->base_cache_key, handle);
  1594. const Slice key = key_data.AsSlice();
  1595. Statistics* statistics = rep_->ioptions.statistics.get();
  1596. typename BlockCacheInterface<TBlocklike>::TypedHandle* cache_handle;
  1597. if (cached_dict.GetValue()) {
  1598. // NOTE: inefficient BlockCreateContext copy for dict-aware decompressor
  1599. // (see TODO in block_cache.h)
  1600. BlockCreateContext create_ctx = rep_->create_context;
  1601. create_ctx.decompressor = cached_dict.GetValue()->decompressor_.get();
  1602. cache_handle = block_cache.LookupFull(
  1603. key, &create_ctx, GetCachePriority<TBlocklike>(), statistics,
  1604. rep_->ioptions.lowest_used_cache_tier);
  1605. } else {
  1606. cache_handle = block_cache.LookupFull(
  1607. key, &rep_->create_context, GetCachePriority<TBlocklike>(), statistics,
  1608. rep_->ioptions.lowest_used_cache_tier);
  1609. }
  1610. if (!cache_handle) {
  1611. UpdateCacheMissMetrics(TBlocklike::kBlockType, /* get_context = */ nullptr);
  1612. return s;
  1613. }
  1614. // Found in Cache.
  1615. TBlocklike* value = block_cache.Value(cache_handle);
  1616. if (value) {
  1617. UpdateCacheHitMetrics(TBlocklike::kBlockType, /* get_context = */ nullptr,
  1618. block_cache.get()->GetUsage(cache_handle));
  1619. }
  1620. out_parsed_block->SetCachedValue(value, block_cache.get(), cache_handle);
  1621. assert(!out_parsed_block->IsEmpty());
  1622. return s;
  1623. }
  1624. template <typename TBlocklike>
  1625. Status BlockBasedTable::CreateAndPinBlockInCache(
  1626. const ReadOptions& ro, const BlockHandle& handle,
  1627. UnownedPtr<Decompressor> decomp, BlockContents* contents,
  1628. CachableEntry<TBlocklike>* out_parsed_block) const {
  1629. CompressionType compression_type = GetBlockCompressionType(*contents);
  1630. // If we don't own the contents and we don't need to decompress, copy
  1631. // the block to heap in order to have ownership. If decompression is
  1632. // needed, then the decompressor will allocate a buffer.
  1633. if (!contents->own_bytes() && compression_type == kNoCompression) {
  1634. Slice src = Slice(contents->data.data(), BlockSizeWithTrailer(handle));
  1635. *contents = BlockContents(
  1636. CopyBufferToHeap(GetMemoryAllocator(rep_->table_options), src),
  1637. handle.size());
  1638. #ifndef NDEBUG
  1639. contents->has_trailer = true;
  1640. #endif
  1641. }
  1642. Status s;
  1643. if (ro.fill_cache) {
  1644. s = MaybeReadBlockAndLoadToCache(nullptr, ro, handle, decomp,
  1645. /*for_compaction=*/false, out_parsed_block,
  1646. nullptr, nullptr, contents,
  1647. /*async_read=*/false,
  1648. /*use_block_cache_for_lookup=*/true);
  1649. }
  1650. if (!s.ok()) {
  1651. return s;
  1652. }
  1653. // fill_cache could be false, or no block cache is configured. In that
  1654. // case, decompress if necessary and take ownership of the block
  1655. if (out_parsed_block->GetValue() == nullptr && contents != nullptr) {
  1656. BlockContents tmp_contents;
  1657. if (compression_type != kNoCompression) {
  1658. s = DecompressSerializedBlock(contents->data.data(), handle.size(),
  1659. compression_type, *decomp, &tmp_contents,
  1660. rep_->ioptions,
  1661. GetMemoryAllocator(rep_->table_options));
  1662. } else {
  1663. tmp_contents = std::move(*contents);
  1664. }
  1665. if (s.ok()) {
  1666. std::unique_ptr<TBlocklike> block_holder;
  1667. rep_->create_context.Create(&block_holder, std::move(tmp_contents));
  1668. out_parsed_block->SetOwnedValue(std::move(block_holder));
  1669. }
  1670. }
  1671. return s;
  1672. }
  1673. // If contents is nullptr, this function looks up the block caches for the
  1674. // data block referenced by handle, and read the block from disk if necessary.
  1675. // If contents is non-null, it skips the cache lookup and disk read, since
  1676. // the caller has already read it. In both cases, if ro.fill_cache is true,
  1677. // it inserts the block into the block cache.
  1678. template <typename TBlocklike>
  1679. WithBlocklikeCheck<Status, TBlocklike>
  1680. BlockBasedTable::MaybeReadBlockAndLoadToCache(
  1681. FilePrefetchBuffer* prefetch_buffer, const ReadOptions& ro,
  1682. const BlockHandle& handle, UnownedPtr<Decompressor> decomp,
  1683. bool for_compaction, CachableEntry<TBlocklike>* out_parsed_block,
  1684. GetContext* get_context, BlockCacheLookupContext* lookup_context,
  1685. BlockContents* contents, bool async_read,
  1686. bool use_block_cache_for_lookup) const {
  1687. assert(out_parsed_block != nullptr);
  1688. const bool no_io = (ro.read_tier == kBlockCacheTier);
  1689. BlockCacheInterface<TBlocklike> block_cache{
  1690. rep_->table_options.block_cache.get()};
  1691. // First, try to get the block from the cache
  1692. //
  1693. // If either block cache is enabled, we'll try to read from it.
  1694. Status s;
  1695. CacheKey key_data;
  1696. Slice key;
  1697. bool is_cache_hit = false;
  1698. if (block_cache) {
  1699. // create key for block cache
  1700. key_data = GetCacheKey(rep_->base_cache_key, handle);
  1701. key = key_data.AsSlice();
  1702. if (!contents) {
  1703. if (use_block_cache_for_lookup) {
  1704. s = GetDataBlockFromCache(key, block_cache, out_parsed_block,
  1705. get_context, decomp);
  1706. // Value could still be null at this point, so check the cache handle
  1707. // and update the read pattern for prefetching
  1708. if (out_parsed_block->GetValue() ||
  1709. out_parsed_block->GetCacheHandle()) {
  1710. // TODO(haoyu): Differentiate cache hit on uncompressed block cache
  1711. // and compressed block cache.
  1712. is_cache_hit = true;
  1713. if (prefetch_buffer) {
  1714. // Update the block details so that PrefetchBuffer can use the read
  1715. // pattern to determine if reads are sequential or not for
  1716. // prefetching. It should also take in account blocks read from
  1717. // cache.
  1718. prefetch_buffer->UpdateReadPattern(
  1719. handle.offset(), BlockSizeWithTrailer(handle),
  1720. ro.adaptive_readahead /*decrease_readahead_size*/);
  1721. }
  1722. }
  1723. }
  1724. }
  1725. // Can't find the block from the cache. If I/O is allowed, read from the
  1726. // file.
  1727. if (out_parsed_block->GetValue() == nullptr &&
  1728. out_parsed_block->GetCacheHandle() == nullptr && !no_io &&
  1729. ro.fill_cache) {
  1730. Statistics* statistics = rep_->ioptions.stats;
  1731. const bool maybe_compressed =
  1732. BlockTypeMaybeCompressed(TBlocklike::kBlockType) &&
  1733. rep_->decompressor;
  1734. // This flag, if true, tells BlockFetcher to return the uncompressed
  1735. // block when ReadBlockContents() is called.
  1736. const bool do_uncompress = maybe_compressed;
  1737. CompressionType contents_comp_type;
  1738. // Maybe serialized or uncompressed
  1739. BlockContents tmp_contents;
  1740. BlockContents uncomp_contents;
  1741. BlockContents comp_contents;
  1742. if (!contents) {
  1743. Histograms histogram = for_compaction ? READ_BLOCK_COMPACTION_MICROS
  1744. : READ_BLOCK_GET_MICROS;
  1745. StopWatch sw(rep_->ioptions.clock, statistics, histogram);
  1746. // Setting do_uncompress to false may cause an extra mempcy in the
  1747. // following cases -
  1748. // 1. Compression is enabled, but block is not actually compressed
  1749. // 2. Compressed block is in the prefetch buffer
  1750. // 3. Direct IO
  1751. //
  1752. // It would also cause a memory allocation to be used rather than
  1753. // stack if the compressed block size is < 5KB
  1754. BlockFetcher block_fetcher(
  1755. rep_->file.get(), prefetch_buffer, rep_->footer, ro, handle,
  1756. &tmp_contents, rep_->ioptions, do_uncompress, maybe_compressed,
  1757. TBlocklike::kBlockType, decomp, rep_->persistent_cache_options,
  1758. GetMemoryAllocator(rep_->table_options),
  1759. /*allocator=*/nullptr);
  1760. // If prefetch_buffer is not allocated, it will fallback to synchronous
  1761. // reading of block contents.
  1762. if (async_read && prefetch_buffer != nullptr) {
  1763. s = block_fetcher.ReadAsyncBlockContents();
  1764. if (!s.ok()) {
  1765. return s;
  1766. }
  1767. } else {
  1768. s = block_fetcher.ReadBlockContents();
  1769. }
  1770. contents_comp_type = block_fetcher.compression_type();
  1771. if (get_context) {
  1772. switch (TBlocklike::kBlockType) {
  1773. case BlockType::kIndex:
  1774. ++get_context->get_context_stats_.num_index_read;
  1775. break;
  1776. case BlockType::kFilter:
  1777. case BlockType::kFilterPartitionIndex:
  1778. ++get_context->get_context_stats_.num_filter_read;
  1779. break;
  1780. default:
  1781. break;
  1782. }
  1783. }
  1784. if (s.ok()) {
  1785. if (do_uncompress && contents_comp_type != kNoCompression) {
  1786. comp_contents = BlockContents(block_fetcher.GetCompressedBlock());
  1787. uncomp_contents = std::move(tmp_contents);
  1788. } else if (contents_comp_type != kNoCompression) {
  1789. // do_uncompress must be false, so output of BlockFetcher is
  1790. // compressed
  1791. comp_contents = std::move(tmp_contents);
  1792. } else {
  1793. uncomp_contents = std::move(tmp_contents);
  1794. }
  1795. // If filling cache is allowed and a cache is configured, try to put
  1796. // the block to the cache. Do this here while block_fetcher is in
  1797. // scope, since comp_contents will be a reference to the compressed
  1798. // block in block_fetcher
  1799. s = PutDataBlockToCache(
  1800. key, block_cache, out_parsed_block, std::move(uncomp_contents),
  1801. std::move(comp_contents), contents_comp_type, decomp,
  1802. GetMemoryAllocator(rep_->table_options), get_context);
  1803. }
  1804. } else {
  1805. contents_comp_type = GetBlockCompressionType(*contents);
  1806. if (contents_comp_type != kNoCompression) {
  1807. comp_contents = std::move(*contents);
  1808. } else {
  1809. uncomp_contents = std::move(*contents);
  1810. }
  1811. if (s.ok()) {
  1812. // If filling cache is allowed and a cache is configured, try to put
  1813. // the block to the cache.
  1814. s = PutDataBlockToCache(
  1815. key, block_cache, out_parsed_block, std::move(uncomp_contents),
  1816. std::move(comp_contents), contents_comp_type, decomp,
  1817. GetMemoryAllocator(rep_->table_options), get_context);
  1818. }
  1819. }
  1820. }
  1821. }
  1822. // TODO: optimize so that lookup_context != nullptr implies the others
  1823. if (block_cache_tracer_ && block_cache_tracer_->is_tracing_enabled() &&
  1824. lookup_context) {
  1825. SaveLookupContextOrTraceRecord(
  1826. key, is_cache_hit, ro, out_parsed_block->GetValue(), lookup_context);
  1827. }
  1828. assert(s.ok() || out_parsed_block->GetValue() == nullptr);
  1829. return s;
  1830. }
  1831. template <typename TBlocklike>
  1832. WithBlocklikeCheck<void, TBlocklike>
  1833. BlockBasedTable::SaveLookupContextOrTraceRecord(
  1834. const Slice& block_key, bool is_cache_hit, const ReadOptions& ro,
  1835. const TBlocklike* parsed_block_value,
  1836. BlockCacheLookupContext* lookup_context) const {
  1837. assert(lookup_context);
  1838. size_t usage = 0;
  1839. uint64_t nkeys = 0;
  1840. if (parsed_block_value) {
  1841. // Approximate the number of keys in the block using restarts.
  1842. int interval = rep_->table_options.block_restart_interval;
  1843. nkeys = interval * GetBlockNumRestarts(*parsed_block_value);
  1844. // On average, the last restart should be just over half utilized.
  1845. // Specifically, 1..N should be N/2 + 0.5. For example, 7 -> 4, 8 -> 4.5.
  1846. // Use the get_id to alternate between rounding up vs. down.
  1847. if (nkeys > 0) {
  1848. bool rounding = static_cast<int>(lookup_context->get_id) & 1;
  1849. nkeys -= (interval - rounding) / 2;
  1850. }
  1851. usage = parsed_block_value->ApproximateMemoryUsage();
  1852. }
  1853. TraceType trace_block_type = TraceType::kTraceMax;
  1854. switch (TBlocklike::kBlockType) {
  1855. case BlockType::kData:
  1856. trace_block_type = TraceType::kBlockTraceDataBlock;
  1857. break;
  1858. case BlockType::kFilter:
  1859. case BlockType::kFilterPartitionIndex:
  1860. trace_block_type = TraceType::kBlockTraceFilterBlock;
  1861. break;
  1862. case BlockType::kCompressionDictionary:
  1863. trace_block_type = TraceType::kBlockTraceUncompressionDictBlock;
  1864. break;
  1865. case BlockType::kRangeDeletion:
  1866. trace_block_type = TraceType::kBlockTraceRangeDeletionBlock;
  1867. break;
  1868. case BlockType::kIndex:
  1869. case BlockType::kUserDefinedIndex:
  1870. trace_block_type = TraceType::kBlockTraceIndexBlock;
  1871. break;
  1872. default:
  1873. // This cannot happen.
  1874. assert(false);
  1875. break;
  1876. }
  1877. const bool no_io = ro.read_tier == kBlockCacheTier;
  1878. bool no_insert = no_io || !ro.fill_cache;
  1879. if (BlockCacheTraceHelper::IsGetOrMultiGetOnDataBlock(
  1880. trace_block_type, lookup_context->caller)) {
  1881. // Make a copy of the block key here since it will be logged later.
  1882. lookup_context->FillLookupContext(is_cache_hit, no_insert, trace_block_type,
  1883. /*block_size=*/usage,
  1884. block_key.ToString(), nkeys);
  1885. // Defer logging the access to Get() and MultiGet() to trace additional
  1886. // information, e.g., referenced_key
  1887. } else {
  1888. // Avoid making copy of block_key if it doesn't need to be saved in
  1889. // BlockCacheLookupContext
  1890. lookup_context->FillLookupContext(is_cache_hit, no_insert, trace_block_type,
  1891. /*block_size=*/usage,
  1892. /*block_key=*/{}, nkeys);
  1893. // Fill in default values for irrelevant/unknown fields
  1894. FinishTraceRecord(*lookup_context, block_key,
  1895. lookup_context->referenced_key,
  1896. /*does_referenced_key_exist*/ false,
  1897. /*referenced_data_size*/ 0);
  1898. }
  1899. }
  1900. void BlockBasedTable::FinishTraceRecord(
  1901. const BlockCacheLookupContext& lookup_context, const Slice& block_key,
  1902. const Slice& referenced_key, bool does_referenced_key_exist,
  1903. uint64_t referenced_data_size) const {
  1904. // Avoid making copy of referenced_key if it doesn't need to be saved in
  1905. // BlockCacheLookupContext
  1906. BlockCacheTraceRecord access_record(
  1907. rep_->ioptions.clock->NowMicros(),
  1908. /*block_key=*/"", lookup_context.block_type, lookup_context.block_size,
  1909. rep_->cf_id_for_tracing(),
  1910. /*cf_name=*/"", rep_->level_for_tracing(), rep_->sst_number_for_tracing(),
  1911. lookup_context.caller, lookup_context.is_cache_hit,
  1912. lookup_context.no_insert, lookup_context.get_id,
  1913. lookup_context.get_from_user_specified_snapshot,
  1914. /*referenced_key=*/"", referenced_data_size,
  1915. lookup_context.num_keys_in_block, does_referenced_key_exist);
  1916. // TODO: Should handle status here?
  1917. block_cache_tracer_
  1918. ->WriteBlockAccess(access_record, block_key, rep_->cf_name_for_tracing(),
  1919. referenced_key)
  1920. .PermitUncheckedError();
  1921. }
  1922. template <typename TBlocklike /*, auto*/>
  1923. WithBlocklikeCheck<Status, TBlocklike> BlockBasedTable::RetrieveBlock(
  1924. FilePrefetchBuffer* prefetch_buffer, const ReadOptions& ro,
  1925. const BlockHandle& handle, UnownedPtr<Decompressor> decomp,
  1926. CachableEntry<TBlocklike>* out_parsed_block, GetContext* get_context,
  1927. BlockCacheLookupContext* lookup_context, bool for_compaction,
  1928. bool use_cache, bool async_read, bool use_block_cache_for_lookup) const {
  1929. assert(out_parsed_block);
  1930. assert(out_parsed_block->IsEmpty());
  1931. Status s;
  1932. if (use_cache) {
  1933. s = MaybeReadBlockAndLoadToCache(
  1934. prefetch_buffer, ro, handle, decomp, for_compaction, out_parsed_block,
  1935. get_context, lookup_context,
  1936. /*contents=*/nullptr, async_read, use_block_cache_for_lookup);
  1937. if (!s.ok()) {
  1938. return s;
  1939. }
  1940. if (out_parsed_block->GetValue() != nullptr ||
  1941. out_parsed_block->GetCacheHandle() != nullptr) {
  1942. assert(s.ok());
  1943. return s;
  1944. }
  1945. }
  1946. assert(out_parsed_block->IsEmpty());
  1947. const bool no_io = ro.read_tier == kBlockCacheTier;
  1948. if (no_io) {
  1949. return Status::Incomplete("no blocking io");
  1950. }
  1951. const bool maybe_compressed =
  1952. BlockTypeMaybeCompressed(TBlocklike::kBlockType) && rep_->decompressor;
  1953. std::unique_ptr<TBlocklike> block;
  1954. {
  1955. Histograms histogram =
  1956. for_compaction ? READ_BLOCK_COMPACTION_MICROS : READ_BLOCK_GET_MICROS;
  1957. StopWatch sw(rep_->ioptions.clock, rep_->ioptions.stats, histogram);
  1958. s = ReadAndParseBlockFromFile(
  1959. rep_->file.get(), prefetch_buffer, rep_->footer, ro, handle, &block,
  1960. rep_->ioptions, rep_->create_context, maybe_compressed, decomp,
  1961. rep_->persistent_cache_options, GetMemoryAllocator(rep_->table_options),
  1962. for_compaction, async_read);
  1963. if (get_context) {
  1964. switch (TBlocklike::kBlockType) {
  1965. case BlockType::kIndex:
  1966. ++(get_context->get_context_stats_.num_index_read);
  1967. break;
  1968. case BlockType::kFilter:
  1969. case BlockType::kFilterPartitionIndex:
  1970. ++(get_context->get_context_stats_.num_filter_read);
  1971. break;
  1972. default:
  1973. break;
  1974. }
  1975. }
  1976. }
  1977. if (!s.ok()) {
  1978. return s;
  1979. }
  1980. out_parsed_block->SetOwnedValue(std::move(block));
  1981. assert(s.ok());
  1982. return s;
  1983. }
  1984. BlockBasedTable::PartitionedIndexIteratorState::PartitionedIndexIteratorState(
  1985. const BlockBasedTable* table,
  1986. UnorderedMap<uint64_t, CachableEntry<Block>>* block_map)
  1987. : table_(table), block_map_(block_map) {}
  1988. InternalIteratorBase<IndexValue>*
  1989. BlockBasedTable::PartitionedIndexIteratorState::NewSecondaryIterator(
  1990. const BlockHandle& handle) {
  1991. // Return a block iterator on the index partition
  1992. auto block = block_map_->find(handle.offset());
  1993. // block_map_ must be exhaustive
  1994. if (block == block_map_->end()) {
  1995. assert(false);
  1996. // Signal problem to caller
  1997. return nullptr;
  1998. }
  1999. const Rep* rep = table_->get_rep();
  2000. assert(rep);
  2001. Statistics* kNullStats = nullptr;
  2002. // We don't return pinned data from index blocks, so no need
  2003. // to set `block_contents_pinned`.
  2004. return block->second.GetValue()->NewIndexIterator(
  2005. rep->internal_comparator.user_comparator(),
  2006. rep->get_global_seqno(BlockType::kIndex), nullptr, kNullStats, true,
  2007. rep->index_has_first_key, rep->index_key_includes_seq,
  2008. rep->index_value_is_full, /*block_contents_pinned=*/false,
  2009. rep->user_defined_timestamps_persisted);
  2010. }
  2011. // This will be broken if the user specifies an unusual implementation
  2012. // of Options.comparator, or if the user specifies an unusual
  2013. // definition of prefixes in BlockBasedTableOptions.filter_policy.
  2014. // In particular, we require the following three properties:
  2015. //
  2016. // 1) key.starts_with(prefix(key))
  2017. // 2) Compare(prefix(key), key) <= 0.
  2018. // 3) If Compare(key1, key2) <= 0, then Compare(prefix(key1), prefix(key2)) <= 0
  2019. //
  2020. // If read_options.read_tier == kBlockCacheTier, this method will do no I/O and
  2021. // will return true if the filter block is not in memory and not found in block
  2022. // cache.
  2023. //
  2024. // REQUIRES: this method shouldn't be called while the DB lock is held.
  2025. bool BlockBasedTable::PrefixRangeMayMatch(
  2026. const Slice& internal_key, const ReadOptions& read_options,
  2027. const SliceTransform* options_prefix_extractor,
  2028. const bool need_upper_bound_check, BlockCacheLookupContext* lookup_context,
  2029. bool* filter_checked) const {
  2030. if (!rep_->filter_policy) {
  2031. return true;
  2032. }
  2033. const SliceTransform* prefix_extractor;
  2034. if (rep_->table_prefix_extractor == nullptr) {
  2035. if (need_upper_bound_check) {
  2036. return true;
  2037. }
  2038. prefix_extractor = options_prefix_extractor;
  2039. } else {
  2040. prefix_extractor = rep_->table_prefix_extractor.get();
  2041. }
  2042. auto ts_sz = rep_->internal_comparator.user_comparator()->timestamp_size();
  2043. auto user_key_without_ts =
  2044. ExtractUserKeyAndStripTimestamp(internal_key, ts_sz);
  2045. if (!prefix_extractor->InDomain(user_key_without_ts)) {
  2046. return true;
  2047. }
  2048. bool may_match = true;
  2049. FilterBlockReader* const filter = rep_->filter.get();
  2050. *filter_checked = false;
  2051. if (filter != nullptr) {
  2052. const Slice* const const_ikey_ptr = &internal_key;
  2053. may_match = filter->RangeMayExist(
  2054. read_options.iterate_upper_bound, user_key_without_ts, prefix_extractor,
  2055. rep_->internal_comparator.user_comparator(), const_ikey_ptr,
  2056. filter_checked, need_upper_bound_check, lookup_context, read_options);
  2057. }
  2058. return may_match;
  2059. }
  2060. bool BlockBasedTable::PrefixExtractorChanged(
  2061. const SliceTransform* prefix_extractor) const {
  2062. if (prefix_extractor == nullptr) {
  2063. return true;
  2064. } else if (prefix_extractor == rep_->table_prefix_extractor.get()) {
  2065. return false;
  2066. } else {
  2067. return PrefixExtractorChangedHelper(rep_->table_properties.get(),
  2068. prefix_extractor);
  2069. }
  2070. }
  2071. Statistics* BlockBasedTable::GetStatistics() const {
  2072. return rep_->ioptions.stats;
  2073. }
  2074. bool BlockBasedTable::IsLastLevel() const {
  2075. return rep_->level == rep_->ioptions.num_levels - 1;
  2076. }
  2077. InternalIterator* BlockBasedTable::NewIterator(
  2078. const ReadOptions& read_options, const SliceTransform* prefix_extractor,
  2079. Arena* arena, bool skip_filters, TableReaderCaller caller,
  2080. size_t compaction_readahead_size, bool allow_unprepared_value) {
  2081. BlockCacheLookupContext lookup_context{caller};
  2082. bool need_upper_bound_check =
  2083. read_options.auto_prefix_mode || PrefixExtractorChanged(prefix_extractor);
  2084. std::unique_ptr<InternalIteratorBase<IndexValue>> index_iter(NewIndexIterator(
  2085. read_options,
  2086. /*disable_prefix_seek=*/need_upper_bound_check &&
  2087. rep_->index_type == BlockBasedTableOptions::kHashSearch,
  2088. /*input_iter=*/nullptr, /*get_context=*/nullptr, &lookup_context));
  2089. if (arena == nullptr) {
  2090. return new BlockBasedTableIterator(
  2091. this, read_options, rep_->internal_comparator, std::move(index_iter),
  2092. !skip_filters &&
  2093. (!read_options.total_order_seek || read_options.auto_prefix_mode ||
  2094. read_options.prefix_same_as_start) &&
  2095. prefix_extractor != nullptr,
  2096. need_upper_bound_check, prefix_extractor, caller,
  2097. compaction_readahead_size, allow_unprepared_value);
  2098. } else {
  2099. auto* mem = arena->AllocateAligned(sizeof(BlockBasedTableIterator));
  2100. return new (mem) BlockBasedTableIterator(
  2101. this, read_options, rep_->internal_comparator, std::move(index_iter),
  2102. !skip_filters &&
  2103. (!read_options.total_order_seek || read_options.auto_prefix_mode ||
  2104. read_options.prefix_same_as_start) &&
  2105. prefix_extractor != nullptr,
  2106. need_upper_bound_check, prefix_extractor, caller,
  2107. compaction_readahead_size, allow_unprepared_value);
  2108. }
  2109. }
  2110. FragmentedRangeTombstoneIterator* BlockBasedTable::NewRangeTombstoneIterator(
  2111. const ReadOptions& read_options) {
  2112. if (rep_->fragmented_range_dels == nullptr) {
  2113. return nullptr;
  2114. }
  2115. SequenceNumber snapshot = kMaxSequenceNumber;
  2116. if (read_options.snapshot != nullptr) {
  2117. snapshot = read_options.snapshot->GetSequenceNumber();
  2118. }
  2119. return new FragmentedRangeTombstoneIterator(rep_->fragmented_range_dels,
  2120. rep_->internal_comparator,
  2121. snapshot, read_options.timestamp);
  2122. }
  2123. FragmentedRangeTombstoneIterator* BlockBasedTable::NewRangeTombstoneIterator(
  2124. SequenceNumber read_seqno, const Slice* timestamp) {
  2125. if (rep_->fragmented_range_dels == nullptr) {
  2126. return nullptr;
  2127. }
  2128. return new FragmentedRangeTombstoneIterator(rep_->fragmented_range_dels,
  2129. rep_->internal_comparator,
  2130. read_seqno, timestamp);
  2131. }
  2132. bool BlockBasedTable::FullFilterKeyMayMatch(
  2133. FilterBlockReader* filter, const Slice& internal_key,
  2134. const SliceTransform* prefix_extractor, GetContext* get_context,
  2135. BlockCacheLookupContext* lookup_context,
  2136. const ReadOptions& read_options) const {
  2137. if (filter == nullptr) {
  2138. return true;
  2139. }
  2140. Slice user_key = ExtractUserKey(internal_key);
  2141. const Slice* const const_ikey_ptr = &internal_key;
  2142. bool may_match = true;
  2143. size_t ts_sz = rep_->internal_comparator.user_comparator()->timestamp_size();
  2144. Slice user_key_without_ts = StripTimestampFromUserKey(user_key, ts_sz);
  2145. if (rep_->whole_key_filtering) {
  2146. may_match = filter->KeyMayMatch(user_key_without_ts, const_ikey_ptr,
  2147. get_context, lookup_context, read_options);
  2148. if (may_match) {
  2149. RecordTick(rep_->ioptions.stats, BLOOM_FILTER_FULL_POSITIVE);
  2150. PERF_COUNTER_BY_LEVEL_ADD(bloom_filter_full_positive, 1, rep_->level);
  2151. } else {
  2152. RecordTick(rep_->ioptions.stats, BLOOM_FILTER_USEFUL);
  2153. PERF_COUNTER_BY_LEVEL_ADD(bloom_filter_useful, 1, rep_->level);
  2154. }
  2155. } else if (!PrefixExtractorChanged(prefix_extractor) &&
  2156. prefix_extractor->InDomain(user_key_without_ts)) {
  2157. // FIXME ^^^: there should be no reason for Get() to depend on current
  2158. // prefix_extractor at all. It should always use table_prefix_extractor.
  2159. may_match = filter->PrefixMayMatch(
  2160. prefix_extractor->Transform(user_key_without_ts), const_ikey_ptr,
  2161. get_context, lookup_context, read_options);
  2162. RecordTick(rep_->ioptions.stats, BLOOM_FILTER_PREFIX_CHECKED);
  2163. if (may_match) {
  2164. // Includes prefix stats
  2165. PERF_COUNTER_BY_LEVEL_ADD(bloom_filter_full_positive, 1, rep_->level);
  2166. } else {
  2167. RecordTick(rep_->ioptions.stats, BLOOM_FILTER_PREFIX_USEFUL);
  2168. // Includes prefix stats
  2169. PERF_COUNTER_BY_LEVEL_ADD(bloom_filter_useful, 1, rep_->level);
  2170. }
  2171. }
  2172. return may_match;
  2173. }
  2174. void BlockBasedTable::FullFilterKeysMayMatch(
  2175. FilterBlockReader* filter, MultiGetRange* range,
  2176. const SliceTransform* prefix_extractor,
  2177. BlockCacheLookupContext* lookup_context,
  2178. const ReadOptions& read_options) const {
  2179. if (filter == nullptr) {
  2180. return;
  2181. }
  2182. uint64_t before_keys = range->KeysLeft();
  2183. assert(before_keys > 0); // Caller should ensure
  2184. if (rep_->whole_key_filtering) {
  2185. filter->KeysMayMatch(range, lookup_context, read_options);
  2186. uint64_t after_keys = range->KeysLeft();
  2187. if (after_keys) {
  2188. RecordTick(rep_->ioptions.stats, BLOOM_FILTER_FULL_POSITIVE, after_keys);
  2189. PERF_COUNTER_BY_LEVEL_ADD(bloom_filter_full_positive, after_keys,
  2190. rep_->level);
  2191. }
  2192. uint64_t filtered_keys = before_keys - after_keys;
  2193. if (filtered_keys) {
  2194. RecordTick(rep_->ioptions.stats, BLOOM_FILTER_USEFUL, filtered_keys);
  2195. PERF_COUNTER_BY_LEVEL_ADD(bloom_filter_useful, filtered_keys,
  2196. rep_->level);
  2197. }
  2198. } else if (!PrefixExtractorChanged(prefix_extractor)) {
  2199. // FIXME ^^^: there should be no reason for MultiGet() to depend on current
  2200. // prefix_extractor at all. It should always use table_prefix_extractor.
  2201. filter->PrefixesMayMatch(range, prefix_extractor, lookup_context,
  2202. read_options);
  2203. RecordTick(rep_->ioptions.stats, BLOOM_FILTER_PREFIX_CHECKED, before_keys);
  2204. uint64_t after_keys = range->KeysLeft();
  2205. if (after_keys) {
  2206. // Includes prefix stats
  2207. PERF_COUNTER_BY_LEVEL_ADD(bloom_filter_full_positive, after_keys,
  2208. rep_->level);
  2209. }
  2210. uint64_t filtered_keys = before_keys - after_keys;
  2211. if (filtered_keys) {
  2212. RecordTick(rep_->ioptions.stats, BLOOM_FILTER_PREFIX_USEFUL,
  2213. filtered_keys);
  2214. // Includes prefix stats
  2215. PERF_COUNTER_BY_LEVEL_ADD(bloom_filter_useful, filtered_keys,
  2216. rep_->level);
  2217. }
  2218. }
  2219. }
  2220. Status BlockBasedTable::ApproximateKeyAnchors(const ReadOptions& read_options,
  2221. std::vector<Anchor>& anchors) {
  2222. // We iterator the whole index block here. More efficient implementation
  2223. // is possible if we push this operation into IndexReader. For example, we
  2224. // can directly sample from restart block entries in the index block and
  2225. // only read keys needed. Here we take a simple solution. Performance is
  2226. // likely not to be a problem. We are compacting the whole file, so all
  2227. // keys will be read out anyway. An extra read to index block might be
  2228. // a small share of the overhead. We can try to optimize if needed.
  2229. //
  2230. // `CacheDependencies()` brings all the blocks into cache using one I/O. That
  2231. // way the full index scan usually finds the index data it is looking for in
  2232. // cache rather than doing an I/O for each "dependency" (partition).
  2233. Status s = rep_->index_reader->CacheDependencies(
  2234. read_options, false /* pin */, nullptr /* prefetch_buffer */);
  2235. if (!s.ok()) {
  2236. return s;
  2237. }
  2238. IndexBlockIter iiter_on_stack;
  2239. auto iiter = NewIndexIterator(
  2240. read_options, /*disable_prefix_seek=*/false, &iiter_on_stack,
  2241. /*get_context=*/nullptr, /*lookup_context=*/nullptr);
  2242. std::unique_ptr<InternalIteratorBase<IndexValue>> iiter_unique_ptr;
  2243. if (iiter != &iiter_on_stack) {
  2244. iiter_unique_ptr.reset(iiter);
  2245. }
  2246. // If needed the threshold could be more adaptive. For example, it can be
  2247. // based on size, so that a larger will be sampled to more partitions than a
  2248. // smaller file. The size might also need to be passed in by the caller based
  2249. // on total compaction size.
  2250. const uint64_t kMaxNumAnchors = uint64_t{128};
  2251. uint64_t num_blocks = this->GetTableProperties()->num_data_blocks;
  2252. uint64_t num_blocks_per_anchor = num_blocks / kMaxNumAnchors;
  2253. if (num_blocks_per_anchor == 0) {
  2254. num_blocks_per_anchor = 1;
  2255. }
  2256. uint64_t count = 0;
  2257. std::string last_key;
  2258. uint64_t range_size = 0;
  2259. uint64_t prev_offset = 0;
  2260. for (iiter->SeekToFirst(); iiter->Valid(); iiter->Next()) {
  2261. const BlockHandle& bh = iiter->value().handle;
  2262. range_size += bh.offset() + bh.size() - prev_offset;
  2263. prev_offset = bh.offset() + bh.size();
  2264. if (++count % num_blocks_per_anchor == 0) {
  2265. count = 0;
  2266. anchors.emplace_back(iiter->user_key(), range_size);
  2267. range_size = 0;
  2268. } else {
  2269. last_key = iiter->user_key().ToString();
  2270. }
  2271. }
  2272. if (count != 0) {
  2273. anchors.emplace_back(last_key, range_size);
  2274. }
  2275. return Status::OK();
  2276. }
  2277. bool BlockBasedTable::TimestampMayMatch(const ReadOptions& read_options) const {
  2278. if (read_options.timestamp != nullptr && !rep_->min_timestamp.empty()) {
  2279. RecordTick(rep_->ioptions.stats, TIMESTAMP_FILTER_TABLE_CHECKED);
  2280. auto read_ts = read_options.timestamp;
  2281. auto comparator = rep_->internal_comparator.user_comparator();
  2282. if (comparator->CompareTimestamp(*read_ts, rep_->min_timestamp) < 0) {
  2283. RecordTick(rep_->ioptions.stats, TIMESTAMP_FILTER_TABLE_FILTERED);
  2284. return false;
  2285. }
  2286. }
  2287. return true;
  2288. }
  2289. Status BlockBasedTable::Get(const ReadOptions& read_options, const Slice& key,
  2290. GetContext* get_context,
  2291. const SliceTransform* prefix_extractor,
  2292. bool skip_filters) {
  2293. // Similar to Bloom filter !may_match
  2294. // If timestamp is beyond the range of the table, skip
  2295. if (!TimestampMayMatch(read_options)) {
  2296. return Status::OK();
  2297. }
  2298. assert(key.size() >= 8); // key must be internal key
  2299. assert(get_context != nullptr);
  2300. Status s;
  2301. FilterBlockReader* const filter =
  2302. !skip_filters ? rep_->filter.get() : nullptr;
  2303. // First check the full filter
  2304. // If full filter not useful, Then go into each block
  2305. uint64_t tracing_get_id = get_context->get_tracing_get_id();
  2306. BlockCacheLookupContext lookup_context{
  2307. TableReaderCaller::kUserGet, tracing_get_id,
  2308. /*get_from_user_specified_snapshot=*/read_options.snapshot != nullptr};
  2309. if (block_cache_tracer_ && block_cache_tracer_->is_tracing_enabled()) {
  2310. // Trace the key since it contains both user key and sequence number.
  2311. lookup_context.referenced_key = key.ToString();
  2312. lookup_context.get_from_user_specified_snapshot =
  2313. read_options.snapshot != nullptr;
  2314. }
  2315. TEST_SYNC_POINT("BlockBasedTable::Get:BeforeFilterMatch");
  2316. const bool may_match =
  2317. FullFilterKeyMayMatch(filter, key, prefix_extractor, get_context,
  2318. &lookup_context, read_options);
  2319. TEST_SYNC_POINT("BlockBasedTable::Get:AfterFilterMatch");
  2320. if (may_match) {
  2321. IndexBlockIter iiter_on_stack;
  2322. // if prefix_extractor found in block differs from options, disable
  2323. // BlockPrefixIndex. Only do this check when index_type is kHashSearch.
  2324. bool need_upper_bound_check = false;
  2325. if (rep_->index_type == BlockBasedTableOptions::kHashSearch) {
  2326. need_upper_bound_check = PrefixExtractorChanged(prefix_extractor);
  2327. }
  2328. auto iiter =
  2329. NewIndexIterator(read_options, need_upper_bound_check, &iiter_on_stack,
  2330. get_context, &lookup_context);
  2331. std::unique_ptr<InternalIteratorBase<IndexValue>> iiter_unique_ptr;
  2332. if (iiter != &iiter_on_stack) {
  2333. iiter_unique_ptr.reset(iiter);
  2334. }
  2335. size_t ts_sz =
  2336. rep_->internal_comparator.user_comparator()->timestamp_size();
  2337. bool matched = false; // if such user key matched a key in SST
  2338. bool done = false;
  2339. for (iiter->Seek(key); iiter->Valid() && !done; iiter->Next()) {
  2340. IndexValue v = iiter->value();
  2341. if (!v.first_internal_key.empty() && !skip_filters &&
  2342. UserComparatorWrapper(rep_->internal_comparator.user_comparator())
  2343. .CompareWithoutTimestamp(
  2344. ExtractUserKey(key),
  2345. ExtractUserKey(v.first_internal_key)) < 0) {
  2346. // The requested key falls between highest key in previous block and
  2347. // lowest key in current block.
  2348. break;
  2349. }
  2350. BlockCacheLookupContext lookup_data_block_context{
  2351. TableReaderCaller::kUserGet, tracing_get_id,
  2352. /*get_from_user_specified_snapshot=*/read_options.snapshot !=
  2353. nullptr};
  2354. bool does_referenced_key_exist = false;
  2355. DataBlockIter biter;
  2356. uint64_t referenced_data_size = 0;
  2357. Status tmp_status;
  2358. NewDataBlockIterator<DataBlockIter>(
  2359. read_options, v.handle, &biter, BlockType::kData, get_context,
  2360. &lookup_data_block_context, /*prefetch_buffer=*/nullptr,
  2361. /*for_compaction=*/false, /*async_read=*/false, tmp_status,
  2362. /*use_block_cache_for_lookup=*/true);
  2363. if (read_options.read_tier == kBlockCacheTier &&
  2364. biter.status().IsIncomplete()) {
  2365. // couldn't get block from block_cache
  2366. // Update Saver.state to Found because we are only looking for
  2367. // whether we can guarantee the key is not there when "no_io" is set
  2368. get_context->MarkKeyMayExist();
  2369. s = biter.status();
  2370. break;
  2371. }
  2372. if (!biter.status().ok()) {
  2373. s = biter.status();
  2374. break;
  2375. }
  2376. bool may_exist = biter.SeekForGet(key);
  2377. // If user-specified timestamp is supported, we cannot end the search
  2378. // just because hash index lookup indicates the key+ts does not exist.
  2379. if (!may_exist && ts_sz == 0) {
  2380. // HashSeek cannot find the key this block and the the iter is not
  2381. // the end of the block, i.e. cannot be in the following blocks
  2382. // either. In this case, the seek_key cannot be found, so we break
  2383. // from the top level for-loop.
  2384. done = true;
  2385. } else {
  2386. // Call the *saver function on each entry/block until it returns false
  2387. for (; biter.Valid(); biter.Next()) {
  2388. ParsedInternalKey parsed_key;
  2389. Status pik_status = ParseInternalKey(
  2390. biter.key(), &parsed_key, false /* log_err_key */); // TODO
  2391. if (!pik_status.ok()) {
  2392. s = pik_status;
  2393. break;
  2394. }
  2395. Status read_status;
  2396. bool ret = get_context->SaveValue(
  2397. parsed_key, biter.value(), &matched, &read_status,
  2398. biter.IsValuePinned() ? &biter : nullptr);
  2399. if (!read_status.ok()) {
  2400. s = read_status;
  2401. break;
  2402. }
  2403. if (!ret) {
  2404. if (get_context->State() == GetContext::GetState::kFound) {
  2405. does_referenced_key_exist = true;
  2406. referenced_data_size = biter.key().size() + biter.value().size();
  2407. }
  2408. done = true;
  2409. break;
  2410. }
  2411. }
  2412. if (s.ok()) {
  2413. s = biter.status();
  2414. }
  2415. if (!s.ok()) {
  2416. break;
  2417. }
  2418. }
  2419. // Write the block cache access record.
  2420. if (block_cache_tracer_ && block_cache_tracer_->is_tracing_enabled()) {
  2421. // Avoid making copy of block_key, cf_name, and referenced_key when
  2422. // constructing the access record.
  2423. Slice referenced_key;
  2424. if (does_referenced_key_exist) {
  2425. referenced_key = biter.key();
  2426. } else {
  2427. referenced_key = key;
  2428. }
  2429. FinishTraceRecord(lookup_data_block_context,
  2430. lookup_data_block_context.block_key, referenced_key,
  2431. does_referenced_key_exist, referenced_data_size);
  2432. }
  2433. if (done) {
  2434. // Avoid the extra Next which is expensive in two-level indexes
  2435. break;
  2436. }
  2437. }
  2438. if (matched && filter != nullptr) {
  2439. if (rep_->whole_key_filtering) {
  2440. RecordTick(rep_->ioptions.stats, BLOOM_FILTER_FULL_TRUE_POSITIVE);
  2441. } else {
  2442. RecordTick(rep_->ioptions.stats, BLOOM_FILTER_PREFIX_TRUE_POSITIVE);
  2443. }
  2444. // Includes prefix stats
  2445. PERF_COUNTER_BY_LEVEL_ADD(bloom_filter_full_true_positive, 1,
  2446. rep_->level);
  2447. }
  2448. if (s.ok() && !iiter->status().IsNotFound()) {
  2449. s = iiter->status();
  2450. }
  2451. }
  2452. return s;
  2453. }
  2454. Status BlockBasedTable::MultiGetFilter(const ReadOptions& read_options,
  2455. const SliceTransform* prefix_extractor,
  2456. MultiGetRange* mget_range) {
  2457. if (mget_range->empty()) {
  2458. // Caller should ensure non-empty (performance bug)
  2459. assert(false);
  2460. return Status::OK(); // Nothing to do
  2461. }
  2462. FilterBlockReader* const filter = rep_->filter.get();
  2463. if (!filter) {
  2464. return Status::OK();
  2465. }
  2466. // First check the full filter
  2467. // If full filter not useful, Then go into each block
  2468. uint64_t tracing_mget_id = BlockCacheTraceHelper::kReservedGetId;
  2469. if (mget_range->begin()->get_context) {
  2470. tracing_mget_id = mget_range->begin()->get_context->get_tracing_get_id();
  2471. }
  2472. BlockCacheLookupContext lookup_context{
  2473. TableReaderCaller::kUserMultiGet, tracing_mget_id,
  2474. /*_get_from_user_specified_snapshot=*/read_options.snapshot != nullptr};
  2475. FullFilterKeysMayMatch(filter, mget_range, prefix_extractor, &lookup_context,
  2476. read_options);
  2477. return Status::OK();
  2478. }
  2479. Status BlockBasedTable::Prefetch(const ReadOptions& read_options,
  2480. const Slice* const begin,
  2481. const Slice* const end) {
  2482. auto& comparator = rep_->internal_comparator;
  2483. UserComparatorWrapper user_comparator(comparator.user_comparator());
  2484. // pre-condition
  2485. if (begin && end && comparator.Compare(*begin, *end) > 0) {
  2486. return Status::InvalidArgument(*begin, *end);
  2487. }
  2488. BlockCacheLookupContext lookup_context{TableReaderCaller::kPrefetch};
  2489. IndexBlockIter iiter_on_stack;
  2490. auto iiter = NewIndexIterator(read_options, /*need_upper_bound_check=*/false,
  2491. &iiter_on_stack, /*get_context=*/nullptr,
  2492. &lookup_context);
  2493. std::unique_ptr<InternalIteratorBase<IndexValue>> iiter_unique_ptr;
  2494. if (iiter != &iiter_on_stack) {
  2495. iiter_unique_ptr = std::unique_ptr<InternalIteratorBase<IndexValue>>(iiter);
  2496. }
  2497. if (!iiter->status().ok()) {
  2498. // error opening index iterator
  2499. return iiter->status();
  2500. }
  2501. // indicates if we are on the last page that need to be pre-fetched
  2502. bool prefetching_boundary_page = false;
  2503. for (begin ? iiter->Seek(*begin) : iiter->SeekToFirst(); iiter->Valid();
  2504. iiter->Next()) {
  2505. BlockHandle block_handle = iiter->value().handle;
  2506. const bool is_user_key = !rep_->index_key_includes_seq;
  2507. if (end &&
  2508. ((!is_user_key && comparator.Compare(iiter->key(), *end) >= 0) ||
  2509. (is_user_key &&
  2510. user_comparator.Compare(iiter->key(), ExtractUserKey(*end)) >= 0))) {
  2511. if (prefetching_boundary_page) {
  2512. break;
  2513. }
  2514. // The index entry represents the last key in the data block.
  2515. // We should load this page into memory as well, but no more
  2516. prefetching_boundary_page = true;
  2517. }
  2518. // Load the block specified by the block_handle into the block cache
  2519. DataBlockIter biter;
  2520. Status tmp_status;
  2521. NewDataBlockIterator<DataBlockIter>(
  2522. read_options, block_handle, &biter, /*type=*/BlockType::kData,
  2523. /*get_context=*/nullptr, &lookup_context,
  2524. /*prefetch_buffer=*/nullptr, /*for_compaction=*/false,
  2525. /*async_read=*/false, tmp_status, /*use_block_cache_for_lookup=*/true);
  2526. if (!biter.status().ok()) {
  2527. // there was an unexpected error while pre-fetching
  2528. return biter.status();
  2529. }
  2530. }
  2531. return Status::OK();
  2532. }
  2533. Status BlockBasedTable::VerifyChecksum(const ReadOptions& read_options,
  2534. TableReaderCaller caller) {
  2535. Status s;
  2536. // Check Meta blocks
  2537. std::unique_ptr<Block> metaindex;
  2538. std::unique_ptr<InternalIterator> metaindex_iter;
  2539. s = ReadMetaIndexBlock(read_options, nullptr /* prefetch buffer */,
  2540. &metaindex, &metaindex_iter);
  2541. if (s.ok()) {
  2542. s = VerifyChecksumInMetaBlocks(read_options, metaindex_iter.get());
  2543. if (!s.ok()) {
  2544. return s;
  2545. }
  2546. } else {
  2547. return s;
  2548. }
  2549. // Check Data blocks
  2550. IndexBlockIter iiter_on_stack;
  2551. BlockCacheLookupContext context{caller};
  2552. InternalIteratorBase<IndexValue>* iiter = NewIndexIterator(
  2553. read_options, /*disable_prefix_seek=*/false, &iiter_on_stack,
  2554. /*get_context=*/nullptr, &context);
  2555. std::unique_ptr<InternalIteratorBase<IndexValue>> iiter_unique_ptr;
  2556. if (iiter != &iiter_on_stack) {
  2557. iiter_unique_ptr = std::unique_ptr<InternalIteratorBase<IndexValue>>(iiter);
  2558. }
  2559. if (!iiter->status().ok()) {
  2560. // error opening index iterator
  2561. return iiter->status();
  2562. }
  2563. s = VerifyChecksumInBlocks(read_options, iiter);
  2564. return s;
  2565. }
  2566. Status BlockBasedTable::VerifyChecksumInBlocks(
  2567. const ReadOptions& read_options,
  2568. InternalIteratorBase<IndexValue>* index_iter) {
  2569. Status s;
  2570. // We are scanning the whole file, so no need to do exponential
  2571. // increasing of the buffer size.
  2572. size_t readahead_size = (read_options.readahead_size != 0)
  2573. ? read_options.readahead_size
  2574. : rep_->table_options.max_auto_readahead_size;
  2575. // FilePrefetchBuffer doesn't work in mmap mode and readahead is not
  2576. // needed there.
  2577. ReadaheadParams readahead_params;
  2578. readahead_params.initial_readahead_size = readahead_size;
  2579. readahead_params.max_readahead_size = readahead_size;
  2580. FilePrefetchBuffer prefetch_buffer(
  2581. readahead_params, !rep_->ioptions.allow_mmap_reads /* enable */);
  2582. for (index_iter->SeekToFirst(); index_iter->Valid(); index_iter->Next()) {
  2583. s = index_iter->status();
  2584. if (!s.ok()) {
  2585. break;
  2586. }
  2587. BlockHandle handle = index_iter->value().handle;
  2588. BlockContents contents;
  2589. BlockFetcher block_fetcher(
  2590. rep_->file.get(), &prefetch_buffer, rep_->footer, read_options, handle,
  2591. &contents, rep_->ioptions, false /* decompress */,
  2592. false /*maybe_compressed*/, BlockType::kData, nullptr /*decompressor*/,
  2593. rep_->persistent_cache_options);
  2594. s = block_fetcher.ReadBlockContents();
  2595. if (!s.ok()) {
  2596. break;
  2597. }
  2598. }
  2599. if (s.ok()) {
  2600. // In the case of two level indexes, we would have exited the above loop
  2601. // by checking index_iter->Valid(), but Valid() might have returned false
  2602. // due to an IO error. So check the index_iter status
  2603. s = index_iter->status();
  2604. }
  2605. return s;
  2606. }
  2607. BlockType BlockBasedTable::GetBlockTypeForMetaBlockByName(
  2608. const Slice& meta_block_name) {
  2609. if (meta_block_name.starts_with(kFullFilterBlockPrefix)) {
  2610. return BlockType::kFilter;
  2611. }
  2612. if (meta_block_name.starts_with(kPartitionedFilterBlockPrefix)) {
  2613. return BlockType::kFilterPartitionIndex;
  2614. }
  2615. if (meta_block_name == kPropertiesBlockName) {
  2616. return BlockType::kProperties;
  2617. }
  2618. if (meta_block_name == kCompressionDictBlockName) {
  2619. return BlockType::kCompressionDictionary;
  2620. }
  2621. if (meta_block_name == kRangeDelBlockName) {
  2622. return BlockType::kRangeDeletion;
  2623. }
  2624. if (meta_block_name == kHashIndexPrefixesBlock) {
  2625. return BlockType::kHashIndexPrefixes;
  2626. }
  2627. if (meta_block_name == kHashIndexPrefixesMetadataBlock) {
  2628. return BlockType::kHashIndexMetadata;
  2629. }
  2630. if (meta_block_name == kIndexBlockName) {
  2631. return BlockType::kIndex;
  2632. }
  2633. if (meta_block_name.starts_with(kUserDefinedIndexPrefix)) {
  2634. return BlockType::kUserDefinedIndex;
  2635. }
  2636. if (meta_block_name.starts_with(kObsoleteFilterBlockPrefix)) {
  2637. // Obsolete but possible in old files
  2638. return BlockType::kInvalid;
  2639. }
  2640. assert(false);
  2641. return BlockType::kInvalid;
  2642. }
  2643. Status BlockBasedTable::VerifyChecksumInMetaBlocks(
  2644. const ReadOptions& read_options, InternalIteratorBase<Slice>* index_iter) {
  2645. Status s;
  2646. for (index_iter->SeekToFirst(); index_iter->Valid(); index_iter->Next()) {
  2647. s = index_iter->status();
  2648. if (!s.ok()) {
  2649. break;
  2650. }
  2651. BlockHandle handle;
  2652. Slice input = index_iter->value();
  2653. s = handle.DecodeFrom(&input);
  2654. if (!s.ok()) {
  2655. break;
  2656. }
  2657. BlockContents contents;
  2658. const Slice meta_block_name = index_iter->key();
  2659. if (meta_block_name == kPropertiesBlockName) {
  2660. // Unfortunate special handling for properties block checksum w/
  2661. // global seqno
  2662. std::unique_ptr<TableProperties> table_properties;
  2663. s = ReadTablePropertiesHelper(read_options, handle, rep_->file.get(),
  2664. nullptr /* prefetch_buffer */, rep_->footer,
  2665. rep_->ioptions, &table_properties,
  2666. nullptr /* memory_allocator */);
  2667. } else if (rep_->verify_checksum_set_on_open &&
  2668. meta_block_name == kIndexBlockName) {
  2669. // WART: For now, to maintain similar I/O behavior as before
  2670. // format_version=6, we skip verifying index block checksum--but only
  2671. // if it was checked on open.
  2672. } else {
  2673. // FIXME? Need to verify checksums of index and filter partitions?
  2674. s = BlockFetcher(rep_->file.get(), nullptr /* prefetch buffer */,
  2675. rep_->footer, read_options, handle, &contents,
  2676. rep_->ioptions, false /* decompress */,
  2677. false /*maybe_compressed*/,
  2678. GetBlockTypeForMetaBlockByName(meta_block_name),
  2679. nullptr /*decompressor*/, rep_->persistent_cache_options)
  2680. .ReadBlockContents();
  2681. }
  2682. if (!s.ok()) {
  2683. break;
  2684. }
  2685. }
  2686. return s;
  2687. }
  2688. bool BlockBasedTable::EraseFromCache(const BlockHandle& handle) const {
  2689. assert(rep_ != nullptr);
  2690. Cache* const cache = rep_->table_options.block_cache.get();
  2691. if (cache == nullptr) {
  2692. return false;
  2693. }
  2694. CacheKey key = GetCacheKey(rep_->base_cache_key, handle);
  2695. Cache::Handle* const cache_handle = cache->Lookup(key.AsSlice());
  2696. if (cache_handle == nullptr) {
  2697. return false;
  2698. }
  2699. return cache->Release(cache_handle, /*erase_if_last_ref=*/true);
  2700. }
  2701. bool BlockBasedTable::TEST_BlockInCache(const BlockHandle& handle) const {
  2702. assert(rep_ != nullptr);
  2703. Cache* const cache = rep_->table_options.block_cache.get();
  2704. if (cache == nullptr) {
  2705. return false;
  2706. }
  2707. CacheKey key = GetCacheKey(rep_->base_cache_key, handle);
  2708. Cache::Handle* const cache_handle = cache->Lookup(key.AsSlice());
  2709. if (cache_handle == nullptr) {
  2710. return false;
  2711. }
  2712. cache->Release(cache_handle);
  2713. return true;
  2714. }
  2715. bool BlockBasedTable::TEST_KeyInCache(const ReadOptions& options,
  2716. const Slice& key) {
  2717. std::unique_ptr<InternalIteratorBase<IndexValue>> iiter(NewIndexIterator(
  2718. options, /*need_upper_bound_check=*/false, /*input_iter=*/nullptr,
  2719. /*get_context=*/nullptr, /*lookup_context=*/nullptr));
  2720. iiter->Seek(key);
  2721. assert(iiter->status().ok());
  2722. assert(iiter->Valid());
  2723. return TEST_BlockInCache(iiter->value().handle);
  2724. }
  2725. void BlockBasedTable::TEST_GetDataBlockHandle(const ReadOptions& options,
  2726. const Slice& key,
  2727. BlockHandle& handle) {
  2728. std::unique_ptr<InternalIteratorBase<IndexValue>> iiter(NewIndexIterator(
  2729. options, /*disable_prefix_seek=*/false, /*input_iter=*/nullptr,
  2730. /*get_context=*/nullptr, /*lookup_context=*/nullptr));
  2731. iiter->Seek(key);
  2732. assert(iiter->Valid());
  2733. handle = iiter->value().handle;
  2734. }
  2735. // REQUIRES: The following fields of rep_ should have already been populated:
  2736. // 1. file
  2737. // 2. index_handle,
  2738. // 3. options
  2739. // 4. internal_comparator
  2740. // 5. index_type
  2741. Status BlockBasedTable::CreateIndexReader(
  2742. const ReadOptions& ro, FilePrefetchBuffer* prefetch_buffer,
  2743. InternalIterator* meta_iter, bool use_cache, bool prefetch, bool pin,
  2744. BlockCacheLookupContext* lookup_context,
  2745. std::unique_ptr<IndexReader>* index_reader) {
  2746. if (FormatVersionUsesIndexHandleInFooter(rep_->footer.format_version())) {
  2747. rep_->index_handle = rep_->footer.index_handle();
  2748. } else {
  2749. Status s = FindMetaBlock(meta_iter, kIndexBlockName, &rep_->index_handle);
  2750. if (!s.ok()) {
  2751. return s;
  2752. }
  2753. }
  2754. switch (rep_->index_type) {
  2755. case BlockBasedTableOptions::kTwoLevelIndexSearch: {
  2756. return PartitionIndexReader::Create(this, ro, prefetch_buffer, use_cache,
  2757. prefetch, pin, lookup_context,
  2758. index_reader);
  2759. }
  2760. case BlockBasedTableOptions::kBinarySearch:
  2761. FALLTHROUGH_INTENDED;
  2762. case BlockBasedTableOptions::kBinarySearchWithFirstKey: {
  2763. return BinarySearchIndexReader::Create(this, ro, prefetch_buffer,
  2764. use_cache, prefetch, pin,
  2765. lookup_context, index_reader);
  2766. }
  2767. case BlockBasedTableOptions::kHashSearch: {
  2768. if (!rep_->table_prefix_extractor) {
  2769. ROCKS_LOG_WARN(rep_->ioptions.logger,
  2770. "Missing prefix extractor for hash index. Fall back to"
  2771. " binary search index.");
  2772. return BinarySearchIndexReader::Create(this, ro, prefetch_buffer,
  2773. use_cache, prefetch, pin,
  2774. lookup_context, index_reader);
  2775. } else {
  2776. return HashIndexReader::Create(this, ro, prefetch_buffer, meta_iter,
  2777. use_cache, prefetch, pin, lookup_context,
  2778. index_reader);
  2779. }
  2780. }
  2781. default: {
  2782. std::string error_message =
  2783. "Unrecognized index type: " + std::to_string(rep_->index_type);
  2784. return Status::InvalidArgument(error_message.c_str());
  2785. }
  2786. }
  2787. }
  2788. uint64_t BlockBasedTable::ApproximateDataOffsetOf(
  2789. const InternalIteratorBase<IndexValue>& index_iter,
  2790. uint64_t data_size) const {
  2791. assert(index_iter.status().ok());
  2792. if (index_iter.Valid()) {
  2793. BlockHandle handle = index_iter.value().handle;
  2794. return handle.offset();
  2795. } else {
  2796. // The iterator is past the last key in the file.
  2797. return data_size;
  2798. }
  2799. }
  2800. uint64_t BlockBasedTable::GetApproximateDataSize() {
  2801. // Should be in table properties unless super old version
  2802. if (rep_->table_properties) {
  2803. return rep_->table_properties->data_size;
  2804. }
  2805. // Fall back to rough estimate from footer
  2806. return rep_->footer.metaindex_handle().offset();
  2807. }
  2808. uint64_t BlockBasedTable::ApproximateOffsetOf(const ReadOptions& read_options,
  2809. const Slice& key,
  2810. TableReaderCaller caller) {
  2811. uint64_t data_size = GetApproximateDataSize();
  2812. if (UNLIKELY(data_size == 0)) {
  2813. // Hmm. Let's just split in half to avoid skewing one way or another,
  2814. // since we don't know whether we're operating on lower bound or
  2815. // upper bound.
  2816. return rep_->file_size / 2;
  2817. }
  2818. BlockCacheLookupContext context(caller);
  2819. IndexBlockIter iiter_on_stack;
  2820. auto index_iter =
  2821. NewIndexIterator(read_options, /*disable_prefix_seek=*/true,
  2822. /*input_iter=*/&iiter_on_stack, /*get_context=*/nullptr,
  2823. /*lookup_context=*/&context);
  2824. std::unique_ptr<InternalIteratorBase<IndexValue>> iiter_unique_ptr;
  2825. if (index_iter != &iiter_on_stack) {
  2826. iiter_unique_ptr.reset(index_iter);
  2827. }
  2828. index_iter->Seek(key);
  2829. uint64_t offset;
  2830. if (index_iter->status().ok()) {
  2831. offset = ApproximateDataOffsetOf(*index_iter, data_size);
  2832. } else {
  2833. // Split in half to avoid skewing one way or another,
  2834. // since we don't know whether we're operating on lower bound or
  2835. // upper bound.
  2836. return rep_->file_size / 2;
  2837. }
  2838. // Pro-rate file metadata (incl filters) size-proportionally across data
  2839. // blocks.
  2840. double size_ratio =
  2841. static_cast<double>(offset) / static_cast<double>(data_size);
  2842. return static_cast<uint64_t>(size_ratio *
  2843. static_cast<double>(rep_->file_size));
  2844. }
  2845. uint64_t BlockBasedTable::ApproximateSize(const ReadOptions& read_options,
  2846. const Slice& start, const Slice& end,
  2847. TableReaderCaller caller) {
  2848. assert(rep_->internal_comparator.Compare(start, end) <= 0);
  2849. uint64_t data_size = GetApproximateDataSize();
  2850. if (UNLIKELY(data_size == 0)) {
  2851. // Hmm. Assume whole file is involved, since we have lower and upper
  2852. // bound. This likely skews the estimate if we consider that this function
  2853. // is typically called with `[start, end]` fully contained in the file's
  2854. // key-range.
  2855. return rep_->file_size;
  2856. }
  2857. BlockCacheLookupContext context(caller);
  2858. IndexBlockIter iiter_on_stack;
  2859. auto index_iter =
  2860. NewIndexIterator(read_options, /*disable_prefix_seek=*/true,
  2861. /*input_iter=*/&iiter_on_stack, /*get_context=*/nullptr,
  2862. /*lookup_context=*/&context);
  2863. std::unique_ptr<InternalIteratorBase<IndexValue>> iiter_unique_ptr;
  2864. if (index_iter != &iiter_on_stack) {
  2865. iiter_unique_ptr.reset(index_iter);
  2866. }
  2867. index_iter->Seek(start);
  2868. uint64_t start_offset;
  2869. if (index_iter->status().ok()) {
  2870. start_offset = ApproximateDataOffsetOf(*index_iter, data_size);
  2871. } else {
  2872. // Assume file is involved from the start. This likely skews the estimate
  2873. // but is consistent with the above error handling.
  2874. start_offset = 0;
  2875. }
  2876. index_iter->Seek(end);
  2877. uint64_t end_offset;
  2878. if (index_iter->status().ok()) {
  2879. end_offset = ApproximateDataOffsetOf(*index_iter, data_size);
  2880. } else {
  2881. // Assume file is involved until the end. This likely skews the estimate
  2882. // but is consistent with the above error handling.
  2883. end_offset = data_size;
  2884. }
  2885. assert(end_offset >= start_offset);
  2886. // Pro-rate file metadata (incl filters) size-proportionally across data
  2887. // blocks.
  2888. double size_ratio = static_cast<double>(end_offset - start_offset) /
  2889. static_cast<double>(data_size);
  2890. return static_cast<uint64_t>(size_ratio *
  2891. static_cast<double>(rep_->file_size));
  2892. }
  2893. bool BlockBasedTable::TEST_FilterBlockInCache() const {
  2894. assert(rep_ != nullptr);
  2895. return rep_->filter_type != Rep::FilterType::kNoFilter &&
  2896. TEST_BlockInCache(rep_->filter_handle);
  2897. }
  2898. bool BlockBasedTable::TEST_IndexBlockInCache() const {
  2899. assert(rep_ != nullptr);
  2900. return TEST_BlockInCache(rep_->index_handle);
  2901. }
  2902. Status BlockBasedTable::GetKVPairsFromDataBlocks(
  2903. const ReadOptions& read_options, std::vector<KVPairBlock>* kv_pair_blocks) {
  2904. std::unique_ptr<InternalIteratorBase<IndexValue>> blockhandles_iter(
  2905. NewIndexIterator(read_options, /*need_upper_bound_check=*/false,
  2906. /*input_iter=*/nullptr, /*get_context=*/nullptr,
  2907. /*lookup_contex=*/nullptr));
  2908. Status s = blockhandles_iter->status();
  2909. if (!s.ok()) {
  2910. // Cannot read Index Block
  2911. return s;
  2912. }
  2913. for (blockhandles_iter->SeekToFirst(); blockhandles_iter->Valid();
  2914. blockhandles_iter->Next()) {
  2915. s = blockhandles_iter->status();
  2916. if (!s.ok()) {
  2917. break;
  2918. }
  2919. std::unique_ptr<InternalIterator> datablock_iter;
  2920. Status tmp_status;
  2921. datablock_iter.reset(NewDataBlockIterator<DataBlockIter>(
  2922. read_options, blockhandles_iter->value().handle,
  2923. /*input_iter=*/nullptr, /*type=*/BlockType::kData,
  2924. /*get_context=*/nullptr, /*lookup_context=*/nullptr,
  2925. /*prefetch_buffer=*/nullptr, /*for_compaction=*/false,
  2926. /*async_read=*/false, tmp_status, /*use_block_cache_for_lookup=*/true));
  2927. s = datablock_iter->status();
  2928. if (!s.ok()) {
  2929. // Error reading the block - Skipped
  2930. continue;
  2931. }
  2932. KVPairBlock kv_pair_block;
  2933. for (datablock_iter->SeekToFirst(); datablock_iter->Valid();
  2934. datablock_iter->Next()) {
  2935. s = datablock_iter->status();
  2936. if (!s.ok()) {
  2937. // Error reading the block - Skipped
  2938. break;
  2939. }
  2940. const Slice& key = datablock_iter->key();
  2941. const Slice& value = datablock_iter->value();
  2942. std::string key_copy = std::string(key.data(), key.size());
  2943. std::string value_copy = std::string(value.data(), value.size());
  2944. kv_pair_block.push_back(
  2945. std::make_pair(std::move(key_copy), std::move(value_copy)));
  2946. }
  2947. kv_pair_blocks->push_back(std::move(kv_pair_block));
  2948. }
  2949. return Status::OK();
  2950. }
  2951. Status BlockBasedTable::DumpTable(WritableFile* out_file) {
  2952. WritableFileStringStreamAdapter out_file_wrapper(out_file);
  2953. std::ostream out_stream(&out_file_wrapper);
  2954. // Output Footer
  2955. out_stream << "Footer Details:\n"
  2956. "--------------------------------------\n";
  2957. out_stream << " " << rep_->footer.ToString() << "\n";
  2958. // Output MetaIndex
  2959. out_stream << "Metaindex Details:\n"
  2960. "--------------------------------------\n";
  2961. std::unique_ptr<Block> metaindex;
  2962. std::unique_ptr<InternalIterator> metaindex_iter;
  2963. // TODO: plumb Env::IOActivity, Env::IOPriority
  2964. const ReadOptions ro;
  2965. Status s = ReadMetaIndexBlock(ro, nullptr /* prefetch_buffer */, &metaindex,
  2966. &metaindex_iter);
  2967. if (s.ok()) {
  2968. for (metaindex_iter->SeekToFirst(); metaindex_iter->Valid();
  2969. metaindex_iter->Next()) {
  2970. s = metaindex_iter->status();
  2971. if (!s.ok()) {
  2972. return s;
  2973. }
  2974. if (metaindex_iter->key() == kPropertiesBlockName) {
  2975. out_stream << " Properties block handle: "
  2976. << metaindex_iter->value().ToString(true) << "\n";
  2977. } else if (metaindex_iter->key() == kCompressionDictBlockName) {
  2978. out_stream << " Compression dictionary block handle: "
  2979. << metaindex_iter->value().ToString(true) << "\n";
  2980. } else if (strstr(metaindex_iter->key().ToString().c_str(),
  2981. "filter.rocksdb.") != nullptr) {
  2982. out_stream << " Filter block handle: "
  2983. << metaindex_iter->value().ToString(true) << "\n";
  2984. } else if (metaindex_iter->key() == kRangeDelBlockName) {
  2985. out_stream << " Range deletion block handle: "
  2986. << metaindex_iter->value().ToString(true) << "\n";
  2987. }
  2988. }
  2989. out_stream << "\n";
  2990. } else {
  2991. return s;
  2992. }
  2993. // Output TableProperties
  2994. const ROCKSDB_NAMESPACE::TableProperties* table_properties;
  2995. table_properties = rep_->table_properties.get();
  2996. if (table_properties != nullptr) {
  2997. out_stream << "Table Properties:\n"
  2998. "--------------------------------------\n";
  2999. out_stream << " " << table_properties->ToString("\n ", ": ") << "\n";
  3000. }
  3001. if (rep_->filter) {
  3002. out_stream << "Filter Details:\n"
  3003. "--------------------------------------\n";
  3004. out_stream << " " << rep_->filter->ToString() << "\n";
  3005. }
  3006. // Output Index block
  3007. s = DumpIndexBlock(out_stream);
  3008. if (!s.ok()) {
  3009. return s;
  3010. }
  3011. // Output compression dictionary
  3012. if (rep_->uncompression_dict_reader) {
  3013. CachableEntry<DecompressorDict> uncompression_dict;
  3014. s = rep_->uncompression_dict_reader->GetOrReadUncompressionDictionary(
  3015. nullptr /* prefetch_buffer */, ro, nullptr /* get_context */,
  3016. nullptr /* lookup_context */, &uncompression_dict);
  3017. if (!s.ok()) {
  3018. return s;
  3019. }
  3020. assert(uncompression_dict.GetValue());
  3021. const Slice& raw_dict = uncompression_dict.GetValue()->GetRawDict();
  3022. out_stream << "Compression Dictionary:\n"
  3023. "--------------------------------------\n";
  3024. out_stream << " size (bytes): " << raw_dict.size() << "\n\n";
  3025. out_stream << " HEX " << raw_dict.ToString(true) << "\n\n";
  3026. }
  3027. // Output range deletions block
  3028. auto* range_del_iter = NewRangeTombstoneIterator(ro);
  3029. if (range_del_iter != nullptr) {
  3030. range_del_iter->SeekToFirst();
  3031. if (range_del_iter->Valid()) {
  3032. out_stream << "Range deletions:\n"
  3033. "--------------------------------------\n";
  3034. for (; range_del_iter->Valid(); range_del_iter->Next()) {
  3035. DumpKeyValue(range_del_iter->key(), range_del_iter->value(),
  3036. out_stream);
  3037. }
  3038. out_stream << "\n";
  3039. }
  3040. delete range_del_iter;
  3041. }
  3042. // Output Data blocks
  3043. s = DumpDataBlocks(out_stream);
  3044. if (!s.ok()) {
  3045. return s;
  3046. }
  3047. if (!out_stream.good()) {
  3048. return Status::IOError("Failed to write to output file");
  3049. }
  3050. return Status::OK();
  3051. }
  3052. Status BlockBasedTable::DumpIndexBlock(std::ostream& out_stream) {
  3053. out_stream << "Index Details:\n"
  3054. "--------------------------------------\n";
  3055. // TODO: plumb Env::IOActivity, Env::IOPriority
  3056. const ReadOptions read_options;
  3057. std::unique_ptr<InternalIteratorBase<IndexValue>> blockhandles_iter(
  3058. NewIndexIterator(read_options, /*need_upper_bound_check=*/false,
  3059. /*input_iter=*/nullptr, /*get_context=*/nullptr,
  3060. /*lookup_contex=*/nullptr));
  3061. Status s = blockhandles_iter->status();
  3062. if (!s.ok()) {
  3063. out_stream << "Can not read Index Block \n\n";
  3064. return s;
  3065. }
  3066. out_stream << " Block key hex dump: Data block handle\n";
  3067. out_stream << " Block key ascii\n\n";
  3068. for (blockhandles_iter->SeekToFirst(); blockhandles_iter->Valid();
  3069. blockhandles_iter->Next()) {
  3070. s = blockhandles_iter->status();
  3071. if (!s.ok()) {
  3072. break;
  3073. }
  3074. Slice key = blockhandles_iter->key();
  3075. Slice user_key;
  3076. InternalKey ikey;
  3077. if (!rep_->index_key_includes_seq) {
  3078. user_key = key;
  3079. } else {
  3080. ikey.DecodeFrom(key);
  3081. user_key = ikey.user_key();
  3082. }
  3083. out_stream << " HEX " << user_key.ToString(true) << ": "
  3084. << blockhandles_iter->value().ToString(true,
  3085. rep_->index_has_first_key)
  3086. << " offset " << blockhandles_iter->value().handle.offset()
  3087. << " size " << blockhandles_iter->value().handle.size() << "\n";
  3088. std::string str_key = user_key.ToString();
  3089. std::string res_key;
  3090. char cspace = ' ';
  3091. for (size_t i = 0; i < str_key.size(); i++) {
  3092. res_key.append(&str_key[i], 1);
  3093. res_key.append(1, cspace);
  3094. }
  3095. out_stream << " ASCII " << res_key << "\n";
  3096. out_stream << " ------\n";
  3097. }
  3098. out_stream << "\n";
  3099. return Status::OK();
  3100. }
  3101. Status BlockBasedTable::DumpDataBlocks(std::ostream& out_stream) {
  3102. // TODO: plumb Env::IOActivity, Env::IOPriority
  3103. const ReadOptions read_options;
  3104. std::unique_ptr<InternalIteratorBase<IndexValue>> blockhandles_iter(
  3105. NewIndexIterator(read_options, /*need_upper_bound_check=*/false,
  3106. /*input_iter=*/nullptr, /*get_context=*/nullptr,
  3107. /*lookup_contex=*/nullptr));
  3108. Status s = blockhandles_iter->status();
  3109. if (!s.ok()) {
  3110. out_stream << "Can not read Index Block \n\n";
  3111. return s;
  3112. }
  3113. uint64_t datablock_size_min = std::numeric_limits<uint64_t>::max();
  3114. uint64_t datablock_size_max = 0;
  3115. uint64_t datablock_size_sum = 0;
  3116. size_t block_id = 1;
  3117. for (blockhandles_iter->SeekToFirst(); blockhandles_iter->Valid();
  3118. block_id++, blockhandles_iter->Next()) {
  3119. s = blockhandles_iter->status();
  3120. if (!s.ok()) {
  3121. break;
  3122. }
  3123. BlockHandle bh = blockhandles_iter->value().handle;
  3124. uint64_t datablock_size = bh.size();
  3125. datablock_size_min = std::min(datablock_size_min, datablock_size);
  3126. datablock_size_max = std::max(datablock_size_max, datablock_size);
  3127. datablock_size_sum += datablock_size;
  3128. out_stream << "Data Block # " << block_id << " @ "
  3129. << blockhandles_iter->value().handle.ToString(true) << "\n";
  3130. out_stream << "--------------------------------------\n";
  3131. std::unique_ptr<InternalIterator> datablock_iter;
  3132. Status tmp_status;
  3133. datablock_iter.reset(NewDataBlockIterator<DataBlockIter>(
  3134. read_options, blockhandles_iter->value().handle,
  3135. /*input_iter=*/nullptr, /*type=*/BlockType::kData,
  3136. /*get_context=*/nullptr, /*lookup_context=*/nullptr,
  3137. /*prefetch_buffer=*/nullptr, /*for_compaction=*/false,
  3138. /*async_read=*/false, tmp_status, /*use_block_cache_for_lookup=*/true));
  3139. s = datablock_iter->status();
  3140. if (!s.ok()) {
  3141. out_stream << "Error reading the block - Skipped \n\n";
  3142. continue;
  3143. }
  3144. for (datablock_iter->SeekToFirst(); datablock_iter->Valid();
  3145. datablock_iter->Next()) {
  3146. s = datablock_iter->status();
  3147. if (!s.ok()) {
  3148. out_stream << "Error reading the block - Skipped \n";
  3149. break;
  3150. }
  3151. DumpKeyValue(datablock_iter->key(), datablock_iter->value(), out_stream);
  3152. }
  3153. out_stream << "\n";
  3154. }
  3155. uint64_t num_datablocks = block_id - 1;
  3156. if (num_datablocks) {
  3157. double datablock_size_avg =
  3158. static_cast<double>(datablock_size_sum) / num_datablocks;
  3159. out_stream << "Data Block Summary:\n";
  3160. out_stream << "--------------------------------------\n";
  3161. out_stream << " # data blocks: " << num_datablocks << "\n";
  3162. out_stream << " min data block size: " << datablock_size_min << "\n";
  3163. out_stream << " max data block size: " << datablock_size_max << "\n";
  3164. out_stream << " avg data block size: "
  3165. << std::to_string(datablock_size_avg) << "\n";
  3166. }
  3167. return Status::OK();
  3168. }
  3169. void BlockBasedTable::DumpKeyValue(const Slice& key, const Slice& value,
  3170. std::ostream& out_stream) {
  3171. InternalKey ikey;
  3172. ikey.DecodeFrom(key);
  3173. out_stream << " HEX " << ikey.user_key().ToString(true) << ": "
  3174. << value.ToString(true) << "\n";
  3175. std::string str_key = ikey.user_key().ToString();
  3176. std::string str_value = value.ToString();
  3177. std::string res_key, res_value;
  3178. char cspace = ' ';
  3179. for (size_t i = 0; i < str_key.size(); i++) {
  3180. if (str_key[i] == '\0') {
  3181. res_key.append("\\0", 2);
  3182. } else {
  3183. res_key.append(&str_key[i], 1);
  3184. }
  3185. res_key.append(1, cspace);
  3186. }
  3187. for (size_t i = 0; i < str_value.size(); i++) {
  3188. if (str_value[i] == '\0') {
  3189. res_value.append("\\0", 2);
  3190. } else {
  3191. res_value.append(&str_value[i], 1);
  3192. }
  3193. res_value.append(1, cspace);
  3194. }
  3195. out_stream << " ASCII " << res_key << ": " << res_value << "\n";
  3196. out_stream << " ------\n";
  3197. }
  3198. void BlockBasedTable::MarkObsolete(uint32_t uncache_aggressiveness) {
  3199. rep_->uncache_aggressiveness.StoreRelaxed(uncache_aggressiveness);
  3200. }
  3201. } // namespace ROCKSDB_NAMESPACE