db_basic_test.cc 182 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402
  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 <cstring>
  10. #include "db/db_test_util.h"
  11. #include "options/options_helper.h"
  12. #include "port/stack_trace.h"
  13. #include "rocksdb/filter_policy.h"
  14. #include "rocksdb/flush_block_policy.h"
  15. #include "rocksdb/merge_operator.h"
  16. #include "rocksdb/perf_context.h"
  17. #include "rocksdb/table.h"
  18. #include "rocksdb/utilities/debug.h"
  19. #include "table/block_based/block_based_table_reader.h"
  20. #include "table/block_based/block_builder.h"
  21. #include "test_util/sync_point.h"
  22. #include "util/file_checksum_helper.h"
  23. #include "util/random.h"
  24. #include "utilities/counted_fs.h"
  25. #include "utilities/fault_injection_env.h"
  26. #include "utilities/fault_injection_fs.h"
  27. #include "utilities/merge_operators.h"
  28. #include "utilities/merge_operators/string_append/stringappend.h"
  29. namespace ROCKSDB_NAMESPACE {
  30. namespace {
  31. class MyFlushBlockPolicy : public FlushBlockPolicy {
  32. public:
  33. explicit MyFlushBlockPolicy(const int num_keys_in_block,
  34. const BlockBuilder& data_block_builder)
  35. : num_keys_in_block_(num_keys_in_block),
  36. num_keys_(0),
  37. data_block_builder_(data_block_builder) {}
  38. bool Update(const Slice& /*key*/, const Slice& /*value*/) override {
  39. if (data_block_builder_.empty()) {
  40. // First key in this block
  41. num_keys_ = 1;
  42. return false;
  43. }
  44. // Flush every 10 keys
  45. if (num_keys_ == num_keys_in_block_) {
  46. num_keys_ = 1;
  47. return true;
  48. }
  49. num_keys_++;
  50. return false;
  51. }
  52. private:
  53. const int num_keys_in_block_;
  54. int num_keys_;
  55. const BlockBuilder& data_block_builder_;
  56. };
  57. class MyFlushBlockPolicyFactory : public FlushBlockPolicyFactory {
  58. public:
  59. explicit MyFlushBlockPolicyFactory(const int num_keys_in_block)
  60. : num_keys_in_block_(num_keys_in_block) {}
  61. virtual const char* Name() const override {
  62. return "MyFlushBlockPolicyFactory";
  63. }
  64. virtual FlushBlockPolicy* NewFlushBlockPolicy(
  65. const BlockBasedTableOptions& /*table_options*/,
  66. const BlockBuilder& data_block_builder) const override {
  67. return new MyFlushBlockPolicy(num_keys_in_block_, data_block_builder);
  68. }
  69. private:
  70. const int num_keys_in_block_;
  71. };
  72. } // namespace
  73. static bool enable_io_uring = true;
  74. extern "C" bool RocksDbIOUringEnable() { return enable_io_uring; }
  75. class DBBasicTest : public DBTestBase {
  76. public:
  77. DBBasicTest() : DBTestBase("db_basic_test", /*env_do_fsync=*/false) {}
  78. };
  79. TEST_F(DBBasicTest, OpenWhenOpen) {
  80. Options options = CurrentOptions();
  81. options.env = env_;
  82. DB* db2 = nullptr;
  83. Status s = DB::Open(options, dbname_, &db2);
  84. ASSERT_NOK(s) << [db2]() {
  85. delete db2;
  86. return "db2 open: ok";
  87. }();
  88. ASSERT_EQ(Status::Code::kIOError, s.code());
  89. ASSERT_EQ(Status::SubCode::kNone, s.subcode());
  90. ASSERT_TRUE(strstr(s.getState(), "lock ") != nullptr);
  91. delete db2;
  92. }
  93. TEST_F(DBBasicTest, EnableDirectIOWithZeroBuf) {
  94. if (!IsDirectIOSupported()) {
  95. ROCKSDB_GTEST_BYPASS("Direct IO not supported");
  96. return;
  97. }
  98. Options options = GetDefaultOptions();
  99. options.create_if_missing = true;
  100. options.use_direct_io_for_flush_and_compaction = true;
  101. options.writable_file_max_buffer_size = 0;
  102. ASSERT_TRUE(TryReopen(options).IsInvalidArgument());
  103. options.writable_file_max_buffer_size = 1024;
  104. Reopen(options);
  105. const std::unordered_map<std::string, std::string> new_db_opts = {
  106. {"writable_file_max_buffer_size", "0"}};
  107. ASSERT_TRUE(db_->SetDBOptions(new_db_opts).IsInvalidArgument());
  108. }
  109. TEST_F(DBBasicTest, UniqueSession) {
  110. Options options = CurrentOptions();
  111. std::string sid1, sid2, sid3, sid4;
  112. ASSERT_OK(db_->GetDbSessionId(sid1));
  113. Reopen(options);
  114. ASSERT_OK(db_->GetDbSessionId(sid2));
  115. ASSERT_OK(Put("foo", "v1"));
  116. ASSERT_OK(db_->GetDbSessionId(sid4));
  117. Reopen(options);
  118. ASSERT_OK(db_->GetDbSessionId(sid3));
  119. ASSERT_NE(sid1, sid2);
  120. ASSERT_NE(sid1, sid3);
  121. ASSERT_NE(sid2, sid3);
  122. ASSERT_EQ(sid2, sid4);
  123. // Expected compact format for session ids (see notes in implementation)
  124. TestRegex expected("[0-9A-Z]{20}");
  125. EXPECT_MATCHES_REGEX(sid1, expected);
  126. EXPECT_MATCHES_REGEX(sid2, expected);
  127. EXPECT_MATCHES_REGEX(sid3, expected);
  128. Close();
  129. ASSERT_OK(ReadOnlyReopen(options));
  130. ASSERT_OK(db_->GetDbSessionId(sid1));
  131. // Test uniqueness between readonly open (sid1) and regular open (sid3)
  132. ASSERT_NE(sid1, sid3);
  133. Close();
  134. ASSERT_OK(ReadOnlyReopen(options));
  135. ASSERT_OK(db_->GetDbSessionId(sid2));
  136. ASSERT_EQ("v1", Get("foo"));
  137. ASSERT_OK(db_->GetDbSessionId(sid3));
  138. ASSERT_NE(sid1, sid2);
  139. ASSERT_EQ(sid2, sid3);
  140. DestroyAndReopen(options);
  141. CreateAndReopenWithCF({"goku"}, options);
  142. ASSERT_OK(db_->GetDbSessionId(sid1));
  143. ASSERT_OK(Put("bar", "e1"));
  144. ASSERT_OK(db_->GetDbSessionId(sid2));
  145. ASSERT_EQ("e1", Get("bar"));
  146. ASSERT_OK(db_->GetDbSessionId(sid3));
  147. ReopenWithColumnFamilies({"default", "goku"}, options);
  148. ASSERT_OK(db_->GetDbSessionId(sid4));
  149. ASSERT_EQ(sid1, sid2);
  150. ASSERT_EQ(sid2, sid3);
  151. ASSERT_NE(sid1, sid4);
  152. }
  153. TEST_F(DBBasicTest, ReadOnlyDB) {
  154. ASSERT_OK(Put("foo", "v1"));
  155. ASSERT_OK(Put("bar", "v2"));
  156. ASSERT_OK(Flush());
  157. ASSERT_OK(Put("foo", "v3"));
  158. Close();
  159. auto verify_one_iter = [&](Iterator* iter) {
  160. int count = 0;
  161. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  162. ASSERT_OK(iter->status());
  163. ++count;
  164. }
  165. ASSERT_OK(iter->status());
  166. // Always expect two keys: "foo" and "bar"
  167. ASSERT_EQ(count, 2);
  168. };
  169. auto verify_all_iters = [&]() {
  170. Iterator* iter = db_->NewIterator(ReadOptions());
  171. verify_one_iter(iter);
  172. delete iter;
  173. std::vector<Iterator*> iters;
  174. ASSERT_OK(db_->NewIterators(ReadOptions(),
  175. {dbfull()->DefaultColumnFamily()}, &iters));
  176. ASSERT_EQ(static_cast<uint64_t>(1), iters.size());
  177. verify_one_iter(iters[0]);
  178. delete iters[0];
  179. };
  180. auto options = CurrentOptions();
  181. assert(options.env == env_);
  182. ASSERT_OK(EnforcedReadOnlyReopen(options));
  183. ASSERT_EQ("v3", Get("foo"));
  184. ASSERT_EQ("v2", Get("bar"));
  185. verify_all_iters();
  186. ASSERT_EQ(Flush().code(), Status::Code::kNotSupported);
  187. Close();
  188. // Reopen and flush memtable.
  189. Reopen(options);
  190. ASSERT_OK(Flush());
  191. Close();
  192. // Now check keys in read only mode.
  193. ASSERT_OK(EnforcedReadOnlyReopen(options));
  194. ASSERT_EQ("v3", Get("foo"));
  195. ASSERT_EQ("v2", Get("bar"));
  196. verify_all_iters();
  197. ASSERT_EQ(db_->SyncWAL().code(), Status::Code::kNotSupported);
  198. // More ops that should fail
  199. std::vector<ColumnFamilyHandle*> cfhs{{}};
  200. ASSERT_EQ(db_->CreateColumnFamily(options, "blah", &cfhs[0]).code(),
  201. Status::Code::kNotSupported);
  202. ASSERT_EQ(db_->CreateColumnFamilies(options, {"blah"}, &cfhs).code(),
  203. Status::Code::kNotSupported);
  204. std::vector<ColumnFamilyDescriptor> cfds;
  205. cfds.push_back({"blah", options});
  206. ASSERT_EQ(db_->CreateColumnFamilies(cfds, &cfhs).code(),
  207. Status::Code::kNotSupported);
  208. }
  209. TEST_F(DBBasicTest, ReadOnlyDBWithWriteDBIdToManifestSet) {
  210. auto options = CurrentOptions();
  211. options.write_dbid_to_manifest = false;
  212. DestroyAndReopen(options);
  213. ASSERT_OK(Put("foo", "v1"));
  214. ASSERT_OK(Put("bar", "v2"));
  215. ASSERT_OK(Put("foo", "v3"));
  216. Close();
  217. options.write_dbid_to_manifest = true;
  218. assert(options.env == env_);
  219. ASSERT_OK(EnforcedReadOnlyReopen(options));
  220. std::string db_id1;
  221. ASSERT_OK(db_->GetDbIdentity(db_id1));
  222. ASSERT_EQ("v3", Get("foo"));
  223. ASSERT_EQ("v2", Get("bar"));
  224. Iterator* iter = db_->NewIterator(ReadOptions());
  225. int count = 0;
  226. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  227. ASSERT_OK(iter->status());
  228. ++count;
  229. }
  230. ASSERT_EQ(count, 2);
  231. delete iter;
  232. Close();
  233. // Reopen and flush memtable.
  234. Reopen(options);
  235. ASSERT_OK(Flush());
  236. Close();
  237. // Now check keys in read only mode.
  238. ASSERT_OK(EnforcedReadOnlyReopen(options));
  239. ASSERT_EQ("v3", Get("foo"));
  240. ASSERT_EQ("v2", Get("bar"));
  241. ASSERT_TRUE(db_->SyncWAL().IsNotSupported());
  242. std::string db_id2;
  243. ASSERT_OK(db_->GetDbIdentity(db_id2));
  244. ASSERT_EQ(db_id1, db_id2);
  245. }
  246. TEST_F(DBBasicTest, CompactedDB) {
  247. const uint64_t kFileSize = 1 << 20;
  248. Options options = CurrentOptions();
  249. options.disable_auto_compactions = true;
  250. options.write_buffer_size = kFileSize;
  251. options.target_file_size_base = kFileSize;
  252. options.max_bytes_for_level_base = 1 << 30;
  253. options.compression = kNoCompression;
  254. Reopen(options);
  255. // 1 L0 file, use CompactedDB if max_open_files = -1
  256. ASSERT_OK(Put("aaa", DummyString(kFileSize / 2, '1')));
  257. ASSERT_OK(Flush());
  258. Close();
  259. ASSERT_OK(ReadOnlyReopen(options));
  260. Status s = Put("new", "value");
  261. ASSERT_EQ(s.ToString(),
  262. "Not implemented: Not supported operation in read only mode.");
  263. ASSERT_EQ(DummyString(kFileSize / 2, '1'), Get("aaa"));
  264. Close();
  265. options.max_open_files = -1;
  266. ASSERT_OK(ReadOnlyReopen(options));
  267. s = Put("new", "value");
  268. ASSERT_EQ(s.ToString(),
  269. "Not implemented: Not supported in compacted db mode.");
  270. ASSERT_EQ(DummyString(kFileSize / 2, '1'), Get("aaa"));
  271. Close();
  272. Reopen(options);
  273. // Add more L0 files
  274. ASSERT_OK(Put("bbb", DummyString(kFileSize / 2, '2')));
  275. ASSERT_OK(Flush());
  276. ASSERT_OK(Put("aaa", DummyString(kFileSize / 2, 'a')));
  277. ASSERT_OK(Flush());
  278. ASSERT_OK(Put("bbb", DummyString(kFileSize / 2, 'b')));
  279. ASSERT_OK(Put("eee", DummyString(kFileSize / 2, 'e')));
  280. ASSERT_OK(Flush());
  281. ASSERT_OK(Put("something_not_flushed", "x"));
  282. Close();
  283. ASSERT_OK(ReadOnlyReopen(options));
  284. // Fallback to read-only DB
  285. s = Put("new", "value");
  286. ASSERT_EQ(s.ToString(),
  287. "Not implemented: Not supported operation in read only mode.");
  288. // TODO: validate that other write ops return NotImplemented
  289. // (DBImplReadOnly is missing some overrides)
  290. // Ensure no deadlock on flush triggered by another API function
  291. // (Old deadlock bug depends on something_not_flushed above.)
  292. std::vector<std::string> files;
  293. uint64_t manifest_file_size;
  294. ASSERT_OK(db_->GetLiveFiles(files, &manifest_file_size, /*flush*/ true));
  295. LiveFilesStorageInfoOptions lfsi_opts;
  296. lfsi_opts.wal_size_for_flush = 0; // always
  297. std::vector<LiveFileStorageInfo> files2;
  298. ASSERT_OK(db_->GetLiveFilesStorageInfo(lfsi_opts, &files2));
  299. Close();
  300. // Full compaction
  301. Reopen(options);
  302. // Add more keys
  303. ASSERT_OK(Put("fff", DummyString(kFileSize / 2, 'f')));
  304. ASSERT_OK(Put("hhh", DummyString(kFileSize / 2, 'h')));
  305. ASSERT_OK(Put("iii", DummyString(kFileSize / 2, 'i')));
  306. ASSERT_OK(Put("jjj", DummyString(kFileSize / 2, 'j')));
  307. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  308. ASSERT_EQ(3, NumTableFilesAtLevel(1));
  309. Close();
  310. // CompactedDB
  311. ASSERT_OK(ReadOnlyReopen(options));
  312. s = Put("new", "value");
  313. ASSERT_EQ(s.ToString(),
  314. "Not implemented: Not supported in compacted db mode.");
  315. ASSERT_EQ("NOT_FOUND", Get("abc"));
  316. ASSERT_EQ(DummyString(kFileSize / 2, 'a'), Get("aaa"));
  317. ASSERT_EQ(DummyString(kFileSize / 2, 'b'), Get("bbb"));
  318. ASSERT_EQ("NOT_FOUND", Get("ccc"));
  319. ASSERT_EQ(DummyString(kFileSize / 2, 'e'), Get("eee"));
  320. ASSERT_EQ(DummyString(kFileSize / 2, 'f'), Get("fff"));
  321. ASSERT_EQ("NOT_FOUND", Get("ggg"));
  322. ASSERT_EQ(DummyString(kFileSize / 2, 'h'), Get("hhh"));
  323. ASSERT_EQ(DummyString(kFileSize / 2, 'i'), Get("iii"));
  324. ASSERT_EQ(DummyString(kFileSize / 2, 'j'), Get("jjj"));
  325. ASSERT_EQ("NOT_FOUND", Get("kkk"));
  326. // TODO: validate that other write ops return NotImplemented
  327. // (CompactedDB is missing some overrides)
  328. // Ensure no deadlock on flush triggered by another API function
  329. ASSERT_OK(db_->GetLiveFiles(files, &manifest_file_size, /*flush*/ true));
  330. ASSERT_OK(db_->GetLiveFilesStorageInfo(lfsi_opts, &files2));
  331. // MultiGet
  332. std::vector<std::string> values;
  333. std::vector<Status> status_list = dbfull()->MultiGet(
  334. ReadOptions(),
  335. std::vector<Slice>({Slice("aaa"), Slice("ccc"), Slice("eee"),
  336. Slice("ggg"), Slice("iii"), Slice("kkk")}),
  337. &values);
  338. ASSERT_EQ(status_list.size(), static_cast<uint64_t>(6));
  339. ASSERT_EQ(values.size(), static_cast<uint64_t>(6));
  340. ASSERT_OK(status_list[0]);
  341. ASSERT_EQ(DummyString(kFileSize / 2, 'a'), values[0]);
  342. ASSERT_TRUE(status_list[1].IsNotFound());
  343. ASSERT_OK(status_list[2]);
  344. ASSERT_EQ(DummyString(kFileSize / 2, 'e'), values[2]);
  345. ASSERT_TRUE(status_list[3].IsNotFound());
  346. ASSERT_OK(status_list[4]);
  347. ASSERT_EQ(DummyString(kFileSize / 2, 'i'), values[4]);
  348. ASSERT_TRUE(status_list[5].IsNotFound());
  349. Reopen(options);
  350. // Add a key
  351. ASSERT_OK(Put("fff", DummyString(kFileSize / 2, 'f')));
  352. Close();
  353. ASSERT_OK(ReadOnlyReopen(options));
  354. s = Put("new", "value");
  355. ASSERT_EQ(s.ToString(),
  356. "Not implemented: Not supported operation in read only mode.");
  357. }
  358. TEST_F(DBBasicTest, LevelLimitReopen) {
  359. Options options = CurrentOptions();
  360. CreateAndReopenWithCF({"pikachu"}, options);
  361. const std::string value(1024 * 1024, ' ');
  362. int i = 0;
  363. while (NumTableFilesAtLevel(2, 1) == 0) {
  364. ASSERT_OK(Put(1, Key(i++), value));
  365. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  366. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  367. }
  368. options.num_levels = 1;
  369. options.max_bytes_for_level_multiplier_additional.resize(1, 1);
  370. Status s = TryReopenWithColumnFamilies({"default", "pikachu"}, options);
  371. ASSERT_EQ(s.IsInvalidArgument(), true);
  372. ASSERT_EQ(s.ToString(),
  373. "Invalid argument: db has more levels than options.num_levels");
  374. options.num_levels = 10;
  375. options.max_bytes_for_level_multiplier_additional.resize(10, 1);
  376. ASSERT_OK(TryReopenWithColumnFamilies({"default", "pikachu"}, options));
  377. }
  378. TEST_F(DBBasicTest, PutDeleteGet) {
  379. do {
  380. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  381. ASSERT_OK(Put(1, "foo", "v1"));
  382. ASSERT_EQ("v1", Get(1, "foo"));
  383. ASSERT_OK(Put(1, "foo", "v2"));
  384. ASSERT_EQ("v2", Get(1, "foo"));
  385. ASSERT_OK(Delete(1, "foo"));
  386. ASSERT_EQ("NOT_FOUND", Get(1, "foo"));
  387. } while (ChangeOptions());
  388. }
  389. TEST_F(DBBasicTest, PutSingleDeleteGet) {
  390. do {
  391. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  392. ASSERT_OK(Put(1, "foo", "v1"));
  393. ASSERT_EQ("v1", Get(1, "foo"));
  394. ASSERT_OK(Put(1, "foo2", "v2"));
  395. ASSERT_EQ("v2", Get(1, "foo2"));
  396. ASSERT_OK(SingleDelete(1, "foo"));
  397. ASSERT_EQ("NOT_FOUND", Get(1, "foo"));
  398. // Ski FIFO and universal compaction because they do not apply to the test
  399. // case. Skip MergePut because single delete does not get removed when it
  400. // encounters a merge.
  401. } while (ChangeOptions(kSkipFIFOCompaction | kSkipUniversalCompaction |
  402. kSkipMergePut));
  403. }
  404. TEST_F(DBBasicTest, TimedPutBasic) {
  405. do {
  406. Options options = CurrentOptions();
  407. options.merge_operator = MergeOperators::CreateStringAppendOperator();
  408. CreateAndReopenWithCF({"pikachu"}, options);
  409. ASSERT_OK(TimedPut(1, "foo", "v1", /*write_unix_time=*/0));
  410. // Read from memtable
  411. ASSERT_EQ("v1", Get(1, "foo"));
  412. ASSERT_OK(TimedPut(1, "foo", "v2.1", /*write_unix_time=*/3));
  413. ASSERT_EQ("v2.1", Get(1, "foo"));
  414. // Read from sst file
  415. ASSERT_OK(db_->Flush(FlushOptions(), handles_[1]));
  416. ASSERT_OK(Merge(1, "foo", "v2.2"));
  417. ASSERT_EQ("v2.1,v2.2", Get(1, "foo"));
  418. ASSERT_OK(Delete(1, "foo"));
  419. ASSERT_EQ("NOT_FOUND", Get(1, "foo"));
  420. ASSERT_OK(TimedPut(1, "bar", "bv1", /*write_unix_time=*/0));
  421. ASSERT_EQ("bv1", Get(1, "bar"));
  422. ASSERT_OK(TimedPut(1, "baz", "bzv1", /*write_unix_time=*/0));
  423. ASSERT_EQ("bzv1", Get(1, "baz"));
  424. if (option_config_ != kRowCache) {
  425. std::string range_del_begin = "b";
  426. std::string range_del_end = "baz";
  427. Slice begin_rdel = range_del_begin, end_rdel = range_del_end;
  428. ASSERT_OK(
  429. db_->DeleteRange(WriteOptions(), handles_[1], begin_rdel, end_rdel));
  430. ASSERT_EQ("NOT_FOUND", Get(1, "bar"));
  431. }
  432. ASSERT_EQ("bzv1", Get(1, "baz"));
  433. ASSERT_OK(SingleDelete(1, "baz"));
  434. ASSERT_EQ("NOT_FOUND", Get(1, "baz"));
  435. } while (ChangeOptions(kSkipPlainTable));
  436. }
  437. TEST_F(DBBasicTest, EmptyFlush) {
  438. // It is possible to produce empty flushes when using single deletes. Tests
  439. // whether empty flushes cause issues.
  440. do {
  441. Random rnd(301);
  442. Options options = CurrentOptions();
  443. options.disable_auto_compactions = true;
  444. CreateAndReopenWithCF({"pikachu"}, options);
  445. ASSERT_OK(Put(1, "a", Slice()));
  446. ASSERT_OK(SingleDelete(1, "a"));
  447. ASSERT_OK(Flush(1));
  448. ASSERT_EQ("[ ]", AllEntriesFor("a", 1));
  449. // Skip FIFO and universal compaction as they do not apply to the test
  450. // case. Skip MergePut because merges cannot be combined with single
  451. // deletions.
  452. } while (ChangeOptions(kSkipFIFOCompaction | kSkipUniversalCompaction |
  453. kSkipMergePut));
  454. }
  455. TEST_F(DBBasicTest, GetFromVersions) {
  456. do {
  457. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  458. ASSERT_OK(Put(1, "foo", "v1"));
  459. ASSERT_OK(Flush(1));
  460. ASSERT_EQ("v1", Get(1, "foo"));
  461. ASSERT_EQ("NOT_FOUND", Get(0, "foo"));
  462. } while (ChangeOptions());
  463. }
  464. TEST_F(DBBasicTest, GetSnapshot) {
  465. anon::OptionsOverride options_override;
  466. options_override.skip_policy = kSkipNoSnapshot;
  467. do {
  468. CreateAndReopenWithCF({"pikachu"}, CurrentOptions(options_override));
  469. // Try with both a short key and a long key
  470. for (int i = 0; i < 2; i++) {
  471. std::string key = (i == 0) ? std::string("foo") : std::string(200, 'x');
  472. ASSERT_OK(Put(1, key, "v1"));
  473. const Snapshot* s1 = db_->GetSnapshot();
  474. ASSERT_OK(Put(1, key, "v2"));
  475. ASSERT_EQ("v2", Get(1, key));
  476. ASSERT_EQ("v1", Get(1, key, s1));
  477. ASSERT_OK(Flush(1));
  478. ASSERT_EQ("v2", Get(1, key));
  479. ASSERT_EQ("v1", Get(1, key, s1));
  480. db_->ReleaseSnapshot(s1);
  481. }
  482. } while (ChangeOptions());
  483. }
  484. TEST_F(DBBasicTest, CheckLock) {
  485. do {
  486. DB* localdb = nullptr;
  487. Options options = CurrentOptions();
  488. ASSERT_OK(TryReopen(options));
  489. // second open should fail
  490. Status s = DB::Open(options, dbname_, &localdb);
  491. ASSERT_NOK(s) << [localdb]() {
  492. delete localdb;
  493. return "localdb open: ok";
  494. }();
  495. #ifdef OS_LINUX
  496. ASSERT_TRUE(s.ToString().find("lock ") != std::string::npos);
  497. #endif // OS_LINUX
  498. } while (ChangeCompactOptions());
  499. }
  500. TEST_F(DBBasicTest, FlushMultipleMemtable) {
  501. do {
  502. Options options = CurrentOptions();
  503. WriteOptions writeOpt = WriteOptions();
  504. writeOpt.disableWAL = true;
  505. options.max_write_buffer_number = 4;
  506. options.min_write_buffer_number_to_merge = 3;
  507. options.max_write_buffer_size_to_maintain = -1;
  508. CreateAndReopenWithCF({"pikachu"}, options);
  509. ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "foo", "v1"));
  510. ASSERT_OK(Flush(1));
  511. ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "bar", "v1"));
  512. ASSERT_EQ("v1", Get(1, "foo"));
  513. ASSERT_EQ("v1", Get(1, "bar"));
  514. ASSERT_OK(Flush(1));
  515. } while (ChangeCompactOptions());
  516. }
  517. TEST_F(DBBasicTest, FlushEmptyColumnFamily) {
  518. // Block flush thread and disable compaction thread
  519. env_->SetBackgroundThreads(1, Env::HIGH);
  520. env_->SetBackgroundThreads(1, Env::LOW);
  521. test::SleepingBackgroundTask sleeping_task_low;
  522. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
  523. Env::Priority::LOW);
  524. test::SleepingBackgroundTask sleeping_task_high;
  525. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask,
  526. &sleeping_task_high, Env::Priority::HIGH);
  527. Options options = CurrentOptions();
  528. // disable compaction
  529. options.disable_auto_compactions = true;
  530. WriteOptions writeOpt = WriteOptions();
  531. writeOpt.disableWAL = true;
  532. options.max_write_buffer_number = 2;
  533. options.min_write_buffer_number_to_merge = 1;
  534. options.max_write_buffer_size_to_maintain =
  535. static_cast<int64_t>(options.write_buffer_size);
  536. CreateAndReopenWithCF({"pikachu"}, options);
  537. // Compaction can still go through even if no thread can flush the
  538. // mem table.
  539. ASSERT_OK(Flush(0));
  540. ASSERT_OK(Flush(1));
  541. // Insert can go through
  542. ASSERT_OK(dbfull()->Put(writeOpt, handles_[0], "foo", "v1"));
  543. ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "bar", "v1"));
  544. ASSERT_EQ("v1", Get(0, "foo"));
  545. ASSERT_EQ("v1", Get(1, "bar"));
  546. sleeping_task_high.WakeUp();
  547. sleeping_task_high.WaitUntilDone();
  548. // Flush can still go through.
  549. ASSERT_OK(Flush(0));
  550. ASSERT_OK(Flush(1));
  551. sleeping_task_low.WakeUp();
  552. sleeping_task_low.WaitUntilDone();
  553. }
  554. TEST_F(DBBasicTest, Flush) {
  555. do {
  556. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  557. WriteOptions writeOpt = WriteOptions();
  558. writeOpt.disableWAL = true;
  559. SetPerfLevel(kEnableTime);
  560. ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "foo", "v1"));
  561. // this will now also flush the last 2 writes
  562. ASSERT_OK(Flush(1));
  563. ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "bar", "v1"));
  564. get_perf_context()->Reset();
  565. Get(1, "foo");
  566. ASSERT_TRUE((int)get_perf_context()->get_from_output_files_time > 0);
  567. ASSERT_EQ(2, (int)get_perf_context()->get_read_bytes);
  568. ReopenWithColumnFamilies({"default", "pikachu"}, CurrentOptions());
  569. ASSERT_EQ("v1", Get(1, "foo"));
  570. ASSERT_EQ("v1", Get(1, "bar"));
  571. writeOpt.disableWAL = true;
  572. ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "bar", "v2"));
  573. ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "foo", "v2"));
  574. ASSERT_OK(Flush(1));
  575. ReopenWithColumnFamilies({"default", "pikachu"}, CurrentOptions());
  576. ASSERT_EQ("v2", Get(1, "bar"));
  577. get_perf_context()->Reset();
  578. ASSERT_EQ("v2", Get(1, "foo"));
  579. ASSERT_TRUE((int)get_perf_context()->get_from_output_files_time > 0);
  580. writeOpt.disableWAL = false;
  581. ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "bar", "v3"));
  582. ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "foo", "v3"));
  583. ASSERT_OK(Flush(1));
  584. ReopenWithColumnFamilies({"default", "pikachu"}, CurrentOptions());
  585. // 'foo' should be there because its put
  586. // has WAL enabled.
  587. ASSERT_EQ("v3", Get(1, "foo"));
  588. ASSERT_EQ("v3", Get(1, "bar"));
  589. SetPerfLevel(kDisable);
  590. } while (ChangeCompactOptions());
  591. }
  592. TEST_F(DBBasicTest, ManifestRollOver) {
  593. do {
  594. Options options;
  595. options.max_manifest_file_size = 10; // 10 bytes
  596. options = CurrentOptions(options);
  597. CreateAndReopenWithCF({"pikachu"}, options);
  598. {
  599. ASSERT_OK(Put(1, "manifest_key1", std::string(1000, '1')));
  600. ASSERT_OK(Put(1, "manifest_key2", std::string(1000, '2')));
  601. ASSERT_OK(Put(1, "manifest_key3", std::string(1000, '3')));
  602. uint64_t manifest_before_flush = dbfull()->TEST_Current_Manifest_FileNo();
  603. ASSERT_OK(Flush(1)); // This should trigger LogAndApply.
  604. uint64_t manifest_after_flush = dbfull()->TEST_Current_Manifest_FileNo();
  605. ASSERT_GT(manifest_after_flush, manifest_before_flush);
  606. ReopenWithColumnFamilies({"default", "pikachu"}, options);
  607. ASSERT_GT(dbfull()->TEST_Current_Manifest_FileNo(), manifest_after_flush);
  608. // check if a new manifest file got inserted or not.
  609. ASSERT_EQ(std::string(1000, '1'), Get(1, "manifest_key1"));
  610. ASSERT_EQ(std::string(1000, '2'), Get(1, "manifest_key2"));
  611. ASSERT_EQ(std::string(1000, '3'), Get(1, "manifest_key3"));
  612. }
  613. } while (ChangeCompactOptions());
  614. }
  615. TEST_F(DBBasicTest, IdentityAcrossRestarts) {
  616. constexpr size_t kMinIdSize = 10;
  617. do {
  618. for (bool with_manifest : {false, true}) {
  619. for (bool write_file : {false, true}) {
  620. std::string idfilename = IdentityFileName(dbname_);
  621. std::string id1, tmp;
  622. ASSERT_OK(db_->GetDbIdentity(id1));
  623. ASSERT_GE(id1.size(), kMinIdSize);
  624. Options options = CurrentOptions();
  625. options.write_dbid_to_manifest = with_manifest;
  626. options.write_identity_file = true; // initially
  627. Reopen(options);
  628. std::string id2;
  629. ASSERT_OK(db_->GetDbIdentity(id2));
  630. // id2 should match id1 because identity was not regenerated
  631. ASSERT_EQ(id1, id2);
  632. ASSERT_OK(ReadFileToString(env_, idfilename, &tmp));
  633. ASSERT_EQ(tmp, id2);
  634. if (write_file) {
  635. // Recover from deleted/missing IDENTITY
  636. ASSERT_OK(env_->DeleteFile(idfilename));
  637. } else {
  638. // Transition to no IDENTITY file
  639. options.write_identity_file = false;
  640. if (!with_manifest) {
  641. // Incompatible options, should fail
  642. ASSERT_NOK(TryReopen(options));
  643. // Back to a usable config and continue
  644. options.write_identity_file = true;
  645. Reopen(options);
  646. continue;
  647. }
  648. }
  649. Reopen(options);
  650. std::string id3;
  651. ASSERT_OK(db_->GetDbIdentity(id3));
  652. if (with_manifest) {
  653. // id3 should match id1 because identity was restored from manifest
  654. ASSERT_EQ(id1, id3);
  655. } else {
  656. // id3 should NOT match id1 because identity was regenerated
  657. ASSERT_NE(id1, id3);
  658. ASSERT_GE(id3.size(), kMinIdSize);
  659. }
  660. if (write_file) {
  661. ASSERT_OK(ReadFileToString(env_, idfilename, &tmp));
  662. ASSERT_EQ(tmp, id3);
  663. // Recover from truncated IDENTITY
  664. std::unique_ptr<WritableFile> w;
  665. ASSERT_OK(env_->NewWritableFile(idfilename, &w, EnvOptions()));
  666. ASSERT_OK(w->Close());
  667. } else {
  668. ASSERT_TRUE(env_->FileExists(idfilename).IsNotFound());
  669. }
  670. Reopen(options);
  671. std::string id4;
  672. ASSERT_OK(db_->GetDbIdentity(id4));
  673. if (with_manifest) {
  674. // id4 should match id1 because identity was restored from manifest
  675. ASSERT_EQ(id1, id4);
  676. } else {
  677. // id4 should NOT match id1 because identity was regenerated
  678. ASSERT_NE(id1, id4);
  679. ASSERT_GE(id4.size(), kMinIdSize);
  680. }
  681. std::string silly_id = "asdf123456789";
  682. if (write_file) {
  683. ASSERT_OK(ReadFileToString(env_, idfilename, &tmp));
  684. ASSERT_EQ(tmp, id4);
  685. // Recover from overwritten IDENTITY
  686. std::unique_ptr<WritableFile> w;
  687. ASSERT_OK(env_->NewWritableFile(idfilename, &w, EnvOptions()));
  688. ASSERT_OK(w->Append(silly_id));
  689. ASSERT_OK(w->Close());
  690. } else {
  691. ASSERT_TRUE(env_->FileExists(idfilename).IsNotFound());
  692. }
  693. Reopen(options);
  694. std::string id5;
  695. ASSERT_OK(db_->GetDbIdentity(id5));
  696. if (with_manifest) {
  697. // id4 should match id1 because identity was restored from manifest
  698. ASSERT_EQ(id1, id5);
  699. } else {
  700. ASSERT_EQ(id5, silly_id);
  701. }
  702. if (write_file) {
  703. ASSERT_OK(ReadFileToString(env_, idfilename, &tmp));
  704. ASSERT_EQ(tmp, id5);
  705. } else {
  706. ASSERT_TRUE(env_->FileExists(idfilename).IsNotFound());
  707. }
  708. }
  709. }
  710. } while (ChangeCompactOptions());
  711. }
  712. TEST_F(DBBasicTest, LockFileRecovery) {
  713. Options options = CurrentOptions();
  714. // Regardless of best_efforts_recovery
  715. for (bool ber : {false, true}) {
  716. options.best_efforts_recovery = ber;
  717. DestroyAndReopen(options);
  718. std::string id1, id2;
  719. ASSERT_OK(db_->GetDbIdentity(id1));
  720. Close();
  721. // Should be OK to re-open DB after lock file deleted
  722. std::string lockfilename = LockFileName(dbname_);
  723. ASSERT_OK(env_->DeleteFile(lockfilename));
  724. Reopen(options);
  725. // Should be same DB as before
  726. ASSERT_OK(db_->GetDbIdentity(id2));
  727. ASSERT_EQ(id1, id2);
  728. }
  729. }
  730. TEST_F(DBBasicTest, Snapshot) {
  731. env_->SetMockSleep();
  732. anon::OptionsOverride options_override;
  733. options_override.skip_policy = kSkipNoSnapshot;
  734. do {
  735. CreateAndReopenWithCF({"pikachu"}, CurrentOptions(options_override));
  736. ASSERT_OK(Put(0, "foo", "0v1"));
  737. ASSERT_OK(Put(1, "foo", "1v1"));
  738. const Snapshot* s1 = db_->GetSnapshot();
  739. ASSERT_EQ(1U, GetNumSnapshots());
  740. uint64_t time_snap1 = GetTimeOldestSnapshots();
  741. ASSERT_GT(time_snap1, 0U);
  742. ASSERT_EQ(GetSequenceOldestSnapshots(), s1->GetSequenceNumber());
  743. ASSERT_OK(Put(0, "foo", "0v2"));
  744. ASSERT_OK(Put(1, "foo", "1v2"));
  745. env_->MockSleepForSeconds(1);
  746. const Snapshot* s2 = db_->GetSnapshot();
  747. ASSERT_EQ(2U, GetNumSnapshots());
  748. ASSERT_EQ(time_snap1, GetTimeOldestSnapshots());
  749. ASSERT_EQ(GetSequenceOldestSnapshots(), s1->GetSequenceNumber());
  750. ASSERT_OK(Put(0, "foo", "0v3"));
  751. ASSERT_OK(Put(1, "foo", "1v3"));
  752. {
  753. ManagedSnapshot s3(db_);
  754. ASSERT_EQ(3U, GetNumSnapshots());
  755. ASSERT_EQ(time_snap1, GetTimeOldestSnapshots());
  756. ASSERT_EQ(GetSequenceOldestSnapshots(), s1->GetSequenceNumber());
  757. ASSERT_OK(Put(0, "foo", "0v4"));
  758. ASSERT_OK(Put(1, "foo", "1v4"));
  759. ASSERT_EQ("0v1", Get(0, "foo", s1));
  760. ASSERT_EQ("1v1", Get(1, "foo", s1));
  761. ASSERT_EQ("0v2", Get(0, "foo", s2));
  762. ASSERT_EQ("1v2", Get(1, "foo", s2));
  763. ASSERT_EQ("0v3", Get(0, "foo", s3.snapshot()));
  764. ASSERT_EQ("1v3", Get(1, "foo", s3.snapshot()));
  765. ASSERT_EQ("0v4", Get(0, "foo"));
  766. ASSERT_EQ("1v4", Get(1, "foo"));
  767. }
  768. ASSERT_EQ(2U, GetNumSnapshots());
  769. ASSERT_EQ(time_snap1, GetTimeOldestSnapshots());
  770. ASSERT_EQ(GetSequenceOldestSnapshots(), s1->GetSequenceNumber());
  771. ASSERT_EQ("0v1", Get(0, "foo", s1));
  772. ASSERT_EQ("1v1", Get(1, "foo", s1));
  773. ASSERT_EQ("0v2", Get(0, "foo", s2));
  774. ASSERT_EQ("1v2", Get(1, "foo", s2));
  775. ASSERT_EQ("0v4", Get(0, "foo"));
  776. ASSERT_EQ("1v4", Get(1, "foo"));
  777. db_->ReleaseSnapshot(s1);
  778. ASSERT_EQ("0v2", Get(0, "foo", s2));
  779. ASSERT_EQ("1v2", Get(1, "foo", s2));
  780. ASSERT_EQ("0v4", Get(0, "foo"));
  781. ASSERT_EQ("1v4", Get(1, "foo"));
  782. ASSERT_EQ(1U, GetNumSnapshots());
  783. ASSERT_LT(time_snap1, GetTimeOldestSnapshots());
  784. ASSERT_EQ(GetSequenceOldestSnapshots(), s2->GetSequenceNumber());
  785. db_->ReleaseSnapshot(s2);
  786. ASSERT_EQ(0U, GetNumSnapshots());
  787. ASSERT_EQ(GetSequenceOldestSnapshots(), 0);
  788. ASSERT_EQ("0v4", Get(0, "foo"));
  789. ASSERT_EQ("1v4", Get(1, "foo"));
  790. } while (ChangeOptions());
  791. }
  792. class DBBasicMultiConfigs : public DBBasicTest,
  793. public ::testing::WithParamInterface<int> {
  794. public:
  795. DBBasicMultiConfigs() { option_config_ = GetParam(); }
  796. static std::vector<int> GenerateOptionConfigs() {
  797. std::vector<int> option_configs;
  798. for (int option_config = kDefault; option_config < kEnd; ++option_config) {
  799. if (!ShouldSkipOptions(option_config, kSkipFIFOCompaction)) {
  800. option_configs.push_back(option_config);
  801. }
  802. }
  803. return option_configs;
  804. }
  805. };
  806. TEST_P(DBBasicMultiConfigs, CompactBetweenSnapshots) {
  807. anon::OptionsOverride options_override;
  808. options_override.skip_policy = kSkipNoSnapshot;
  809. Options options = CurrentOptions(options_override);
  810. options.disable_auto_compactions = true;
  811. DestroyAndReopen(options);
  812. CreateAndReopenWithCF({"pikachu"}, options);
  813. Random rnd(301);
  814. FillLevels("a", "z", 1);
  815. ASSERT_OK(Put(1, "foo", "first"));
  816. const Snapshot* snapshot1 = db_->GetSnapshot();
  817. ASSERT_OK(Put(1, "foo", "second"));
  818. ASSERT_OK(Put(1, "foo", "third"));
  819. ASSERT_OK(Put(1, "foo", "fourth"));
  820. const Snapshot* snapshot2 = db_->GetSnapshot();
  821. ASSERT_OK(Put(1, "foo", "fifth"));
  822. ASSERT_OK(Put(1, "foo", "sixth"));
  823. // All entries (including duplicates) exist
  824. // before any compaction or flush is triggered.
  825. ASSERT_EQ(AllEntriesFor("foo", 1),
  826. "[ sixth, fifth, fourth, third, second, first ]");
  827. ASSERT_EQ("sixth", Get(1, "foo"));
  828. ASSERT_EQ("fourth", Get(1, "foo", snapshot2));
  829. ASSERT_EQ("first", Get(1, "foo", snapshot1));
  830. // After a flush, "second", "third" and "fifth" should
  831. // be removed
  832. ASSERT_OK(Flush(1));
  833. ASSERT_EQ(AllEntriesFor("foo", 1), "[ sixth, fourth, first ]");
  834. // after we release the snapshot1, only two values left
  835. db_->ReleaseSnapshot(snapshot1);
  836. FillLevels("a", "z", 1);
  837. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1], nullptr,
  838. nullptr));
  839. // We have only one valid snapshot snapshot2. Since snapshot1 is
  840. // not valid anymore, "first" should be removed by a compaction.
  841. ASSERT_EQ("sixth", Get(1, "foo"));
  842. ASSERT_EQ("fourth", Get(1, "foo", snapshot2));
  843. ASSERT_EQ(AllEntriesFor("foo", 1), "[ sixth, fourth ]");
  844. // after we release the snapshot2, only one value should be left
  845. db_->ReleaseSnapshot(snapshot2);
  846. FillLevels("a", "z", 1);
  847. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1], nullptr,
  848. nullptr));
  849. ASSERT_EQ("sixth", Get(1, "foo"));
  850. ASSERT_EQ(AllEntriesFor("foo", 1), "[ sixth ]");
  851. }
  852. INSTANTIATE_TEST_CASE_P(
  853. DBBasicMultiConfigs, DBBasicMultiConfigs,
  854. ::testing::ValuesIn(DBBasicMultiConfigs::GenerateOptionConfigs()));
  855. TEST_F(DBBasicTest, DBOpen_Options) {
  856. Options options = CurrentOptions();
  857. Close();
  858. Destroy(options);
  859. // Does not exist, and create_if_missing == false: error
  860. DB* db = nullptr;
  861. options.create_if_missing = false;
  862. Status s = DB::Open(options, dbname_, &db);
  863. ASSERT_TRUE(strstr(s.ToString().c_str(), "does not exist") != nullptr);
  864. ASSERT_TRUE(db == nullptr);
  865. // Does not exist, and create_if_missing == true: OK
  866. options.create_if_missing = true;
  867. s = DB::Open(options, dbname_, &db);
  868. ASSERT_OK(s);
  869. ASSERT_TRUE(db != nullptr);
  870. delete db;
  871. db = nullptr;
  872. // Does exist, and error_if_exists == true: error
  873. options.create_if_missing = false;
  874. options.error_if_exists = true;
  875. s = DB::Open(options, dbname_, &db);
  876. ASSERT_TRUE(strstr(s.ToString().c_str(), "exists") != nullptr);
  877. ASSERT_TRUE(db == nullptr);
  878. // Does exist, and error_if_exists == false: OK
  879. options.create_if_missing = true;
  880. options.error_if_exists = false;
  881. s = DB::Open(options, dbname_, &db);
  882. ASSERT_OK(s);
  883. ASSERT_TRUE(db != nullptr);
  884. delete db;
  885. db = nullptr;
  886. }
  887. TEST_F(DBBasicTest, CompactOnFlush) {
  888. anon::OptionsOverride options_override;
  889. options_override.skip_policy = kSkipNoSnapshot;
  890. do {
  891. Options options = CurrentOptions(options_override);
  892. options.disable_auto_compactions = true;
  893. CreateAndReopenWithCF({"pikachu"}, options);
  894. ASSERT_OK(Put(1, "foo", "v1"));
  895. ASSERT_OK(Flush(1));
  896. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v1 ]");
  897. // Write two new keys
  898. ASSERT_OK(Put(1, "a", "begin"));
  899. ASSERT_OK(Put(1, "z", "end"));
  900. ASSERT_OK(Flush(1));
  901. // Case1: Delete followed by a put
  902. ASSERT_OK(Delete(1, "foo"));
  903. ASSERT_OK(Put(1, "foo", "v2"));
  904. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v2, DEL, v1 ]");
  905. // After the current memtable is flushed, the DEL should
  906. // have been removed
  907. ASSERT_OK(Flush(1));
  908. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v2, v1 ]");
  909. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1],
  910. nullptr, nullptr));
  911. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v2 ]");
  912. // Case 2: Delete followed by another delete
  913. ASSERT_OK(Delete(1, "foo"));
  914. ASSERT_OK(Delete(1, "foo"));
  915. ASSERT_EQ(AllEntriesFor("foo", 1), "[ DEL, DEL, v2 ]");
  916. ASSERT_OK(Flush(1));
  917. ASSERT_EQ(AllEntriesFor("foo", 1), "[ DEL, v2 ]");
  918. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1],
  919. nullptr, nullptr));
  920. ASSERT_EQ(AllEntriesFor("foo", 1), "[ ]");
  921. // Case 3: Put followed by a delete
  922. ASSERT_OK(Put(1, "foo", "v3"));
  923. ASSERT_OK(Delete(1, "foo"));
  924. ASSERT_EQ(AllEntriesFor("foo", 1), "[ DEL, v3 ]");
  925. ASSERT_OK(Flush(1));
  926. ASSERT_EQ(AllEntriesFor("foo", 1), "[ DEL ]");
  927. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1],
  928. nullptr, nullptr));
  929. ASSERT_EQ(AllEntriesFor("foo", 1), "[ ]");
  930. // Case 4: Put followed by another Put
  931. ASSERT_OK(Put(1, "foo", "v4"));
  932. ASSERT_OK(Put(1, "foo", "v5"));
  933. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v5, v4 ]");
  934. ASSERT_OK(Flush(1));
  935. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v5 ]");
  936. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1],
  937. nullptr, nullptr));
  938. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v5 ]");
  939. // clear database
  940. ASSERT_OK(Delete(1, "foo"));
  941. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1],
  942. nullptr, nullptr));
  943. ASSERT_EQ(AllEntriesFor("foo", 1), "[ ]");
  944. // Case 5: Put followed by snapshot followed by another Put
  945. // Both puts should remain.
  946. ASSERT_OK(Put(1, "foo", "v6"));
  947. const Snapshot* snapshot = db_->GetSnapshot();
  948. ASSERT_OK(Put(1, "foo", "v7"));
  949. ASSERT_OK(Flush(1));
  950. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v7, v6 ]");
  951. db_->ReleaseSnapshot(snapshot);
  952. // clear database
  953. ASSERT_OK(Delete(1, "foo"));
  954. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1],
  955. nullptr, nullptr));
  956. ASSERT_EQ(AllEntriesFor("foo", 1), "[ ]");
  957. // Case 5: snapshot followed by a put followed by another Put
  958. // Only the last put should remain.
  959. const Snapshot* snapshot1 = db_->GetSnapshot();
  960. ASSERT_OK(Put(1, "foo", "v8"));
  961. ASSERT_OK(Put(1, "foo", "v9"));
  962. ASSERT_OK(Flush(1));
  963. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v9 ]");
  964. db_->ReleaseSnapshot(snapshot1);
  965. } while (ChangeCompactOptions());
  966. }
  967. TEST_F(DBBasicTest, FlushOneColumnFamily) {
  968. Options options = CurrentOptions();
  969. CreateAndReopenWithCF({"pikachu", "ilya", "muromec", "dobrynia", "nikitich",
  970. "alyosha", "popovich"},
  971. options);
  972. ASSERT_OK(Put(0, "Default", "Default"));
  973. ASSERT_OK(Put(1, "pikachu", "pikachu"));
  974. ASSERT_OK(Put(2, "ilya", "ilya"));
  975. ASSERT_OK(Put(3, "muromec", "muromec"));
  976. ASSERT_OK(Put(4, "dobrynia", "dobrynia"));
  977. ASSERT_OK(Put(5, "nikitich", "nikitich"));
  978. ASSERT_OK(Put(6, "alyosha", "alyosha"));
  979. ASSERT_OK(Put(7, "popovich", "popovich"));
  980. for (int i = 0; i < 8; ++i) {
  981. ASSERT_OK(Flush(i));
  982. auto tables = ListTableFiles(env_, dbname_);
  983. ASSERT_EQ(tables.size(), i + 1U);
  984. }
  985. }
  986. TEST_F(DBBasicTest, MultiGetSimple) {
  987. do {
  988. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  989. SetPerfLevel(kEnableCount);
  990. ASSERT_OK(Put(1, "k1", "v1"));
  991. ASSERT_OK(Put(1, "k2", "v2"));
  992. ASSERT_OK(Put(1, "k3", "v3"));
  993. ASSERT_OK(Put(1, "k4", "v4"));
  994. ASSERT_OK(Delete(1, "k4"));
  995. ASSERT_OK(Put(1, "k5", "v5"));
  996. ASSERT_OK(Delete(1, "no_key"));
  997. std::vector<Slice> keys({"k1", "k2", "k3", "k4", "k5", "no_key"});
  998. std::vector<std::string> values(20, "Temporary data to be overwritten");
  999. std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
  1000. get_perf_context()->Reset();
  1001. std::vector<Status> s = db_->MultiGet(ReadOptions(), cfs, keys, &values);
  1002. ASSERT_EQ(values.size(), keys.size());
  1003. ASSERT_EQ(values[0], "v1");
  1004. ASSERT_EQ(values[1], "v2");
  1005. ASSERT_EQ(values[2], "v3");
  1006. ASSERT_EQ(values[4], "v5");
  1007. // four kv pairs * two bytes per value
  1008. ASSERT_EQ(8, (int)get_perf_context()->multiget_read_bytes);
  1009. ASSERT_OK(s[0]);
  1010. ASSERT_OK(s[1]);
  1011. ASSERT_OK(s[2]);
  1012. ASSERT_TRUE(s[3].IsNotFound());
  1013. ASSERT_OK(s[4]);
  1014. ASSERT_TRUE(s[5].IsNotFound());
  1015. SetPerfLevel(kDisable);
  1016. } while (ChangeCompactOptions());
  1017. }
  1018. TEST_F(DBBasicTest, MultiGetEmpty) {
  1019. do {
  1020. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  1021. // Empty Key Set
  1022. std::vector<Slice> keys;
  1023. std::vector<std::string> values;
  1024. std::vector<ColumnFamilyHandle*> cfs;
  1025. std::vector<Status> s = db_->MultiGet(ReadOptions(), cfs, keys, &values);
  1026. ASSERT_EQ(s.size(), 0U);
  1027. // Empty Database, Empty Key Set
  1028. Options options = CurrentOptions();
  1029. options.create_if_missing = true;
  1030. DestroyAndReopen(options);
  1031. CreateAndReopenWithCF({"pikachu"}, options);
  1032. s = db_->MultiGet(ReadOptions(), cfs, keys, &values);
  1033. ASSERT_EQ(s.size(), 0U);
  1034. // Empty Database, Search for Keys
  1035. keys.resize(2);
  1036. keys[0] = "a";
  1037. keys[1] = "b";
  1038. cfs.push_back(handles_[0]);
  1039. cfs.push_back(handles_[1]);
  1040. s = db_->MultiGet(ReadOptions(), cfs, keys, &values);
  1041. ASSERT_EQ(static_cast<int>(s.size()), 2);
  1042. ASSERT_TRUE(s[0].IsNotFound() && s[1].IsNotFound());
  1043. } while (ChangeCompactOptions());
  1044. }
  1045. class DBBlockChecksumTest : public DBBasicTest,
  1046. public testing::WithParamInterface<uint32_t> {};
  1047. INSTANTIATE_TEST_CASE_P(FormatVersions, DBBlockChecksumTest,
  1048. testing::ValuesIn(test::kFooterFormatVersionsToTest));
  1049. TEST_P(DBBlockChecksumTest, BlockChecksumTest) {
  1050. BlockBasedTableOptions table_options;
  1051. table_options.format_version = GetParam();
  1052. Options options = CurrentOptions();
  1053. const int kNumPerFile = 2;
  1054. const auto algs = GetSupportedChecksums();
  1055. const int algs_size = static_cast<int>(algs.size());
  1056. // generate one table with each type of checksum
  1057. for (int i = 0; i < algs_size; ++i) {
  1058. table_options.checksum = algs[i];
  1059. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1060. Reopen(options);
  1061. for (int j = 0; j < kNumPerFile; ++j) {
  1062. ASSERT_OK(Put(Key(i * kNumPerFile + j), Key(i * kNumPerFile + j)));
  1063. }
  1064. ASSERT_OK(Flush());
  1065. }
  1066. // with each valid checksum type setting...
  1067. for (int i = 0; i < algs_size; ++i) {
  1068. table_options.checksum = algs[i];
  1069. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1070. Reopen(options);
  1071. // verify every type of checksum (should be regardless of that setting)
  1072. for (int j = 0; j < algs_size * kNumPerFile; ++j) {
  1073. ASSERT_EQ(Key(j), Get(Key(j)));
  1074. }
  1075. }
  1076. // Now test invalid checksum type
  1077. table_options.checksum = static_cast<ChecksumType>(123);
  1078. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1079. ASSERT_TRUE(TryReopen(options).IsInvalidArgument());
  1080. }
  1081. // On Windows you can have either memory mapped file or a file
  1082. // with unbuffered access. So this asserts and does not make
  1083. // sense to run
  1084. #ifndef OS_WIN
  1085. TEST_F(DBBasicTest, MmapAndBufferOptions) {
  1086. if (!IsMemoryMappedAccessSupported()) {
  1087. return;
  1088. }
  1089. Options options = CurrentOptions();
  1090. options.use_direct_reads = true;
  1091. options.allow_mmap_reads = true;
  1092. ASSERT_NOK(TryReopen(options));
  1093. // All other combinations are acceptable
  1094. options.use_direct_reads = false;
  1095. ASSERT_OK(TryReopen(options));
  1096. if (IsDirectIOSupported()) {
  1097. options.use_direct_reads = true;
  1098. options.allow_mmap_reads = false;
  1099. ASSERT_OK(TryReopen(options));
  1100. }
  1101. options.use_direct_reads = false;
  1102. ASSERT_OK(TryReopen(options));
  1103. }
  1104. #endif
  1105. class TestEnv : public EnvWrapper {
  1106. public:
  1107. explicit TestEnv(Env* base_env) : EnvWrapper(base_env), close_count(0) {}
  1108. static const char* kClassName() { return "TestEnv"; }
  1109. const char* Name() const override { return kClassName(); }
  1110. class TestLogger : public Logger {
  1111. public:
  1112. using Logger::Logv;
  1113. explicit TestLogger(TestEnv* env_ptr) : Logger() { env = env_ptr; }
  1114. ~TestLogger() override {
  1115. if (!closed_) {
  1116. CloseHelper().PermitUncheckedError();
  1117. }
  1118. }
  1119. void Logv(const char* /*format*/, va_list /*ap*/) override {}
  1120. protected:
  1121. Status CloseImpl() override { return CloseHelper(); }
  1122. private:
  1123. Status CloseHelper() {
  1124. env->CloseCountInc();
  1125. ;
  1126. return Status::IOError();
  1127. }
  1128. TestEnv* env;
  1129. };
  1130. void CloseCountInc() { close_count++; }
  1131. int GetCloseCount() { return close_count; }
  1132. Status NewLogger(const std::string& /*fname*/,
  1133. std::shared_ptr<Logger>* result) override {
  1134. result->reset(new TestLogger(this));
  1135. return Status::OK();
  1136. }
  1137. private:
  1138. int close_count;
  1139. };
  1140. TEST_F(DBBasicTest, DBClose) {
  1141. Options options = GetDefaultOptions();
  1142. std::string dbname = test::PerThreadDBPath("db_close_test");
  1143. ASSERT_OK(DestroyDB(dbname, options));
  1144. DB* db = nullptr;
  1145. TestEnv* env = new TestEnv(env_);
  1146. std::unique_ptr<TestEnv> local_env_guard(env);
  1147. options.create_if_missing = true;
  1148. options.env = env;
  1149. Status s = DB::Open(options, dbname, &db);
  1150. ASSERT_OK(s);
  1151. ASSERT_TRUE(db != nullptr);
  1152. s = db->Close();
  1153. ASSERT_EQ(env->GetCloseCount(), 1);
  1154. ASSERT_EQ(s, Status::IOError());
  1155. delete db;
  1156. ASSERT_EQ(env->GetCloseCount(), 1);
  1157. // Do not call DB::Close() and ensure our logger Close() still gets called
  1158. s = DB::Open(options, dbname, &db);
  1159. ASSERT_OK(s);
  1160. ASSERT_TRUE(db != nullptr);
  1161. delete db;
  1162. ASSERT_EQ(env->GetCloseCount(), 2);
  1163. // close by WaitForCompact() with close_db option
  1164. options.create_if_missing = false;
  1165. s = DB::Open(options, dbname, &db);
  1166. ASSERT_OK(s);
  1167. ASSERT_TRUE(db != nullptr);
  1168. WaitForCompactOptions wait_for_compact_options = WaitForCompactOptions();
  1169. wait_for_compact_options.close_db = true;
  1170. s = db->WaitForCompact(wait_for_compact_options);
  1171. ASSERT_EQ(env->GetCloseCount(), 3);
  1172. // see TestLogger::CloseHelper()
  1173. ASSERT_EQ(s, Status::IOError());
  1174. delete db;
  1175. ASSERT_EQ(env->GetCloseCount(), 3);
  1176. // Provide our own logger and ensure DB::Close() does not close it
  1177. options.info_log.reset(new TestEnv::TestLogger(env));
  1178. s = DB::Open(options, dbname, &db);
  1179. ASSERT_OK(s);
  1180. ASSERT_TRUE(db != nullptr);
  1181. s = db->Close();
  1182. ASSERT_EQ(s, Status::OK());
  1183. delete db;
  1184. ASSERT_EQ(env->GetCloseCount(), 3);
  1185. options.info_log.reset();
  1186. ASSERT_EQ(env->GetCloseCount(), 4);
  1187. }
  1188. TEST_F(DBBasicTest, DBCloseAllDirectoryFDs) {
  1189. Options options = GetDefaultOptions();
  1190. std::string dbname = test::PerThreadDBPath("db_close_all_dir_fds_test");
  1191. // Configure a specific WAL directory
  1192. options.wal_dir = dbname + "_wal_dir";
  1193. // Configure 3 different data directories
  1194. options.db_paths.emplace_back(dbname + "_1", 512 * 1024);
  1195. options.db_paths.emplace_back(dbname + "_2", 4 * 1024 * 1024);
  1196. options.db_paths.emplace_back(dbname + "_3", 1024 * 1024 * 1024);
  1197. ASSERT_OK(DestroyDB(dbname, options));
  1198. DB* db = nullptr;
  1199. std::unique_ptr<Env> env = NewCompositeEnv(
  1200. std::make_shared<CountedFileSystem>(FileSystem::Default()));
  1201. options.create_if_missing = true;
  1202. options.env = env.get();
  1203. Status s = DB::Open(options, dbname, &db);
  1204. ASSERT_OK(s);
  1205. ASSERT_TRUE(db != nullptr);
  1206. // Explicitly close the database to ensure the open and close counter for
  1207. // directories are equivalent
  1208. s = db->Close();
  1209. auto* counted_fs =
  1210. options.env->GetFileSystem()->CheckedCast<CountedFileSystem>();
  1211. ASSERT_TRUE(counted_fs != nullptr);
  1212. ASSERT_EQ(counted_fs->counters()->dir_opens,
  1213. counted_fs->counters()->dir_closes);
  1214. ASSERT_OK(s);
  1215. delete db;
  1216. }
  1217. TEST_F(DBBasicTest, DBCloseFlushError) {
  1218. std::unique_ptr<FaultInjectionTestEnv> fault_injection_env(
  1219. new FaultInjectionTestEnv(env_));
  1220. Options options = GetDefaultOptions();
  1221. options.create_if_missing = true;
  1222. options.manual_wal_flush = true;
  1223. options.write_buffer_size = 100;
  1224. options.env = fault_injection_env.get();
  1225. Reopen(options);
  1226. ASSERT_OK(Put("key1", "value1"));
  1227. ASSERT_OK(Put("key2", "value2"));
  1228. ASSERT_OK(dbfull()->TEST_SwitchMemtable());
  1229. ASSERT_OK(Put("key3", "value3"));
  1230. fault_injection_env->SetFilesystemActive(false);
  1231. Status s = dbfull()->Close();
  1232. ASSERT_NE(s, Status::OK());
  1233. // retry should return the same error
  1234. s = dbfull()->Close();
  1235. ASSERT_NE(s, Status::OK());
  1236. fault_injection_env->SetFilesystemActive(true);
  1237. // retry close() is no-op even the system is back. Could be improved if
  1238. // Close() is retry-able: #9029
  1239. s = dbfull()->Close();
  1240. ASSERT_NE(s, Status::OK());
  1241. Destroy(options);
  1242. }
  1243. class DBMultiGetTestWithParam
  1244. : public DBBasicTest,
  1245. public testing::WithParamInterface<std::tuple<bool, bool>> {};
  1246. TEST_P(DBMultiGetTestWithParam, MultiGetMultiCF) {
  1247. #ifndef USE_COROUTINES
  1248. if (std::get<1>(GetParam())) {
  1249. ROCKSDB_GTEST_SKIP("This test requires coroutine support");
  1250. return;
  1251. }
  1252. #endif // USE_COROUTINES
  1253. Options options = CurrentOptions();
  1254. CreateAndReopenWithCF({"pikachu", "ilya", "muromec", "dobrynia", "nikitich",
  1255. "alyosha", "popovich"},
  1256. options);
  1257. // <CF, key, value> tuples
  1258. std::vector<std::tuple<int, std::string, std::string>> cf_kv_vec;
  1259. static const int num_keys = 24;
  1260. cf_kv_vec.reserve(num_keys);
  1261. for (int i = 0; i < num_keys; ++i) {
  1262. int cf = i / 3;
  1263. int cf_key = 1 % 3;
  1264. cf_kv_vec.emplace_back(
  1265. cf, "cf" + std::to_string(cf) + "_key_" + std::to_string(cf_key),
  1266. "cf" + std::to_string(cf) + "_val_" + std::to_string(cf_key));
  1267. ASSERT_OK(Put(std::get<0>(cf_kv_vec[i]), std::get<1>(cf_kv_vec[i]),
  1268. std::get<2>(cf_kv_vec[i])));
  1269. }
  1270. int get_sv_count = 0;
  1271. ROCKSDB_NAMESPACE::DBImpl* db = static_cast_with_check<DBImpl>(db_);
  1272. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1273. "DBImpl::MultiCFSnapshot::AfterRefSV", [&](void* /*arg*/) {
  1274. if (++get_sv_count == 2) {
  1275. // After MultiGet refs a couple of CFs, flush all CFs so MultiGet
  1276. // is forced to repeat the process
  1277. for (int i = 0; i < num_keys; ++i) {
  1278. int cf = i / 3;
  1279. int cf_key = i % 8;
  1280. if (cf_key == 0) {
  1281. ASSERT_OK(Flush(cf));
  1282. }
  1283. ASSERT_OK(Put(std::get<0>(cf_kv_vec[i]), std::get<1>(cf_kv_vec[i]),
  1284. std::get<2>(cf_kv_vec[i]) + "_2"));
  1285. }
  1286. }
  1287. if (get_sv_count == 11) {
  1288. for (int i = 0; i < 8; ++i) {
  1289. auto* cfd = static_cast_with_check<ColumnFamilyHandleImpl>(
  1290. db->GetColumnFamilyHandle(i))
  1291. ->cfd();
  1292. ASSERT_EQ(cfd->TEST_GetLocalSV()->Get(), SuperVersion::kSVInUse);
  1293. }
  1294. }
  1295. });
  1296. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1297. std::vector<int> cfs;
  1298. std::vector<std::string> keys;
  1299. std::vector<std::string> values;
  1300. for (int i = 0; i < num_keys; ++i) {
  1301. cfs.push_back(std::get<0>(cf_kv_vec[i]));
  1302. keys.push_back(std::get<1>(cf_kv_vec[i]));
  1303. }
  1304. values = MultiGet(cfs, keys, nullptr, std::get<0>(GetParam()),
  1305. std::get<1>(GetParam()));
  1306. ASSERT_EQ(values.size(), num_keys);
  1307. for (unsigned int j = 0; j < values.size(); ++j) {
  1308. ASSERT_EQ(values[j], std::get<2>(cf_kv_vec[j]) + "_2");
  1309. }
  1310. keys.clear();
  1311. cfs.clear();
  1312. cfs.push_back(std::get<0>(cf_kv_vec[0]));
  1313. keys.push_back(std::get<1>(cf_kv_vec[0]));
  1314. cfs.push_back(std::get<0>(cf_kv_vec[3]));
  1315. keys.push_back(std::get<1>(cf_kv_vec[3]));
  1316. cfs.push_back(std::get<0>(cf_kv_vec[4]));
  1317. keys.push_back(std::get<1>(cf_kv_vec[4]));
  1318. values = MultiGet(cfs, keys, nullptr, std::get<0>(GetParam()),
  1319. std::get<1>(GetParam()));
  1320. ASSERT_EQ(values[0], std::get<2>(cf_kv_vec[0]) + "_2");
  1321. ASSERT_EQ(values[1], std::get<2>(cf_kv_vec[3]) + "_2");
  1322. ASSERT_EQ(values[2], std::get<2>(cf_kv_vec[4]) + "_2");
  1323. keys.clear();
  1324. cfs.clear();
  1325. cfs.push_back(std::get<0>(cf_kv_vec[7]));
  1326. keys.push_back(std::get<1>(cf_kv_vec[7]));
  1327. cfs.push_back(std::get<0>(cf_kv_vec[6]));
  1328. keys.push_back(std::get<1>(cf_kv_vec[6]));
  1329. cfs.push_back(std::get<0>(cf_kv_vec[1]));
  1330. keys.push_back(std::get<1>(cf_kv_vec[1]));
  1331. values = MultiGet(cfs, keys, nullptr, std::get<0>(GetParam()),
  1332. std::get<1>(GetParam()));
  1333. ASSERT_EQ(values[0], std::get<2>(cf_kv_vec[7]) + "_2");
  1334. ASSERT_EQ(values[1], std::get<2>(cf_kv_vec[6]) + "_2");
  1335. ASSERT_EQ(values[2], std::get<2>(cf_kv_vec[1]) + "_2");
  1336. for (int cf = 0; cf < 8; ++cf) {
  1337. auto* cfd =
  1338. static_cast_with_check<ColumnFamilyHandleImpl>(
  1339. static_cast_with_check<DBImpl>(db_)->GetColumnFamilyHandle(cf))
  1340. ->cfd();
  1341. ASSERT_NE(cfd->TEST_GetLocalSV()->Get(), SuperVersion::kSVInUse);
  1342. ASSERT_NE(cfd->TEST_GetLocalSV()->Get(), SuperVersion::kSVObsolete);
  1343. }
  1344. }
  1345. TEST_P(DBMultiGetTestWithParam, MultiGetMultiCFMutex) {
  1346. #ifndef USE_COROUTINES
  1347. if (std::get<1>(GetParam())) {
  1348. ROCKSDB_GTEST_SKIP("This test requires coroutine support");
  1349. return;
  1350. }
  1351. #endif // USE_COROUTINES
  1352. Options options = CurrentOptions();
  1353. CreateAndReopenWithCF({"pikachu", "ilya", "muromec", "dobrynia", "nikitich",
  1354. "alyosha", "popovich"},
  1355. options);
  1356. for (int i = 0; i < 8; ++i) {
  1357. ASSERT_OK(Put(i, "cf" + std::to_string(i) + "_key",
  1358. "cf" + std::to_string(i) + "_val"));
  1359. }
  1360. int get_sv_count = 0;
  1361. int retries = 0;
  1362. bool last_try = false;
  1363. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1364. "DBImpl::MultiCFSnapshot::LastTry",
  1365. [&](void* /*arg*/) { last_try = true; });
  1366. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1367. "DBImpl::MultiCFSnapshot::AfterRefSV", [&](void* /*arg*/) {
  1368. if (last_try) {
  1369. return;
  1370. }
  1371. if (++get_sv_count == 2) {
  1372. ++retries;
  1373. get_sv_count = 0;
  1374. for (int i = 0; i < 8; ++i) {
  1375. ASSERT_OK(Flush(i));
  1376. ASSERT_OK(Put(
  1377. i, "cf" + std::to_string(i) + "_key",
  1378. "cf" + std::to_string(i) + "_val" + std::to_string(retries)));
  1379. }
  1380. }
  1381. });
  1382. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  1383. {"DBImpl::MultiCFSnapshot::AfterLastTryRefSV",
  1384. "DBMultiGetTestWithParam::MultiGetMultiCFMutex:BeforeCreateSV"},
  1385. {"DBMultiGetTestWithParam::MultiGetMultiCFMutex:AfterCreateSV",
  1386. "DBImpl::MultiCFSnapshot::BeforeLastTryUnRefSV"},
  1387. });
  1388. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1389. port::Thread create_sv_thread([this]() {
  1390. TEST_SYNC_POINT(
  1391. "DBMultiGetTestWithParam::MultiGetMultiCFMutex:BeforeCreateSV");
  1392. // Create a new SuperVersion for each column family after last_try
  1393. // of MultiGet ref SuperVersion and before unref it.
  1394. for (int i = 0; i < 8; ++i) {
  1395. ASSERT_OK(Put(i, "cf" + std::to_string(i) + "_key",
  1396. "cf" + std::to_string(i) + "_val_after_last_try"));
  1397. ASSERT_OK(Flush(i));
  1398. }
  1399. TEST_SYNC_POINT(
  1400. "DBMultiGetTestWithParam::MultiGetMultiCFMutex:AfterCreateSV");
  1401. });
  1402. std::vector<int> cfs;
  1403. std::vector<std::string> keys;
  1404. std::vector<std::string> values;
  1405. for (int i = 0; i < 8; ++i) {
  1406. cfs.push_back(i);
  1407. keys.push_back("cf" + std::to_string(i) + "_key");
  1408. }
  1409. values = MultiGet(cfs, keys, nullptr, std::get<0>(GetParam()),
  1410. std::get<1>(GetParam()));
  1411. create_sv_thread.join();
  1412. ASSERT_TRUE(last_try);
  1413. ASSERT_EQ(values.size(), 8);
  1414. for (unsigned int j = 0; j < values.size(); ++j) {
  1415. ASSERT_EQ(values[j],
  1416. "cf" + std::to_string(j) + "_val" + std::to_string(retries));
  1417. }
  1418. for (int i = 0; i < 8; ++i) {
  1419. auto* cfd =
  1420. static_cast_with_check<ColumnFamilyHandleImpl>(
  1421. static_cast_with_check<DBImpl>(db_)->GetColumnFamilyHandle(i))
  1422. ->cfd();
  1423. ASSERT_NE(cfd->TEST_GetLocalSV()->Get(), SuperVersion::kSVInUse);
  1424. }
  1425. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1426. }
  1427. TEST_P(DBMultiGetTestWithParam, MultiGetMultiCFSnapshot) {
  1428. #ifndef USE_COROUTINES
  1429. if (std::get<1>(GetParam())) {
  1430. ROCKSDB_GTEST_SKIP("This test requires coroutine support");
  1431. return;
  1432. }
  1433. #endif // USE_COROUTINES
  1434. Options options = CurrentOptions();
  1435. CreateAndReopenWithCF({"pikachu", "ilya", "muromec", "dobrynia", "nikitich",
  1436. "alyosha", "popovich"},
  1437. options);
  1438. for (int i = 0; i < 8; ++i) {
  1439. ASSERT_OK(Put(i, "cf" + std::to_string(i) + "_key",
  1440. "cf" + std::to_string(i) + "_val"));
  1441. }
  1442. int get_sv_count = 0;
  1443. ROCKSDB_NAMESPACE::DBImpl* db = static_cast_with_check<DBImpl>(db_);
  1444. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1445. "DBImpl::MultiCFSnapshot::AfterRefSV", [&](void* /*arg*/) {
  1446. if (++get_sv_count == 2) {
  1447. for (int i = 0; i < 8; ++i) {
  1448. ASSERT_OK(Flush(i));
  1449. ASSERT_OK(Put(i, "cf" + std::to_string(i) + "_key",
  1450. "cf" + std::to_string(i) + "_val2"));
  1451. }
  1452. }
  1453. if (get_sv_count == 8) {
  1454. for (int i = 0; i < 8; ++i) {
  1455. auto* cfd = static_cast_with_check<ColumnFamilyHandleImpl>(
  1456. db->GetColumnFamilyHandle(i))
  1457. ->cfd();
  1458. ASSERT_TRUE(
  1459. (cfd->TEST_GetLocalSV()->Get() == SuperVersion::kSVInUse) ||
  1460. (cfd->TEST_GetLocalSV()->Get() == SuperVersion::kSVObsolete));
  1461. }
  1462. }
  1463. });
  1464. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1465. std::vector<int> cfs;
  1466. std::vector<std::string> keys;
  1467. std::vector<std::string> values;
  1468. for (int i = 0; i < 8; ++i) {
  1469. cfs.push_back(i);
  1470. keys.push_back("cf" + std::to_string(i) + "_key");
  1471. }
  1472. const Snapshot* snapshot = db_->GetSnapshot();
  1473. values = MultiGet(cfs, keys, snapshot, std::get<0>(GetParam()),
  1474. std::get<1>(GetParam()));
  1475. db_->ReleaseSnapshot(snapshot);
  1476. ASSERT_EQ(values.size(), 8);
  1477. for (unsigned int j = 0; j < values.size(); ++j) {
  1478. ASSERT_EQ(values[j], "cf" + std::to_string(j) + "_val");
  1479. }
  1480. for (int i = 0; i < 8; ++i) {
  1481. auto* cfd =
  1482. static_cast_with_check<ColumnFamilyHandleImpl>(
  1483. static_cast_with_check<DBImpl>(db_)->GetColumnFamilyHandle(i))
  1484. ->cfd();
  1485. ASSERT_NE(cfd->TEST_GetLocalSV()->Get(), SuperVersion::kSVInUse);
  1486. }
  1487. }
  1488. TEST_P(DBMultiGetTestWithParam, MultiGetMultiCFUnsorted) {
  1489. #ifndef USE_COROUTINES
  1490. if (std::get<1>(GetParam())) {
  1491. ROCKSDB_GTEST_SKIP("This test requires coroutine support");
  1492. return;
  1493. }
  1494. #endif // USE_COROUTINES
  1495. Options options = CurrentOptions();
  1496. CreateAndReopenWithCF({"one", "two"}, options);
  1497. ASSERT_OK(Put(1, "foo", "bar"));
  1498. ASSERT_OK(Put(2, "baz", "xyz"));
  1499. ASSERT_OK(Put(1, "abc", "def"));
  1500. // Note: keys for the same CF do not form a consecutive range
  1501. std::vector<int> cfs{1, 2, 1};
  1502. std::vector<std::string> keys{"foo", "baz", "abc"};
  1503. std::vector<std::string> values;
  1504. values = MultiGet(cfs, keys, /* snapshot */ nullptr,
  1505. /* batched */ std::get<0>(GetParam()),
  1506. /* async */ std::get<1>(GetParam()));
  1507. ASSERT_EQ(values.size(), 3);
  1508. ASSERT_EQ(values[0], "bar");
  1509. ASSERT_EQ(values[1], "xyz");
  1510. ASSERT_EQ(values[2], "def");
  1511. }
  1512. TEST_P(DBMultiGetTestWithParam, MultiGetBatchedSimpleUnsorted) {
  1513. #ifndef USE_COROUTINES
  1514. if (std::get<1>(GetParam())) {
  1515. ROCKSDB_GTEST_SKIP("This test requires coroutine support");
  1516. return;
  1517. }
  1518. #endif // USE_COROUTINES
  1519. // Skip for unbatched MultiGet
  1520. if (!std::get<0>(GetParam())) {
  1521. ROCKSDB_GTEST_BYPASS("This test is only for batched MultiGet");
  1522. return;
  1523. }
  1524. do {
  1525. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  1526. SetPerfLevel(kEnableCount);
  1527. ASSERT_OK(Put(1, "k1", "v1"));
  1528. ASSERT_OK(Put(1, "k2", "v2"));
  1529. ASSERT_OK(Put(1, "k3", "v3"));
  1530. ASSERT_OK(Put(1, "k4", "v4"));
  1531. ASSERT_OK(Delete(1, "k4"));
  1532. ASSERT_OK(Put(1, "k5", "v5"));
  1533. ASSERT_OK(Delete(1, "no_key"));
  1534. get_perf_context()->Reset();
  1535. std::vector<Slice> keys({"no_key", "k5", "k4", "k3", "k2", "k1"});
  1536. std::vector<PinnableSlice> values(keys.size());
  1537. std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
  1538. std::vector<Status> s(keys.size());
  1539. ReadOptions ro;
  1540. ro.async_io = std::get<1>(GetParam());
  1541. db_->MultiGet(ro, handles_[1], keys.size(), keys.data(), values.data(),
  1542. s.data(), false);
  1543. ASSERT_EQ(values.size(), keys.size());
  1544. ASSERT_EQ(std::string(values[5].data(), values[5].size()), "v1");
  1545. ASSERT_EQ(std::string(values[4].data(), values[4].size()), "v2");
  1546. ASSERT_EQ(std::string(values[3].data(), values[3].size()), "v3");
  1547. ASSERT_EQ(std::string(values[1].data(), values[1].size()), "v5");
  1548. // four kv pairs * two bytes per value
  1549. ASSERT_EQ(8, (int)get_perf_context()->multiget_read_bytes);
  1550. ASSERT_TRUE(s[0].IsNotFound());
  1551. ASSERT_OK(s[1]);
  1552. ASSERT_TRUE(s[2].IsNotFound());
  1553. ASSERT_OK(s[3]);
  1554. ASSERT_OK(s[4]);
  1555. ASSERT_OK(s[5]);
  1556. SetPerfLevel(kDisable);
  1557. } while (ChangeCompactOptions());
  1558. }
  1559. TEST_P(DBMultiGetTestWithParam, MultiGetBatchedSortedMultiFile) {
  1560. #ifndef USE_COROUTINES
  1561. if (std::get<1>(GetParam())) {
  1562. ROCKSDB_GTEST_SKIP("This test requires coroutine support");
  1563. return;
  1564. }
  1565. #endif // USE_COROUTINES
  1566. // Skip for unbatched MultiGet
  1567. if (!std::get<0>(GetParam())) {
  1568. ROCKSDB_GTEST_BYPASS("This test is only for batched MultiGet");
  1569. return;
  1570. }
  1571. do {
  1572. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  1573. SetPerfLevel(kEnableCount);
  1574. // To expand the power of this test, generate > 1 table file and
  1575. // mix with memtable
  1576. ASSERT_OK(Put(1, "k1", "v1"));
  1577. ASSERT_OK(Put(1, "k2", "v2"));
  1578. ASSERT_OK(Flush(1));
  1579. ASSERT_OK(Put(1, "k3", "v3"));
  1580. ASSERT_OK(Put(1, "k4", "v4"));
  1581. ASSERT_OK(Flush(1));
  1582. ASSERT_OK(Delete(1, "k4"));
  1583. ASSERT_OK(Put(1, "k5", "v5"));
  1584. ASSERT_OK(Delete(1, "no_key"));
  1585. get_perf_context()->Reset();
  1586. std::vector<Slice> keys({"k1", "k2", "k3", "k4", "k5", "no_key"});
  1587. std::vector<PinnableSlice> values(keys.size());
  1588. std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
  1589. std::vector<Status> s(keys.size());
  1590. ReadOptions ro;
  1591. ro.async_io = std::get<1>(GetParam());
  1592. db_->MultiGet(ro, handles_[1], keys.size(), keys.data(), values.data(),
  1593. s.data(), true);
  1594. ASSERT_EQ(values.size(), keys.size());
  1595. ASSERT_EQ(std::string(values[0].data(), values[0].size()), "v1");
  1596. ASSERT_EQ(std::string(values[1].data(), values[1].size()), "v2");
  1597. ASSERT_EQ(std::string(values[2].data(), values[2].size()), "v3");
  1598. ASSERT_EQ(std::string(values[4].data(), values[4].size()), "v5");
  1599. // four kv pairs * two bytes per value
  1600. ASSERT_EQ(8, (int)get_perf_context()->multiget_read_bytes);
  1601. ASSERT_OK(s[0]);
  1602. ASSERT_OK(s[1]);
  1603. ASSERT_OK(s[2]);
  1604. ASSERT_TRUE(s[3].IsNotFound());
  1605. ASSERT_OK(s[4]);
  1606. ASSERT_TRUE(s[5].IsNotFound());
  1607. SetPerfLevel(kDisable);
  1608. } while (ChangeOptions());
  1609. }
  1610. TEST_P(DBMultiGetTestWithParam, MultiGetBatchedDuplicateKeys) {
  1611. #ifndef USE_COROUTINES
  1612. if (std::get<1>(GetParam())) {
  1613. ROCKSDB_GTEST_SKIP("This test requires coroutine support");
  1614. return;
  1615. }
  1616. #endif // USE_COROUTINES
  1617. // Skip for unbatched MultiGet
  1618. if (!std::get<0>(GetParam())) {
  1619. ROCKSDB_GTEST_BYPASS("This test is only for batched MultiGet");
  1620. return;
  1621. }
  1622. Options opts = CurrentOptions();
  1623. opts.merge_operator = MergeOperators::CreateStringAppendOperator();
  1624. CreateAndReopenWithCF({"pikachu"}, opts);
  1625. SetPerfLevel(kEnableCount);
  1626. // To expand the power of this test, generate > 1 table file and
  1627. // mix with memtable
  1628. ASSERT_OK(Merge(1, "k1", "v1"));
  1629. ASSERT_OK(Merge(1, "k2", "v2"));
  1630. ASSERT_OK(Flush(1));
  1631. MoveFilesToLevel(2, 1);
  1632. ASSERT_OK(Merge(1, "k3", "v3"));
  1633. ASSERT_OK(Merge(1, "k4", "v4"));
  1634. ASSERT_OK(Flush(1));
  1635. MoveFilesToLevel(2, 1);
  1636. ASSERT_OK(Merge(1, "k4", "v4_2"));
  1637. ASSERT_OK(Merge(1, "k6", "v6"));
  1638. ASSERT_OK(Flush(1));
  1639. MoveFilesToLevel(2, 1);
  1640. ASSERT_OK(Merge(1, "k7", "v7"));
  1641. ASSERT_OK(Merge(1, "k8", "v8"));
  1642. ASSERT_OK(Flush(1));
  1643. MoveFilesToLevel(2, 1);
  1644. get_perf_context()->Reset();
  1645. std::vector<Slice> keys({"k8", "k8", "k8", "k4", "k4", "k1", "k3"});
  1646. std::vector<PinnableSlice> values(keys.size());
  1647. std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
  1648. std::vector<Status> s(keys.size());
  1649. ReadOptions ro;
  1650. ro.async_io = std::get<1>(GetParam());
  1651. db_->MultiGet(ro, handles_[1], keys.size(), keys.data(), values.data(),
  1652. s.data(), false);
  1653. ASSERT_EQ(values.size(), keys.size());
  1654. ASSERT_EQ(std::string(values[0].data(), values[0].size()), "v8");
  1655. ASSERT_EQ(std::string(values[1].data(), values[1].size()), "v8");
  1656. ASSERT_EQ(std::string(values[2].data(), values[2].size()), "v8");
  1657. ASSERT_EQ(std::string(values[3].data(), values[3].size()), "v4,v4_2");
  1658. ASSERT_EQ(std::string(values[4].data(), values[4].size()), "v4,v4_2");
  1659. ASSERT_EQ(std::string(values[5].data(), values[5].size()), "v1");
  1660. ASSERT_EQ(std::string(values[6].data(), values[6].size()), "v3");
  1661. ASSERT_EQ(24, (int)get_perf_context()->multiget_read_bytes);
  1662. for (Status& status : s) {
  1663. ASSERT_OK(status);
  1664. }
  1665. SetPerfLevel(kDisable);
  1666. }
  1667. TEST_P(DBMultiGetTestWithParam, MultiGetBatchedMultiLevel) {
  1668. #ifndef USE_COROUTINES
  1669. if (std::get<1>(GetParam())) {
  1670. ROCKSDB_GTEST_SKIP("This test requires coroutine support");
  1671. return;
  1672. }
  1673. #endif // USE_COROUTINES
  1674. // Skip for unbatched MultiGet
  1675. if (!std::get<0>(GetParam())) {
  1676. ROCKSDB_GTEST_BYPASS("This test is only for batched MultiGet");
  1677. return;
  1678. }
  1679. Options options = CurrentOptions();
  1680. options.disable_auto_compactions = true;
  1681. Reopen(options);
  1682. int num_keys = 0;
  1683. for (int i = 0; i < 128; ++i) {
  1684. ASSERT_OK(Put("key_" + std::to_string(i), "val_l2_" + std::to_string(i)));
  1685. num_keys++;
  1686. if (num_keys == 8) {
  1687. ASSERT_OK(Flush());
  1688. num_keys = 0;
  1689. }
  1690. }
  1691. if (num_keys > 0) {
  1692. ASSERT_OK(Flush());
  1693. num_keys = 0;
  1694. }
  1695. MoveFilesToLevel(2);
  1696. for (int i = 0; i < 128; i += 3) {
  1697. ASSERT_OK(Put("key_" + std::to_string(i), "val_l1_" + std::to_string(i)));
  1698. num_keys++;
  1699. if (num_keys == 8) {
  1700. ASSERT_OK(Flush());
  1701. num_keys = 0;
  1702. }
  1703. }
  1704. if (num_keys > 0) {
  1705. ASSERT_OK(Flush());
  1706. num_keys = 0;
  1707. }
  1708. MoveFilesToLevel(1);
  1709. for (int i = 0; i < 128; i += 5) {
  1710. ASSERT_OK(Put("key_" + std::to_string(i), "val_l0_" + std::to_string(i)));
  1711. num_keys++;
  1712. if (num_keys == 8) {
  1713. ASSERT_OK(Flush());
  1714. num_keys = 0;
  1715. }
  1716. }
  1717. if (num_keys > 0) {
  1718. ASSERT_OK(Flush());
  1719. num_keys = 0;
  1720. }
  1721. ASSERT_EQ(0, num_keys);
  1722. for (int i = 0; i < 128; i += 9) {
  1723. ASSERT_OK(Put("key_" + std::to_string(i), "val_mem_" + std::to_string(i)));
  1724. }
  1725. std::vector<std::string> keys;
  1726. std::vector<std::string> values;
  1727. for (int i = 64; i < 80; ++i) {
  1728. keys.push_back("key_" + std::to_string(i));
  1729. }
  1730. values = MultiGet(keys, nullptr, std::get<1>(GetParam()));
  1731. ASSERT_EQ(values.size(), 16);
  1732. for (unsigned int j = 0; j < values.size(); ++j) {
  1733. int key = j + 64;
  1734. if (key % 9 == 0) {
  1735. ASSERT_EQ(values[j], "val_mem_" + std::to_string(key));
  1736. } else if (key % 5 == 0) {
  1737. ASSERT_EQ(values[j], "val_l0_" + std::to_string(key));
  1738. } else if (key % 3 == 0) {
  1739. ASSERT_EQ(values[j], "val_l1_" + std::to_string(key));
  1740. } else {
  1741. ASSERT_EQ(values[j], "val_l2_" + std::to_string(key));
  1742. }
  1743. }
  1744. }
  1745. TEST_P(DBMultiGetTestWithParam, MultiGetDuplicatesEmptyLevel) {
  1746. #ifndef USE_COROUTINES
  1747. if (std::get<1>(GetParam())) {
  1748. ROCKSDB_GTEST_BYPASS("This test requires coroutine support");
  1749. return;
  1750. }
  1751. #endif // USE_COROUTINES
  1752. // Skip for unbatched MultiGet
  1753. if (!std::get<0>(GetParam())) {
  1754. ROCKSDB_GTEST_BYPASS("This test is only for batched MultiGet");
  1755. return;
  1756. }
  1757. std::shared_ptr<FaultInjectionTestFS> fault_fs(
  1758. new FaultInjectionTestFS(env_->GetFileSystem()));
  1759. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fault_fs));
  1760. Options options = CurrentOptions();
  1761. options.env = env.get();
  1762. options.disable_auto_compactions = true;
  1763. options.merge_operator = MergeOperators::CreateStringAppendOperator();
  1764. LRUCacheOptions cache_opts;
  1765. cache_opts.capacity = 1 << 20;
  1766. BlockBasedTableOptions table_opts;
  1767. table_opts.metadata_cache_options.top_level_index_pinning = PinningTier::kAll;
  1768. table_opts.metadata_cache_options.partition_pinning = PinningTier::kNone;
  1769. table_opts.index_type =
  1770. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch;
  1771. table_opts.cache_index_and_filter_blocks = true;
  1772. table_opts.block_cache = cache_opts.MakeSharedCache();
  1773. table_opts.flush_block_policy_factory.reset(new MyFlushBlockPolicyFactory(1));
  1774. options.table_factory.reset(new BlockBasedTableFactory(table_opts));
  1775. Reopen(options);
  1776. int key;
  1777. // Setup the LSM so that the following search bounds are generated for
  1778. // key 9 for each level -
  1779. // Level 1 - lb = 0, rb = max
  1780. // Level 2 - lb = 0, rb = 0
  1781. // Level 3 - lb = 0, rb = -1
  1782. // Level 4 - lb = 0, rb = 0
  1783. key = 9;
  1784. ASSERT_OK(Put("key_" + std::to_string(key), "val_l2_" + std::to_string(key)));
  1785. ASSERT_OK(Flush());
  1786. MoveFilesToLevel(4);
  1787. key = 5;
  1788. ASSERT_OK(Put("key_" + std::to_string(key), "val_l2_" + std::to_string(key)));
  1789. key = 9;
  1790. ASSERT_OK(
  1791. Merge("key_" + std::to_string(key), "val_l2_" + std::to_string(key)));
  1792. const Snapshot* snap = dbfull()->GetSnapshot();
  1793. ASSERT_OK(
  1794. Merge("key_" + std::to_string(key), "val_l2_ext_" + std::to_string(key)));
  1795. ASSERT_OK(Flush());
  1796. // Leave level 3 empty
  1797. MoveFilesToLevel(2);
  1798. key = 2;
  1799. ASSERT_OK(Put("key_" + std::to_string(key), "val_l2_" + std::to_string(key)));
  1800. key = 6;
  1801. ASSERT_OK(
  1802. Merge("key_" + std::to_string(key), "val_l2_" + std::to_string(key)));
  1803. ASSERT_OK(Flush());
  1804. MoveFilesToLevel(1);
  1805. std::vector<std::string> keys;
  1806. std::vector<std::string> values;
  1807. keys.push_back("key_" + std::to_string(9));
  1808. keys.push_back("key_" + std::to_string(9));
  1809. int num_reads = 0;
  1810. SyncPoint::GetInstance()->SetCallBack(
  1811. "FaultInjectionTestFS::RandomRead", [&](void*) {
  1812. ++num_reads;
  1813. // Fail on the 2nd read. First read is index partition,
  1814. // second read is data block in level 1
  1815. if (num_reads == 2) {
  1816. fault_fs->SetFilesystemActive(false);
  1817. } else {
  1818. fault_fs->SetFilesystemActive(true);
  1819. }
  1820. });
  1821. SyncPoint::GetInstance()->EnableProcessing();
  1822. size_t capacity = table_opts.block_cache->GetCapacity();
  1823. table_opts.block_cache->SetCapacity(0);
  1824. table_opts.block_cache->SetCapacity(capacity);
  1825. values = MultiGet(keys, nullptr, std::get<1>(GetParam()));
  1826. ASSERT_EQ(values.size(), 2);
  1827. SyncPoint::GetInstance()->DisableProcessing();
  1828. dbfull()->ReleaseSnapshot(snap);
  1829. Destroy(options);
  1830. }
  1831. TEST_P(DBMultiGetTestWithParam, MultiGetDuplicatesNonEmptyLevel) {
  1832. #ifndef USE_COROUTINES
  1833. if (std::get<1>(GetParam())) {
  1834. ROCKSDB_GTEST_BYPASS("This test requires coroutine support");
  1835. return;
  1836. }
  1837. #endif // USE_COROUTINES
  1838. // Skip for unbatched MultiGet
  1839. if (!std::get<0>(GetParam())) {
  1840. ROCKSDB_GTEST_BYPASS("This test is only for batched MultiGet");
  1841. return;
  1842. }
  1843. std::shared_ptr<FaultInjectionTestFS> fault_fs(
  1844. new FaultInjectionTestFS(env_->GetFileSystem()));
  1845. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fault_fs));
  1846. Options options = CurrentOptions();
  1847. options.env = env.get();
  1848. options.disable_auto_compactions = true;
  1849. options.merge_operator = MergeOperators::CreateStringAppendOperator();
  1850. LRUCacheOptions cache_opts;
  1851. cache_opts.capacity = 1 << 20;
  1852. BlockBasedTableOptions table_opts;
  1853. table_opts.metadata_cache_options.top_level_index_pinning = PinningTier::kAll;
  1854. table_opts.metadata_cache_options.partition_pinning = PinningTier::kNone;
  1855. table_opts.index_type =
  1856. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch;
  1857. table_opts.cache_index_and_filter_blocks = true;
  1858. table_opts.block_cache = cache_opts.MakeSharedCache();
  1859. table_opts.flush_block_policy_factory.reset(new MyFlushBlockPolicyFactory(1));
  1860. options.table_factory.reset(new BlockBasedTableFactory(table_opts));
  1861. Reopen(options);
  1862. int key;
  1863. // Setup the LSM so that the following search bounds are generated for
  1864. // key 9 for each level -
  1865. // Level 1 - lb = 0, rb = max
  1866. // Level 2 - lb = 0, rb = 0
  1867. // Level 3 - lb = 0, rb = 1
  1868. // Level 4 - N/A
  1869. key = 8;
  1870. ASSERT_OK(Put("key_" + std::to_string(key), "val_l2_" + std::to_string(key)));
  1871. ASSERT_OK(Flush());
  1872. MoveFilesToLevel(4);
  1873. key = 7;
  1874. ASSERT_OK(Put("key_" + std::to_string(key), "val_l2_" + std::to_string(key)));
  1875. ASSERT_OK(Flush());
  1876. key = 9;
  1877. ASSERT_OK(Put("key_" + std::to_string(key), "val_l2_" + std::to_string(key)));
  1878. ASSERT_OK(Flush());
  1879. MoveFilesToLevel(3);
  1880. key = 5;
  1881. ASSERT_OK(Put("key_" + std::to_string(key), "val_l2_" + std::to_string(key)));
  1882. key = 9;
  1883. ASSERT_OK(
  1884. Merge("key_" + std::to_string(key), "merge1_l2_" + std::to_string(key)));
  1885. const Snapshot* snap = dbfull()->GetSnapshot();
  1886. ASSERT_OK(
  1887. Merge("key_" + std::to_string(key), "merge2_l2_" + std::to_string(key)));
  1888. ASSERT_OK(Flush());
  1889. MoveFilesToLevel(2);
  1890. key = 2;
  1891. ASSERT_OK(Put("key_" + std::to_string(key), "val_l2_" + std::to_string(key)));
  1892. key = 6;
  1893. ASSERT_OK(
  1894. Merge("key_" + std::to_string(key), "val_l2_" + std::to_string(key)));
  1895. ASSERT_OK(Flush());
  1896. MoveFilesToLevel(1);
  1897. std::vector<std::string> keys;
  1898. std::vector<std::string> values;
  1899. keys.push_back("key_" + std::to_string(9));
  1900. keys.push_back("key_" + std::to_string(9));
  1901. int num_reads = 0;
  1902. SyncPoint::GetInstance()->SetCallBack(
  1903. "FaultInjectionTestFS::RandomRead", [&](void*) {
  1904. ++num_reads;
  1905. // Fail on the 2nd read. First read is index partition,
  1906. // second read is data block in level 1
  1907. if (num_reads == 2) {
  1908. fault_fs->SetFilesystemActive(false);
  1909. } else {
  1910. fault_fs->SetFilesystemActive(true);
  1911. }
  1912. });
  1913. SyncPoint::GetInstance()->EnableProcessing();
  1914. size_t capacity = table_opts.block_cache->GetCapacity();
  1915. table_opts.block_cache->SetCapacity(0);
  1916. table_opts.block_cache->SetCapacity(capacity);
  1917. values = MultiGet(keys, nullptr, std::get<1>(GetParam()));
  1918. ASSERT_EQ(values.size(), 2);
  1919. ASSERT_EQ(values[0], "Corruption: Not active");
  1920. ASSERT_EQ(values[1], "val_l2_9,merge1_l2_9,merge2_l2_9");
  1921. SyncPoint::GetInstance()->DisableProcessing();
  1922. dbfull()->ReleaseSnapshot(snap);
  1923. Destroy(options);
  1924. }
  1925. TEST_P(DBMultiGetTestWithParam, MultiGetBatchedMultiLevelMerge) {
  1926. #ifndef USE_COROUTINES
  1927. if (std::get<1>(GetParam())) {
  1928. ROCKSDB_GTEST_SKIP("This test requires coroutine support");
  1929. return;
  1930. }
  1931. #endif // USE_COROUTINES
  1932. // Skip for unbatched MultiGet
  1933. if (!std::get<0>(GetParam())) {
  1934. ROCKSDB_GTEST_BYPASS("This test is only for batched MultiGet");
  1935. return;
  1936. }
  1937. Options options = CurrentOptions();
  1938. options.disable_auto_compactions = true;
  1939. options.merge_operator = MergeOperators::CreateStringAppendOperator();
  1940. BlockBasedTableOptions bbto;
  1941. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  1942. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  1943. Reopen(options);
  1944. int num_keys = 0;
  1945. for (int i = 0; i < 128; ++i) {
  1946. ASSERT_OK(Put("key_" + std::to_string(i), "val_l2_" + std::to_string(i)));
  1947. num_keys++;
  1948. if (num_keys == 8) {
  1949. ASSERT_OK(Flush());
  1950. num_keys = 0;
  1951. }
  1952. }
  1953. if (num_keys > 0) {
  1954. ASSERT_OK(Flush());
  1955. num_keys = 0;
  1956. }
  1957. MoveFilesToLevel(2);
  1958. for (int i = 0; i < 128; i += 3) {
  1959. ASSERT_OK(Merge("key_" + std::to_string(i), "val_l1_" + std::to_string(i)));
  1960. num_keys++;
  1961. if (num_keys == 8) {
  1962. ASSERT_OK(Flush());
  1963. num_keys = 0;
  1964. }
  1965. }
  1966. if (num_keys > 0) {
  1967. ASSERT_OK(Flush());
  1968. num_keys = 0;
  1969. }
  1970. MoveFilesToLevel(1);
  1971. for (int i = 0; i < 128; i += 5) {
  1972. ASSERT_OK(Merge("key_" + std::to_string(i), "val_l0_" + std::to_string(i)));
  1973. num_keys++;
  1974. if (num_keys == 8) {
  1975. ASSERT_OK(Flush());
  1976. num_keys = 0;
  1977. }
  1978. }
  1979. if (num_keys > 0) {
  1980. ASSERT_OK(Flush());
  1981. num_keys = 0;
  1982. }
  1983. ASSERT_EQ(0, num_keys);
  1984. for (int i = 0; i < 128; i += 9) {
  1985. ASSERT_OK(
  1986. Merge("key_" + std::to_string(i), "val_mem_" + std::to_string(i)));
  1987. }
  1988. std::vector<std::string> keys;
  1989. std::vector<std::string> values;
  1990. for (int i = 32; i < 80; ++i) {
  1991. keys.push_back("key_" + std::to_string(i));
  1992. }
  1993. values = MultiGet(keys, nullptr, std::get<1>(GetParam()));
  1994. ASSERT_EQ(values.size(), keys.size());
  1995. for (unsigned int j = 0; j < 48; ++j) {
  1996. int key = j + 32;
  1997. std::string value;
  1998. value.append("val_l2_" + std::to_string(key));
  1999. if (key % 3 == 0) {
  2000. value.append(",");
  2001. value.append("val_l1_" + std::to_string(key));
  2002. }
  2003. if (key % 5 == 0) {
  2004. value.append(",");
  2005. value.append("val_l0_" + std::to_string(key));
  2006. }
  2007. if (key % 9 == 0) {
  2008. value.append(",");
  2009. value.append("val_mem_" + std::to_string(key));
  2010. }
  2011. ASSERT_EQ(values[j], value);
  2012. }
  2013. }
  2014. TEST_P(DBMultiGetTestWithParam, MultiGetBatchedValueSizeInMemory) {
  2015. #ifndef USE_COROUTINES
  2016. if (std::get<1>(GetParam())) {
  2017. ROCKSDB_GTEST_SKIP("This test requires coroutine support");
  2018. return;
  2019. }
  2020. #endif // USE_COROUTINES
  2021. // Skip for unbatched MultiGet
  2022. if (!std::get<0>(GetParam())) {
  2023. ROCKSDB_GTEST_BYPASS("This test is only for batched MultiGet");
  2024. return;
  2025. }
  2026. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  2027. SetPerfLevel(kEnableCount);
  2028. ASSERT_OK(Put(1, "k1", "v_1"));
  2029. ASSERT_OK(Put(1, "k2", "v_2"));
  2030. ASSERT_OK(Put(1, "k3", "v_3"));
  2031. ASSERT_OK(Put(1, "k4", "v_4"));
  2032. ASSERT_OK(Put(1, "k5", "v_5"));
  2033. ASSERT_OK(Put(1, "k6", "v_6"));
  2034. std::vector<Slice> keys = {"k1", "k2", "k3", "k4", "k5", "k6"};
  2035. std::vector<PinnableSlice> values(keys.size());
  2036. std::vector<Status> s(keys.size());
  2037. std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
  2038. get_perf_context()->Reset();
  2039. ReadOptions ro;
  2040. ro.value_size_soft_limit = 11;
  2041. ro.async_io = std::get<1>(GetParam());
  2042. db_->MultiGet(ro, handles_[1], keys.size(), keys.data(), values.data(),
  2043. s.data(), false);
  2044. ASSERT_EQ(values.size(), keys.size());
  2045. for (unsigned int i = 0; i < 4; i++) {
  2046. ASSERT_EQ(std::string(values[i].data(), values[i].size()),
  2047. "v_" + std::to_string(i + 1));
  2048. }
  2049. for (unsigned int i = 4; i < 6; i++) {
  2050. ASSERT_TRUE(s[i].IsAborted());
  2051. }
  2052. ASSERT_EQ(12, (int)get_perf_context()->multiget_read_bytes);
  2053. SetPerfLevel(kDisable);
  2054. }
  2055. TEST_P(DBMultiGetTestWithParam, MultiGetBatchedValueSize) {
  2056. #ifndef USE_COROUTINES
  2057. if (std::get<1>(GetParam())) {
  2058. ROCKSDB_GTEST_SKIP("This test requires coroutine support");
  2059. return;
  2060. }
  2061. #endif // USE_COROUTINES
  2062. // Skip for unbatched MultiGet
  2063. if (!std::get<0>(GetParam())) {
  2064. return;
  2065. }
  2066. do {
  2067. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  2068. SetPerfLevel(kEnableCount);
  2069. ASSERT_OK(Put(1, "k6", "v6"));
  2070. ASSERT_OK(Put(1, "k7", "v7_"));
  2071. ASSERT_OK(Put(1, "k3", "v3_"));
  2072. ASSERT_OK(Put(1, "k4", "v4"));
  2073. ASSERT_OK(Flush(1));
  2074. ASSERT_OK(Delete(1, "k4"));
  2075. ASSERT_OK(Put(1, "k11", "v11"));
  2076. ASSERT_OK(Delete(1, "no_key"));
  2077. ASSERT_OK(Put(1, "k8", "v8_"));
  2078. ASSERT_OK(Put(1, "k13", "v13"));
  2079. ASSERT_OK(Put(1, "k14", "v14"));
  2080. ASSERT_OK(Put(1, "k15", "v15"));
  2081. ASSERT_OK(Put(1, "k16", "v16"));
  2082. ASSERT_OK(Put(1, "k17", "v17"));
  2083. ASSERT_OK(Flush(1));
  2084. ASSERT_OK(Put(1, "k1", "v1_"));
  2085. ASSERT_OK(Put(1, "k2", "v2_"));
  2086. ASSERT_OK(Put(1, "k5", "v5_"));
  2087. ASSERT_OK(Put(1, "k9", "v9_"));
  2088. ASSERT_OK(Put(1, "k10", "v10"));
  2089. ASSERT_OK(Delete(1, "k2"));
  2090. ASSERT_OK(Delete(1, "k6"));
  2091. get_perf_context()->Reset();
  2092. std::vector<Slice> keys({"k1", "k10", "k11", "k12", "k13", "k14", "k15",
  2093. "k16", "k17", "k2", "k3", "k4", "k5", "k6", "k7",
  2094. "k8", "k9", "no_key"});
  2095. std::vector<PinnableSlice> values(keys.size());
  2096. std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
  2097. std::vector<Status> s(keys.size());
  2098. ReadOptions ro;
  2099. ro.value_size_soft_limit = 20;
  2100. ro.async_io = std::get<1>(GetParam());
  2101. db_->MultiGet(ro, handles_[1], keys.size(), keys.data(), values.data(),
  2102. s.data(), false);
  2103. ASSERT_EQ(values.size(), keys.size());
  2104. // In memory keys
  2105. ASSERT_EQ(std::string(values[0].data(), values[0].size()), "v1_");
  2106. ASSERT_EQ(std::string(values[1].data(), values[1].size()), "v10");
  2107. ASSERT_TRUE(s[9].IsNotFound()); // k2
  2108. ASSERT_EQ(std::string(values[12].data(), values[12].size()), "v5_");
  2109. ASSERT_TRUE(s[13].IsNotFound()); // k6
  2110. ASSERT_EQ(std::string(values[16].data(), values[16].size()), "v9_");
  2111. // In sst files
  2112. ASSERT_EQ(std::string(values[2].data(), values[1].size()), "v11");
  2113. ASSERT_EQ(std::string(values[4].data(), values[4].size()), "v13");
  2114. ASSERT_EQ(std::string(values[5].data(), values[5].size()), "v14");
  2115. // Remaining aborted after value_size exceeds.
  2116. ASSERT_TRUE(s[3].IsAborted());
  2117. ASSERT_TRUE(s[6].IsAborted());
  2118. ASSERT_TRUE(s[7].IsAborted());
  2119. ASSERT_TRUE(s[8].IsAborted());
  2120. ASSERT_TRUE(s[10].IsAborted());
  2121. ASSERT_TRUE(s[11].IsAborted());
  2122. ASSERT_TRUE(s[14].IsAborted());
  2123. ASSERT_TRUE(s[15].IsAborted());
  2124. ASSERT_TRUE(s[17].IsAborted());
  2125. // 6 kv pairs * 3 bytes per value (i.e. 18)
  2126. ASSERT_EQ(21, (int)get_perf_context()->multiget_read_bytes);
  2127. SetPerfLevel(kDisable);
  2128. } while (ChangeCompactOptions());
  2129. }
  2130. TEST_P(DBMultiGetTestWithParam, MultiGetBatchedValueSizeMultiLevelMerge) {
  2131. if (std::get<1>(GetParam())) {
  2132. ROCKSDB_GTEST_BYPASS("This test needs to be fixed for async IO");
  2133. return;
  2134. }
  2135. // Skip for unbatched MultiGet
  2136. if (!std::get<0>(GetParam())) {
  2137. ROCKSDB_GTEST_BYPASS("This test is only for batched MultiGet");
  2138. return;
  2139. }
  2140. Options options = CurrentOptions();
  2141. options.disable_auto_compactions = true;
  2142. options.merge_operator = MergeOperators::CreateStringAppendOperator();
  2143. BlockBasedTableOptions bbto;
  2144. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  2145. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  2146. Reopen(options);
  2147. int num_keys = 0;
  2148. for (int i = 0; i < 64; ++i) {
  2149. ASSERT_OK(Put("key_" + std::to_string(i), "val_l2_" + std::to_string(i)));
  2150. num_keys++;
  2151. if (num_keys == 8) {
  2152. ASSERT_OK(Flush());
  2153. num_keys = 0;
  2154. }
  2155. }
  2156. if (num_keys > 0) {
  2157. ASSERT_OK(Flush());
  2158. num_keys = 0;
  2159. }
  2160. MoveFilesToLevel(2);
  2161. for (int i = 0; i < 64; i += 3) {
  2162. ASSERT_OK(Merge("key_" + std::to_string(i), "val_l1_" + std::to_string(i)));
  2163. num_keys++;
  2164. if (num_keys == 8) {
  2165. ASSERT_OK(Flush());
  2166. num_keys = 0;
  2167. }
  2168. }
  2169. if (num_keys > 0) {
  2170. ASSERT_OK(Flush());
  2171. num_keys = 0;
  2172. }
  2173. MoveFilesToLevel(1);
  2174. for (int i = 0; i < 64; i += 5) {
  2175. ASSERT_OK(Merge("key_" + std::to_string(i), "val_l0_" + std::to_string(i)));
  2176. num_keys++;
  2177. if (num_keys == 8) {
  2178. ASSERT_OK(Flush());
  2179. num_keys = 0;
  2180. }
  2181. }
  2182. if (num_keys > 0) {
  2183. ASSERT_OK(Flush());
  2184. num_keys = 0;
  2185. }
  2186. ASSERT_EQ(0, num_keys);
  2187. for (int i = 0; i < 64; i += 9) {
  2188. ASSERT_OK(
  2189. Merge("key_" + std::to_string(i), "val_mem_" + std::to_string(i)));
  2190. }
  2191. std::vector<std::string> keys_str;
  2192. for (int i = 10; i < 50; ++i) {
  2193. keys_str.push_back("key_" + std::to_string(i));
  2194. }
  2195. std::vector<Slice> keys(keys_str.size());
  2196. for (int i = 0; i < 40; i++) {
  2197. keys[i] = Slice(keys_str[i]);
  2198. }
  2199. std::vector<PinnableSlice> values(keys_str.size());
  2200. std::vector<Status> statuses(keys_str.size());
  2201. ReadOptions read_options;
  2202. read_options.verify_checksums = true;
  2203. read_options.value_size_soft_limit = 380;
  2204. read_options.async_io = std::get<1>(GetParam());
  2205. db_->MultiGet(read_options, dbfull()->DefaultColumnFamily(), keys.size(),
  2206. keys.data(), values.data(), statuses.data());
  2207. ASSERT_EQ(values.size(), keys.size());
  2208. for (unsigned int j = 0; j < 26; ++j) {
  2209. int key = j + 10;
  2210. std::string value;
  2211. value.append("val_l2_" + std::to_string(key));
  2212. if (key % 3 == 0) {
  2213. value.append(",");
  2214. value.append("val_l1_" + std::to_string(key));
  2215. }
  2216. if (key % 5 == 0) {
  2217. value.append(",");
  2218. value.append("val_l0_" + std::to_string(key));
  2219. }
  2220. if (key % 9 == 0) {
  2221. value.append(",");
  2222. value.append("val_mem_" + std::to_string(key));
  2223. }
  2224. ASSERT_EQ(values[j], value);
  2225. ASSERT_OK(statuses[j]);
  2226. }
  2227. // All remaning keys status is set Status::Abort
  2228. for (unsigned int j = 26; j < 40; j++) {
  2229. ASSERT_TRUE(statuses[j].IsAborted());
  2230. }
  2231. }
  2232. INSTANTIATE_TEST_CASE_P(DBMultiGetTestWithParam, DBMultiGetTestWithParam,
  2233. testing::Combine(testing::Bool(), testing::Bool()));
  2234. #if USE_COROUTINES
  2235. class DBMultiGetAsyncIOTest : public DBBasicTest,
  2236. public ::testing::WithParamInterface<bool> {
  2237. public:
  2238. DBMultiGetAsyncIOTest()
  2239. : DBBasicTest(), statistics_(ROCKSDB_NAMESPACE::CreateDBStatistics()) {
  2240. BlockBasedTableOptions bbto;
  2241. bbto.filter_policy.reset(NewBloomFilterPolicy(10));
  2242. options_ = CurrentOptions();
  2243. options_.disable_auto_compactions = true;
  2244. options_.statistics = statistics_;
  2245. options_.table_factory.reset(NewBlockBasedTableFactory(bbto));
  2246. options_.env = Env::Default();
  2247. Reopen(options_);
  2248. int num_keys = 0;
  2249. // Put all keys in the bottommost level, and overwrite some keys
  2250. // in L0 and L1
  2251. for (int i = 0; i < 256; ++i) {
  2252. EXPECT_OK(Put(Key(i), "val_l2_" + std::to_string(i)));
  2253. num_keys++;
  2254. if (num_keys == 8) {
  2255. EXPECT_OK(Flush());
  2256. num_keys = 0;
  2257. }
  2258. }
  2259. if (num_keys > 0) {
  2260. EXPECT_OK(Flush());
  2261. num_keys = 0;
  2262. }
  2263. MoveFilesToLevel(2);
  2264. for (int i = 0; i < 128; i += 3) {
  2265. EXPECT_OK(Put(Key(i), "val_l1_" + std::to_string(i)));
  2266. num_keys++;
  2267. if (num_keys == 8) {
  2268. EXPECT_OK(Flush());
  2269. num_keys = 0;
  2270. }
  2271. }
  2272. if (num_keys > 0) {
  2273. EXPECT_OK(Flush());
  2274. num_keys = 0;
  2275. }
  2276. // Put some range deletes in L1
  2277. for (int i = 128; i < 256; i += 32) {
  2278. std::string range_begin = Key(i);
  2279. std::string range_end = Key(i + 16);
  2280. EXPECT_OK(dbfull()->DeleteRange(WriteOptions(),
  2281. dbfull()->DefaultColumnFamily(),
  2282. range_begin, range_end));
  2283. // Also do some Puts to force creation of bloom filter
  2284. for (int j = i + 16; j < i + 32; ++j) {
  2285. if (j % 3 == 0) {
  2286. EXPECT_OK(Put(Key(j), "val_l1_" + std::to_string(j)));
  2287. }
  2288. }
  2289. EXPECT_OK(Flush());
  2290. }
  2291. MoveFilesToLevel(1);
  2292. for (int i = 0; i < 128; i += 5) {
  2293. EXPECT_OK(Put(Key(i), "val_l0_" + std::to_string(i)));
  2294. num_keys++;
  2295. if (num_keys == 8) {
  2296. EXPECT_OK(Flush());
  2297. num_keys = 0;
  2298. }
  2299. }
  2300. if (num_keys > 0) {
  2301. EXPECT_OK(Flush());
  2302. num_keys = 0;
  2303. }
  2304. EXPECT_EQ(0, num_keys);
  2305. }
  2306. const std::shared_ptr<Statistics>& statistics() { return statistics_; }
  2307. protected:
  2308. void PrepareDBForTest() {
  2309. #ifdef ROCKSDB_IOURING_PRESENT
  2310. Reopen(options_);
  2311. #else // ROCKSDB_IOURING_PRESENT
  2312. // Warm up the block cache so we don't need to use the IO uring
  2313. Iterator* iter = dbfull()->NewIterator(ReadOptions());
  2314. for (iter->SeekToFirst(); iter->Valid() && iter->status().ok();
  2315. iter->Next());
  2316. EXPECT_OK(iter->status());
  2317. delete iter;
  2318. #endif // ROCKSDB_IOURING_PRESENT
  2319. }
  2320. void ReopenDB() { Reopen(options_); }
  2321. private:
  2322. std::shared_ptr<Statistics> statistics_;
  2323. Options options_;
  2324. };
  2325. TEST_P(DBMultiGetAsyncIOTest, GetFromL0) {
  2326. // All 3 keys in L0. The L0 files should be read serially.
  2327. std::vector<std::string> key_strs{Key(0), Key(40), Key(80)};
  2328. std::vector<Slice> keys{key_strs[0], key_strs[1], key_strs[2]};
  2329. std::vector<PinnableSlice> values(key_strs.size());
  2330. std::vector<Status> statuses(key_strs.size());
  2331. PrepareDBForTest();
  2332. ReadOptions ro;
  2333. ro.async_io = true;
  2334. ro.optimize_multiget_for_io = GetParam();
  2335. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  2336. keys.data(), values.data(), statuses.data());
  2337. ASSERT_EQ(values.size(), 3);
  2338. ASSERT_OK(statuses[0]);
  2339. ASSERT_OK(statuses[1]);
  2340. ASSERT_OK(statuses[2]);
  2341. ASSERT_EQ(values[0], "val_l0_" + std::to_string(0));
  2342. ASSERT_EQ(values[1], "val_l0_" + std::to_string(40));
  2343. ASSERT_EQ(values[2], "val_l0_" + std::to_string(80));
  2344. HistogramData multiget_io_batch_size;
  2345. statistics()->histogramData(MULTIGET_IO_BATCH_SIZE, &multiget_io_batch_size);
  2346. // With async IO, lookups will happen in parallel for each key
  2347. #ifdef ROCKSDB_IOURING_PRESENT
  2348. if (GetParam()) {
  2349. ASSERT_EQ(multiget_io_batch_size.count, 1);
  2350. ASSERT_EQ(multiget_io_batch_size.max, 3);
  2351. ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 3);
  2352. } else {
  2353. // Without Async IO, MultiGet will call MultiRead 3 times, once for each
  2354. // L0 file
  2355. ASSERT_EQ(multiget_io_batch_size.count, 3);
  2356. }
  2357. #else // ROCKSDB_IOURING_PRESENT
  2358. ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 0);
  2359. #endif // ROCKSDB_IOURING_PRESENT
  2360. }
  2361. TEST_P(DBMultiGetAsyncIOTest, GetFromL1) {
  2362. std::vector<std::string> key_strs;
  2363. std::vector<Slice> keys;
  2364. std::vector<PinnableSlice> values;
  2365. std::vector<Status> statuses;
  2366. key_strs.push_back(Key(33));
  2367. key_strs.push_back(Key(54));
  2368. key_strs.push_back(Key(102));
  2369. keys.emplace_back(key_strs[0]);
  2370. keys.emplace_back(key_strs[1]);
  2371. keys.emplace_back(key_strs[2]);
  2372. values.resize(keys.size());
  2373. statuses.resize(keys.size());
  2374. PrepareDBForTest();
  2375. ReadOptions ro;
  2376. ro.async_io = true;
  2377. ro.optimize_multiget_for_io = GetParam();
  2378. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  2379. keys.data(), values.data(), statuses.data());
  2380. ASSERT_EQ(values.size(), 3);
  2381. ASSERT_EQ(statuses[0], Status::OK());
  2382. ASSERT_EQ(statuses[1], Status::OK());
  2383. ASSERT_EQ(statuses[2], Status::OK());
  2384. ASSERT_EQ(values[0], "val_l1_" + std::to_string(33));
  2385. ASSERT_EQ(values[1], "val_l1_" + std::to_string(54));
  2386. ASSERT_EQ(values[2], "val_l1_" + std::to_string(102));
  2387. HistogramData multiget_io_batch_size;
  2388. statistics()->histogramData(MULTIGET_IO_BATCH_SIZE, &multiget_io_batch_size);
  2389. #ifdef ROCKSDB_IOURING_PRESENT
  2390. // A batch of 3 async IOs is expected, one for each overlapping file in L1
  2391. ASSERT_EQ(multiget_io_batch_size.count, 1);
  2392. ASSERT_EQ(multiget_io_batch_size.max, 3);
  2393. ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 3);
  2394. #else // ROCKSDB_IOURING_PRESENT
  2395. ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 0);
  2396. #endif // ROCKSDB_IOURING_PRESENT
  2397. }
  2398. #ifdef ROCKSDB_IOURING_PRESENT
  2399. TEST_P(DBMultiGetAsyncIOTest, GetFromL1Error) {
  2400. std::vector<std::string> key_strs;
  2401. std::vector<Slice> keys;
  2402. std::vector<PinnableSlice> values;
  2403. std::vector<Status> statuses;
  2404. key_strs.push_back(Key(33));
  2405. key_strs.push_back(Key(54));
  2406. key_strs.push_back(Key(102));
  2407. keys.emplace_back(key_strs[0]);
  2408. keys.emplace_back(key_strs[1]);
  2409. keys.emplace_back(key_strs[2]);
  2410. values.resize(keys.size());
  2411. statuses.resize(keys.size());
  2412. int count = 0;
  2413. SyncPoint::GetInstance()->SetCallBack(
  2414. "TableCache::GetTableReader:BeforeOpenFile", [&](void* status) {
  2415. count++;
  2416. // Fail the last table reader open, which is the 6th SST file
  2417. // since 3 overlapping L0 files + 3 L1 files containing the keys
  2418. if (count == 6) {
  2419. Status* s = static_cast<Status*>(status);
  2420. *s = Status::IOError();
  2421. }
  2422. });
  2423. // DB open will create table readers unless we reduce the table cache
  2424. // capacity.
  2425. // SanitizeOptions will set max_open_files to minimum of 20. Table cache
  2426. // is allocated with max_open_files - 10 as capacity. So override
  2427. // max_open_files to 11 so table cache capacity will become 1. This will
  2428. // prevent file open during DB open and force the file to be opened
  2429. // during MultiGet
  2430. SyncPoint::GetInstance()->SetCallBack(
  2431. "SanitizeOptions::AfterChangeMaxOpenFiles", [&](void* arg) {
  2432. int* max_open_files = (int*)arg;
  2433. *max_open_files = 11;
  2434. });
  2435. SyncPoint::GetInstance()->EnableProcessing();
  2436. PrepareDBForTest();
  2437. ReadOptions ro;
  2438. ro.async_io = true;
  2439. ro.optimize_multiget_for_io = GetParam();
  2440. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  2441. keys.data(), values.data(), statuses.data());
  2442. SyncPoint::GetInstance()->DisableProcessing();
  2443. ASSERT_EQ(values.size(), 3);
  2444. ASSERT_EQ(statuses[0], Status::OK());
  2445. ASSERT_EQ(statuses[1], Status::OK());
  2446. ASSERT_EQ(statuses[2], Status::IOError());
  2447. HistogramData multiget_io_batch_size;
  2448. statistics()->histogramData(MULTIGET_IO_BATCH_SIZE, &multiget_io_batch_size);
  2449. // A batch of 3 async IOs is expected, one for each overlapping file in L1
  2450. ASSERT_EQ(multiget_io_batch_size.count, 1);
  2451. ASSERT_EQ(multiget_io_batch_size.max, 2);
  2452. ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 2);
  2453. }
  2454. #endif // ROCKSDB_IOURING_PRESENT
  2455. TEST_P(DBMultiGetAsyncIOTest, LastKeyInFile) {
  2456. std::vector<std::string> key_strs;
  2457. std::vector<Slice> keys;
  2458. std::vector<PinnableSlice> values;
  2459. std::vector<Status> statuses;
  2460. // 21 is the last key in the first L1 file
  2461. key_strs.push_back(Key(21));
  2462. key_strs.push_back(Key(54));
  2463. key_strs.push_back(Key(102));
  2464. keys.emplace_back(key_strs[0]);
  2465. keys.emplace_back(key_strs[1]);
  2466. keys.emplace_back(key_strs[2]);
  2467. values.resize(keys.size());
  2468. statuses.resize(keys.size());
  2469. PrepareDBForTest();
  2470. ReadOptions ro;
  2471. ro.async_io = true;
  2472. ro.optimize_multiget_for_io = GetParam();
  2473. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  2474. keys.data(), values.data(), statuses.data());
  2475. ASSERT_EQ(values.size(), 3);
  2476. ASSERT_EQ(statuses[0], Status::OK());
  2477. ASSERT_EQ(statuses[1], Status::OK());
  2478. ASSERT_EQ(statuses[2], Status::OK());
  2479. ASSERT_EQ(values[0], "val_l1_" + std::to_string(21));
  2480. ASSERT_EQ(values[1], "val_l1_" + std::to_string(54));
  2481. ASSERT_EQ(values[2], "val_l1_" + std::to_string(102));
  2482. #ifdef ROCKSDB_IOURING_PRESENT
  2483. HistogramData multiget_io_batch_size;
  2484. statistics()->histogramData(MULTIGET_IO_BATCH_SIZE, &multiget_io_batch_size);
  2485. // Since the first MultiGet key is the last key in a file, the MultiGet is
  2486. // expected to lookup in that file first, before moving on to other files.
  2487. // So the first file lookup will issue one async read, and the next lookup
  2488. // will lookup 2 files in parallel and issue 2 async reads
  2489. ASSERT_EQ(multiget_io_batch_size.count, 2);
  2490. ASSERT_EQ(multiget_io_batch_size.max, 2);
  2491. #endif // ROCKSDB_IOURING_PRESENT
  2492. }
  2493. TEST_P(DBMultiGetAsyncIOTest, GetFromL1AndL2) {
  2494. std::vector<std::string> key_strs;
  2495. std::vector<Slice> keys;
  2496. std::vector<PinnableSlice> values;
  2497. std::vector<Status> statuses;
  2498. // 33 and 102 are in L1, and 56 is in L2
  2499. key_strs.push_back(Key(33));
  2500. key_strs.push_back(Key(56));
  2501. key_strs.push_back(Key(102));
  2502. keys.emplace_back(key_strs[0]);
  2503. keys.emplace_back(key_strs[1]);
  2504. keys.emplace_back(key_strs[2]);
  2505. values.resize(keys.size());
  2506. statuses.resize(keys.size());
  2507. PrepareDBForTest();
  2508. ReadOptions ro;
  2509. ro.async_io = true;
  2510. ro.optimize_multiget_for_io = GetParam();
  2511. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  2512. keys.data(), values.data(), statuses.data());
  2513. ASSERT_EQ(values.size(), 3);
  2514. ASSERT_EQ(statuses[0], Status::OK());
  2515. ASSERT_EQ(statuses[1], Status::OK());
  2516. ASSERT_EQ(statuses[2], Status::OK());
  2517. ASSERT_EQ(values[0], "val_l1_" + std::to_string(33));
  2518. ASSERT_EQ(values[1], "val_l2_" + std::to_string(56));
  2519. ASSERT_EQ(values[2], "val_l1_" + std::to_string(102));
  2520. #ifdef ROCKSDB_IOURING_PRESENT
  2521. HistogramData multiget_io_batch_size;
  2522. statistics()->histogramData(MULTIGET_IO_BATCH_SIZE, &multiget_io_batch_size);
  2523. // There are 2 keys in L1 in twp separate files, and 1 in L2. With
  2524. // optimize_multiget_for_io, all three lookups will happen in parallel.
  2525. // Otherwise, the L2 lookup will happen after L1.
  2526. ASSERT_EQ(multiget_io_batch_size.count, GetParam() ? 1 : 2);
  2527. ASSERT_EQ(multiget_io_batch_size.max, GetParam() ? 3 : 2);
  2528. #endif // ROCKSDB_IOURING_PRESENT
  2529. }
  2530. TEST_P(DBMultiGetAsyncIOTest, GetFromL2WithRangeOverlapL0L1) {
  2531. std::vector<std::string> key_strs;
  2532. std::vector<Slice> keys;
  2533. std::vector<PinnableSlice> values;
  2534. std::vector<Status> statuses;
  2535. // 19 and 26 are in L2, but overlap with L0 and L1 file ranges
  2536. key_strs.push_back(Key(19));
  2537. key_strs.push_back(Key(26));
  2538. keys.emplace_back(key_strs[0]);
  2539. keys.emplace_back(key_strs[1]);
  2540. values.resize(keys.size());
  2541. statuses.resize(keys.size());
  2542. PrepareDBForTest();
  2543. ReadOptions ro;
  2544. ro.async_io = true;
  2545. ro.optimize_multiget_for_io = GetParam();
  2546. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  2547. keys.data(), values.data(), statuses.data());
  2548. ASSERT_EQ(values.size(), 2);
  2549. ASSERT_EQ(statuses[0], Status::OK());
  2550. ASSERT_EQ(statuses[1], Status::OK());
  2551. ASSERT_EQ(values[0], "val_l2_" + std::to_string(19));
  2552. ASSERT_EQ(values[1], "val_l2_" + std::to_string(26));
  2553. #ifdef ROCKSDB_IOURING_PRESENT
  2554. // Bloom filters in L0/L1 will avoid the coroutine calls in those levels
  2555. ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 2);
  2556. #else // ROCKSDB_IOURING_PRESENT
  2557. ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 0);
  2558. #endif // ROCKSDB_IOURING_PRESENT
  2559. }
  2560. #ifdef ROCKSDB_IOURING_PRESENT
  2561. TEST_P(DBMultiGetAsyncIOTest, GetFromL2WithRangeDelInL1) {
  2562. std::vector<std::string> key_strs;
  2563. std::vector<Slice> keys;
  2564. std::vector<PinnableSlice> values;
  2565. std::vector<Status> statuses;
  2566. // 139 and 163 are in L2, but overlap with a range deletes in L1
  2567. key_strs.push_back(Key(139));
  2568. key_strs.push_back(Key(163));
  2569. keys.emplace_back(key_strs[0]);
  2570. keys.emplace_back(key_strs[1]);
  2571. values.resize(keys.size());
  2572. statuses.resize(keys.size());
  2573. PrepareDBForTest();
  2574. ReadOptions ro;
  2575. ro.async_io = true;
  2576. ro.optimize_multiget_for_io = GetParam();
  2577. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  2578. keys.data(), values.data(), statuses.data());
  2579. ASSERT_EQ(values.size(), 2);
  2580. ASSERT_EQ(statuses[0], Status::NotFound());
  2581. ASSERT_EQ(statuses[1], Status::NotFound());
  2582. // Bloom filters in L0/L1 will avoid the coroutine calls in those levels
  2583. ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 2);
  2584. }
  2585. TEST_P(DBMultiGetAsyncIOTest, GetFromL1AndL2WithRangeDelInL1) {
  2586. std::vector<std::string> key_strs;
  2587. std::vector<Slice> keys;
  2588. std::vector<PinnableSlice> values;
  2589. std::vector<Status> statuses;
  2590. // 139 and 163 are in L2, but overlap with a range deletes in L1
  2591. key_strs.push_back(Key(139));
  2592. key_strs.push_back(Key(144));
  2593. key_strs.push_back(Key(163));
  2594. keys.emplace_back(key_strs[0]);
  2595. keys.emplace_back(key_strs[1]);
  2596. keys.emplace_back(key_strs[2]);
  2597. values.resize(keys.size());
  2598. statuses.resize(keys.size());
  2599. PrepareDBForTest();
  2600. ReadOptions ro;
  2601. ro.async_io = true;
  2602. ro.optimize_multiget_for_io = GetParam();
  2603. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  2604. keys.data(), values.data(), statuses.data());
  2605. ASSERT_EQ(values.size(), keys.size());
  2606. ASSERT_EQ(statuses[0], Status::NotFound());
  2607. ASSERT_EQ(statuses[1], Status::OK());
  2608. ASSERT_EQ(values[1], "val_l1_" + std::to_string(144));
  2609. ASSERT_EQ(statuses[2], Status::NotFound());
  2610. // Bloom filters in L0/L1 will avoid the coroutine calls in those levels
  2611. ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 3);
  2612. }
  2613. #endif // ROCKSDB_IOURING_PRESENT
  2614. TEST_P(DBMultiGetAsyncIOTest, GetNoIOUring) {
  2615. std::vector<std::string> key_strs;
  2616. std::vector<Slice> keys;
  2617. std::vector<PinnableSlice> values;
  2618. std::vector<Status> statuses;
  2619. key_strs.push_back(Key(33));
  2620. key_strs.push_back(Key(54));
  2621. key_strs.push_back(Key(102));
  2622. keys.emplace_back(key_strs[0]);
  2623. keys.emplace_back(key_strs[1]);
  2624. keys.emplace_back(key_strs[2]);
  2625. values.resize(keys.size());
  2626. statuses.resize(keys.size());
  2627. enable_io_uring = false;
  2628. ReopenDB();
  2629. ReadOptions ro;
  2630. ro.async_io = true;
  2631. ro.optimize_multiget_for_io = GetParam();
  2632. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  2633. keys.data(), values.data(), statuses.data());
  2634. ASSERT_EQ(values.size(), 3);
  2635. ASSERT_EQ(statuses[0], Status::OK());
  2636. ASSERT_EQ(statuses[1], Status::OK());
  2637. ASSERT_EQ(statuses[2], Status::OK());
  2638. HistogramData async_read_bytes;
  2639. statistics()->histogramData(ASYNC_READ_BYTES, &async_read_bytes);
  2640. // A batch of 3 async IOs is expected, one for each overlapping file in L1
  2641. ASSERT_EQ(async_read_bytes.count, 0);
  2642. ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 0);
  2643. }
  2644. INSTANTIATE_TEST_CASE_P(DBMultiGetAsyncIOTest, DBMultiGetAsyncIOTest,
  2645. testing::Bool());
  2646. #endif // USE_COROUTINES
  2647. TEST_F(DBBasicTest, MultiGetStats) {
  2648. Options options;
  2649. options.create_if_missing = true;
  2650. options.disable_auto_compactions = true;
  2651. options.env = env_;
  2652. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  2653. BlockBasedTableOptions table_options;
  2654. table_options.block_size = 1;
  2655. table_options.index_type =
  2656. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch;
  2657. table_options.partition_filters = true;
  2658. table_options.no_block_cache = true;
  2659. table_options.cache_index_and_filter_blocks = false;
  2660. table_options.filter_policy.reset(NewBloomFilterPolicy(10, false));
  2661. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2662. CreateAndReopenWithCF({"pikachu"}, options);
  2663. int total_keys = 2000;
  2664. std::vector<std::string> keys_str(total_keys);
  2665. std::vector<Slice> keys(total_keys);
  2666. static size_t kMultiGetBatchSize = 100;
  2667. std::vector<PinnableSlice> values(kMultiGetBatchSize);
  2668. std::vector<Status> s(kMultiGetBatchSize);
  2669. ReadOptions read_opts;
  2670. Random rnd(309);
  2671. // Create Multiple SST files at multiple levels.
  2672. for (int i = 0; i < 500; ++i) {
  2673. keys_str[i] = "k" + std::to_string(i);
  2674. keys[i] = Slice(keys_str[i]);
  2675. ASSERT_OK(Put(1, "k" + std::to_string(i), rnd.RandomString(1000)));
  2676. if (i % 100 == 0) {
  2677. ASSERT_OK(Flush(1));
  2678. }
  2679. }
  2680. ASSERT_OK(Flush(1));
  2681. MoveFilesToLevel(2, 1);
  2682. for (int i = 501; i < 1000; ++i) {
  2683. keys_str[i] = "k" + std::to_string(i);
  2684. keys[i] = Slice(keys_str[i]);
  2685. ASSERT_OK(Put(1, "k" + std::to_string(i), rnd.RandomString(1000)));
  2686. if (i % 100 == 0) {
  2687. ASSERT_OK(Flush(1));
  2688. }
  2689. }
  2690. ASSERT_OK(Flush(1));
  2691. MoveFilesToLevel(2, 1);
  2692. for (int i = 1001; i < total_keys; ++i) {
  2693. keys_str[i] = "k" + std::to_string(i);
  2694. keys[i] = Slice(keys_str[i]);
  2695. ASSERT_OK(Put(1, "k" + std::to_string(i), rnd.RandomString(1000)));
  2696. if (i % 100 == 0) {
  2697. ASSERT_OK(Flush(1));
  2698. }
  2699. }
  2700. ASSERT_OK(Flush(1));
  2701. MoveFilesToLevel(1, 1);
  2702. Close();
  2703. ReopenWithColumnFamilies({"default", "pikachu"}, options);
  2704. ASSERT_OK(options.statistics->Reset());
  2705. db_->MultiGet(read_opts, handles_[1], kMultiGetBatchSize, &keys[1250],
  2706. values.data(), s.data(), false);
  2707. ASSERT_EQ(values.size(), kMultiGetBatchSize);
  2708. HistogramData hist_level;
  2709. HistogramData hist_index_and_filter_blocks;
  2710. HistogramData hist_sst;
  2711. options.statistics->histogramData(NUM_LEVEL_READ_PER_MULTIGET, &hist_level);
  2712. options.statistics->histogramData(NUM_INDEX_AND_FILTER_BLOCKS_READ_PER_LEVEL,
  2713. &hist_index_and_filter_blocks);
  2714. options.statistics->histogramData(NUM_SST_READ_PER_LEVEL, &hist_sst);
  2715. // Maximum number of blocks read from a file system in a level.
  2716. ASSERT_EQ(hist_level.max, 1);
  2717. ASSERT_GT(hist_index_and_filter_blocks.max, 0);
  2718. // Maximum number of sst files read from file system in a level.
  2719. ASSERT_EQ(hist_sst.max, 2);
  2720. // Minimun number of blocks read in a level.
  2721. ASSERT_EQ(hist_level.min, 1);
  2722. ASSERT_GT(hist_index_and_filter_blocks.min, 0);
  2723. // Minimun number of sst files read in a level.
  2724. ASSERT_EQ(hist_sst.min, 1);
  2725. for (PinnableSlice& value : values) {
  2726. value.Reset();
  2727. }
  2728. for (Status& status : s) {
  2729. status = Status::OK();
  2730. }
  2731. db_->MultiGet(read_opts, handles_[1], kMultiGetBatchSize, &keys[950],
  2732. values.data(), s.data(), false);
  2733. options.statistics->histogramData(NUM_LEVEL_READ_PER_MULTIGET, &hist_level);
  2734. ASSERT_EQ(hist_level.max, 2);
  2735. }
  2736. // Test class for batched MultiGet with prefix extractor
  2737. // Param bool - If true, use partitioned filters
  2738. // If false, use full filter block
  2739. class MultiGetPrefixExtractorTest : public DBBasicTest,
  2740. public ::testing::WithParamInterface<bool> {
  2741. };
  2742. TEST_P(MultiGetPrefixExtractorTest, Batched) {
  2743. Options options = CurrentOptions();
  2744. options.prefix_extractor.reset(NewFixedPrefixTransform(2));
  2745. options.memtable_prefix_bloom_size_ratio = 10;
  2746. BlockBasedTableOptions bbto;
  2747. if (GetParam()) {
  2748. bbto.index_type = BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch;
  2749. bbto.partition_filters = true;
  2750. }
  2751. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  2752. bbto.whole_key_filtering = false;
  2753. bbto.cache_index_and_filter_blocks = false;
  2754. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  2755. Reopen(options);
  2756. SetPerfLevel(kEnableCount);
  2757. get_perf_context()->Reset();
  2758. ASSERT_OK(Put("k", "v0"));
  2759. ASSERT_OK(Put("kk1", "v1"));
  2760. ASSERT_OK(Put("kk2", "v2"));
  2761. ASSERT_OK(Put("kk3", "v3"));
  2762. ASSERT_OK(Put("kk4", "v4"));
  2763. std::vector<std::string> keys(
  2764. {"k", "kk1", "kk2", "kk3", "kk4", "rofl", "lmho"});
  2765. std::vector<std::string> expected(
  2766. {"v0", "v1", "v2", "v3", "v4", "NOT_FOUND", "NOT_FOUND"});
  2767. std::vector<std::string> values;
  2768. values = MultiGet(keys, nullptr);
  2769. ASSERT_EQ(values, expected);
  2770. // One key ("k") is not queried against the filter because it is outside
  2771. // the prefix_extractor domain, leaving 6 keys with queried prefixes.
  2772. ASSERT_EQ(get_perf_context()->bloom_memtable_miss_count, 2);
  2773. ASSERT_EQ(get_perf_context()->bloom_memtable_hit_count, 4);
  2774. ASSERT_OK(Flush());
  2775. get_perf_context()->Reset();
  2776. values = MultiGet(keys, nullptr);
  2777. ASSERT_EQ(values, expected);
  2778. ASSERT_EQ(get_perf_context()->bloom_sst_miss_count, 2);
  2779. ASSERT_EQ(get_perf_context()->bloom_sst_hit_count, 4);
  2780. // Also check Get stat
  2781. get_perf_context()->Reset();
  2782. for (size_t i = 0; i < keys.size(); ++i) {
  2783. values[i] = Get(keys[i]);
  2784. }
  2785. ASSERT_EQ(values, expected);
  2786. ASSERT_EQ(get_perf_context()->bloom_sst_miss_count, 2);
  2787. ASSERT_EQ(get_perf_context()->bloom_sst_hit_count, 4);
  2788. }
  2789. INSTANTIATE_TEST_CASE_P(MultiGetPrefix, MultiGetPrefixExtractorTest,
  2790. ::testing::Bool());
  2791. class DBMultiGetRowCacheTest : public DBBasicTest,
  2792. public ::testing::WithParamInterface<bool> {};
  2793. TEST_P(DBMultiGetRowCacheTest, MultiGetBatched) {
  2794. do {
  2795. option_config_ = kRowCache;
  2796. Options options = CurrentOptions();
  2797. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  2798. CreateAndReopenWithCF({"pikachu"}, options);
  2799. SetPerfLevel(kEnableCount);
  2800. ASSERT_OK(Put(1, "k1", "v1"));
  2801. ASSERT_OK(Put(1, "k2", "v2"));
  2802. ASSERT_OK(Put(1, "k3", "v3"));
  2803. ASSERT_OK(Put(1, "k4", "v4"));
  2804. ASSERT_OK(Flush(1));
  2805. ASSERT_OK(Put(1, "k5", "v5"));
  2806. const Snapshot* snap1 = dbfull()->GetSnapshot();
  2807. ASSERT_OK(Delete(1, "k4"));
  2808. ASSERT_OK(Flush(1));
  2809. const Snapshot* snap2 = dbfull()->GetSnapshot();
  2810. get_perf_context()->Reset();
  2811. std::vector<Slice> keys({"no_key", "k5", "k4", "k3", "k1"});
  2812. std::vector<PinnableSlice> values(keys.size());
  2813. std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
  2814. std::vector<Status> s(keys.size());
  2815. ReadOptions ro;
  2816. bool use_snapshots = GetParam();
  2817. if (use_snapshots) {
  2818. ro.snapshot = snap2;
  2819. }
  2820. db_->MultiGet(ro, handles_[1], keys.size(), keys.data(), values.data(),
  2821. s.data(), false);
  2822. ASSERT_EQ(values.size(), keys.size());
  2823. ASSERT_EQ(std::string(values[4].data(), values[4].size()), "v1");
  2824. ASSERT_EQ(std::string(values[3].data(), values[3].size()), "v3");
  2825. ASSERT_EQ(std::string(values[1].data(), values[1].size()), "v5");
  2826. // four kv pairs * two bytes per value
  2827. ASSERT_EQ(6, (int)get_perf_context()->multiget_read_bytes);
  2828. ASSERT_TRUE(s[0].IsNotFound());
  2829. ASSERT_OK(s[1]);
  2830. ASSERT_TRUE(s[2].IsNotFound());
  2831. ASSERT_OK(s[3]);
  2832. ASSERT_OK(s[4]);
  2833. // Call MultiGet() again with some intersection with the previous set of
  2834. // keys. Those should already be in the row cache.
  2835. keys.assign({"no_key", "k5", "k3", "k2"});
  2836. for (size_t i = 0; i < keys.size(); ++i) {
  2837. values[i].Reset();
  2838. s[i] = Status::OK();
  2839. }
  2840. get_perf_context()->Reset();
  2841. if (use_snapshots) {
  2842. ro.snapshot = snap1;
  2843. }
  2844. db_->MultiGet(ReadOptions(), handles_[1], keys.size(), keys.data(),
  2845. values.data(), s.data(), false);
  2846. ASSERT_EQ(std::string(values[3].data(), values[3].size()), "v2");
  2847. ASSERT_EQ(std::string(values[2].data(), values[2].size()), "v3");
  2848. ASSERT_EQ(std::string(values[1].data(), values[1].size()), "v5");
  2849. // four kv pairs * two bytes per value
  2850. ASSERT_EQ(6, (int)get_perf_context()->multiget_read_bytes);
  2851. ASSERT_TRUE(s[0].IsNotFound());
  2852. ASSERT_OK(s[1]);
  2853. ASSERT_OK(s[2]);
  2854. ASSERT_OK(s[3]);
  2855. if (use_snapshots) {
  2856. // Only reads from the first SST file would have been cached, since
  2857. // snapshot seq no is > fd.largest_seqno
  2858. ASSERT_EQ(1, TestGetTickerCount(options, ROW_CACHE_HIT));
  2859. } else {
  2860. ASSERT_EQ(2, TestGetTickerCount(options, ROW_CACHE_HIT));
  2861. }
  2862. SetPerfLevel(kDisable);
  2863. dbfull()->ReleaseSnapshot(snap1);
  2864. dbfull()->ReleaseSnapshot(snap2);
  2865. } while (ChangeCompactOptions());
  2866. }
  2867. INSTANTIATE_TEST_CASE_P(DBMultiGetRowCacheTest, DBMultiGetRowCacheTest,
  2868. testing::Values(true, false));
  2869. TEST_F(DBBasicTest, GetAllKeyVersions) {
  2870. Options options = CurrentOptions();
  2871. options.env = env_;
  2872. options.create_if_missing = true;
  2873. options.disable_auto_compactions = true;
  2874. CreateAndReopenWithCF({"pikachu"}, options);
  2875. ASSERT_EQ(2, handles_.size());
  2876. const size_t kNumInserts = 4;
  2877. const size_t kNumDeletes = 4;
  2878. const size_t kNumUpdates = 4;
  2879. // Check default column family
  2880. for (size_t i = 0; i != kNumInserts; ++i) {
  2881. ASSERT_OK(Put(std::to_string(i), "value"));
  2882. }
  2883. for (size_t i = 0; i != kNumUpdates; ++i) {
  2884. ASSERT_OK(Put(std::to_string(i), "value1"));
  2885. }
  2886. for (size_t i = 0; i != kNumDeletes; ++i) {
  2887. ASSERT_OK(Delete(std::to_string(i)));
  2888. }
  2889. std::vector<KeyVersion> key_versions;
  2890. ASSERT_OK(GetAllKeyVersions(db_, {}, {}, std::numeric_limits<size_t>::max(),
  2891. &key_versions));
  2892. ASSERT_EQ(kNumInserts + kNumDeletes + kNumUpdates, key_versions.size());
  2893. for (size_t i = 0; i < kNumInserts + kNumDeletes + kNumUpdates; i++) {
  2894. if (i % 3 == 0) {
  2895. ASSERT_EQ(key_versions[i].GetTypeName(), "TypeDeletion");
  2896. } else {
  2897. ASSERT_EQ(key_versions[i].GetTypeName(), "TypeValue");
  2898. }
  2899. }
  2900. ASSERT_OK(GetAllKeyVersions(db_, handles_[0], {}, {},
  2901. std::numeric_limits<size_t>::max(),
  2902. &key_versions));
  2903. ASSERT_EQ(kNumInserts + kNumDeletes + kNumUpdates, key_versions.size());
  2904. // Check non-default column family
  2905. for (size_t i = 0; i + 1 != kNumInserts; ++i) {
  2906. ASSERT_OK(Put(1, std::to_string(i), "value"));
  2907. }
  2908. for (size_t i = 0; i + 1 != kNumUpdates; ++i) {
  2909. ASSERT_OK(Put(1, std::to_string(i), "value1"));
  2910. }
  2911. for (size_t i = 0; i + 1 != kNumDeletes; ++i) {
  2912. ASSERT_OK(Delete(1, std::to_string(i)));
  2913. }
  2914. ASSERT_OK(GetAllKeyVersions(db_, handles_[1], {}, {},
  2915. std::numeric_limits<size_t>::max(),
  2916. &key_versions));
  2917. ASSERT_EQ(kNumInserts + kNumDeletes + kNumUpdates - 3, key_versions.size());
  2918. // Change from historical behavior: empty key is now interpreted literally as
  2919. // a legal key (rather than as a "not present" key)
  2920. ASSERT_OK(GetAllKeyVersions(db_, handles_[1], Slice(), Slice(),
  2921. std::numeric_limits<size_t>::max(),
  2922. &key_versions));
  2923. ASSERT_EQ(key_versions.size(), 0);
  2924. }
  2925. TEST_F(DBBasicTest, ValueTypeString) {
  2926. KeyVersion key_version;
  2927. // when adding new type, please also update `value_type_string_map`
  2928. for (unsigned char i = ValueType::kTypeDeletion; i < ValueType::kTypeMaxValid;
  2929. i++) {
  2930. key_version.type = i;
  2931. ASSERT_TRUE(key_version.GetTypeName() != "Invalid");
  2932. }
  2933. }
  2934. TEST_F(DBBasicTest, MultiGetIOBufferOverrun) {
  2935. Options options = CurrentOptions();
  2936. Random rnd(301);
  2937. BlockBasedTableOptions table_options;
  2938. table_options.pin_l0_filter_and_index_blocks_in_cache = true;
  2939. table_options.block_size = 16 * 1024;
  2940. ASSERT_TRUE(table_options.block_size >
  2941. BlockBasedTable::kMultiGetReadStackBufSize);
  2942. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2943. Reopen(options);
  2944. std::string zero_str(128, '\0');
  2945. for (int i = 0; i < 100; ++i) {
  2946. // Make the value compressible. A purely random string doesn't compress
  2947. // and the resultant data block will not be compressed
  2948. std::string value(rnd.RandomString(128) + zero_str);
  2949. assert(Put(Key(i), value) == Status::OK());
  2950. }
  2951. ASSERT_OK(Flush());
  2952. std::vector<std::string> key_data(10);
  2953. std::vector<Slice> keys;
  2954. // We cannot resize a PinnableSlice vector, so just set initial size to
  2955. // largest we think we will need
  2956. std::vector<PinnableSlice> values(10);
  2957. std::vector<Status> statuses;
  2958. ReadOptions ro;
  2959. // Warm up the cache first
  2960. key_data.emplace_back(Key(0));
  2961. keys.emplace_back(key_data.back());
  2962. key_data.emplace_back(Key(50));
  2963. keys.emplace_back(key_data.back());
  2964. statuses.resize(keys.size());
  2965. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  2966. keys.data(), values.data(), statuses.data(), true);
  2967. }
  2968. TEST_F(DBBasicTest, MultiGetWithSnapshotsAndPersistedTier) {
  2969. Options options = CurrentOptions();
  2970. options.create_if_missing = true;
  2971. options.atomic_flush = true;
  2972. DestroyAndReopen(options);
  2973. CreateAndReopenWithCF({"cf1", "cf2"}, options);
  2974. // Insert initial data
  2975. ASSERT_OK(Put(0, "key1", "value1_cf0"));
  2976. ASSERT_OK(Put(1, "key1", "value1_cf1"));
  2977. ASSERT_OK(Put(2, "key1", "value1_cf2"));
  2978. ASSERT_OK(Flush({0, 1, 2}));
  2979. for (auto cf : {0, 1, 2}) {
  2980. ASSERT_EQ(1, NumTableFilesAtLevel(0, cf));
  2981. }
  2982. ASSERT_OK(Put(0, "key1", "value2_cf0"));
  2983. ASSERT_OK(Put(1, "key1", "value2_cf1"));
  2984. ASSERT_OK(Put(2, "key1", "value2_cf2"));
  2985. // Prepare for concurrent atomic flush
  2986. std::atomic<bool> flush_done(false);
  2987. std::thread flush_thread([&]() {
  2988. ASSERT_OK(Flush({0, 1, 2}));
  2989. flush_done.store(true);
  2990. });
  2991. // Perform MultiGet with snapshot and read_tier = kPersistentTier
  2992. ReadOptions ro;
  2993. const Snapshot* snapshot = db_->GetSnapshot();
  2994. ro.snapshot = snapshot;
  2995. ro.read_tier = kPersistedTier;
  2996. std::string k = "key1";
  2997. std::vector<Slice> keys(3, Slice(k));
  2998. std::vector<Status> statuses(keys.size());
  2999. std::vector<ColumnFamilyHandle*> cfs(keys.size());
  3000. std::vector<Slice> new_keys(keys.size());
  3001. std::vector<PinnableSlice> pin_values(keys.size());
  3002. for (size_t i = 0; i < keys.size(); ++i) {
  3003. cfs[i] = handles_[i];
  3004. }
  3005. db_->MultiGet(ro, cfs.size(), cfs.data(), keys.data(), pin_values.data(),
  3006. statuses.data());
  3007. for (const auto& s : statuses) {
  3008. ASSERT_OK(s);
  3009. }
  3010. if (pin_values[0] == "value1_cf0") {
  3011. // Check if the first value matches expected value
  3012. ASSERT_EQ(pin_values[1], "value1_cf1");
  3013. ASSERT_EQ(pin_values[2], "value1_cf2");
  3014. } else {
  3015. // If first value doesn't match, check if we got the updated values
  3016. ASSERT_EQ(pin_values[0], "value2_cf0");
  3017. ASSERT_EQ(pin_values[1], "value2_cf1");
  3018. ASSERT_EQ(pin_values[2], "value2_cf2");
  3019. }
  3020. flush_thread.join();
  3021. db_->ReleaseSnapshot(snapshot);
  3022. }
  3023. TEST_F(DBBasicTest, IncrementalRecoveryNoCorrupt) {
  3024. Options options = CurrentOptions();
  3025. DestroyAndReopen(options);
  3026. CreateAndReopenWithCF({"pikachu", "eevee"}, options);
  3027. size_t num_cfs = handles_.size();
  3028. ASSERT_EQ(3, num_cfs);
  3029. WriteOptions write_opts;
  3030. write_opts.disableWAL = true;
  3031. for (size_t cf = 0; cf != num_cfs; ++cf) {
  3032. for (size_t i = 0; i != 10000; ++i) {
  3033. std::string key_str = Key(static_cast<int>(i));
  3034. std::string value_str = std::to_string(cf) + "_" + std::to_string(i);
  3035. ASSERT_OK(Put(static_cast<int>(cf), key_str, value_str));
  3036. if (0 == (i % 1000)) {
  3037. ASSERT_OK(Flush(static_cast<int>(cf)));
  3038. }
  3039. }
  3040. }
  3041. for (size_t cf = 0; cf != num_cfs; ++cf) {
  3042. ASSERT_OK(Flush(static_cast<int>(cf)));
  3043. }
  3044. Close();
  3045. options.best_efforts_recovery = true;
  3046. ReopenWithColumnFamilies({kDefaultColumnFamilyName, "pikachu", "eevee"},
  3047. options);
  3048. num_cfs = handles_.size();
  3049. ASSERT_EQ(3, num_cfs);
  3050. for (size_t cf = 0; cf != num_cfs; ++cf) {
  3051. for (int i = 0; i != 10000; ++i) {
  3052. std::string key_str = Key(static_cast<int>(i));
  3053. std::string expected_value_str =
  3054. std::to_string(cf) + "_" + std::to_string(i);
  3055. ASSERT_EQ(expected_value_str, Get(static_cast<int>(cf), key_str));
  3056. }
  3057. }
  3058. }
  3059. TEST_F(DBBasicTest, BestEffortsRecoveryWithVersionBuildingFailure) {
  3060. Options options = CurrentOptions();
  3061. DestroyAndReopen(options);
  3062. ASSERT_OK(Put("foo", "value"));
  3063. ASSERT_OK(Flush());
  3064. SyncPoint::GetInstance()->DisableProcessing();
  3065. SyncPoint::GetInstance()->ClearAllCallBacks();
  3066. SyncPoint::GetInstance()->SetCallBack(
  3067. "VersionBuilder::CheckConsistencyBeforeReturn", [&](void* arg) {
  3068. ASSERT_NE(nullptr, arg);
  3069. *(static_cast<Status*>(arg)) = Status::Corruption("Inject corruption");
  3070. });
  3071. SyncPoint::GetInstance()->EnableProcessing();
  3072. options.best_efforts_recovery = true;
  3073. Status s = TryReopen(options);
  3074. ASSERT_TRUE(s.IsCorruption());
  3075. SyncPoint::GetInstance()->DisableProcessing();
  3076. SyncPoint::GetInstance()->ClearAllCallBacks();
  3077. }
  3078. namespace {
  3079. class TableFileListener : public EventListener {
  3080. public:
  3081. void OnTableFileCreated(const TableFileCreationInfo& info) override {
  3082. InstrumentedMutexLock lock(&mutex_);
  3083. cf_to_paths_[info.cf_name].push_back(info.file_path);
  3084. }
  3085. std::vector<std::string>& GetFiles(const std::string& cf_name) {
  3086. InstrumentedMutexLock lock(&mutex_);
  3087. return cf_to_paths_[cf_name];
  3088. }
  3089. private:
  3090. InstrumentedMutex mutex_;
  3091. std::unordered_map<std::string, std::vector<std::string>> cf_to_paths_;
  3092. };
  3093. class FlushTableFileListener : public EventListener {
  3094. public:
  3095. void OnTableFileCreated(const TableFileCreationInfo& info) override {
  3096. InstrumentedMutexLock lock(&mutex_);
  3097. if (info.reason != TableFileCreationReason::kFlush) {
  3098. return;
  3099. }
  3100. cf_to_flushed_files_[info.cf_name].push_back(info.file_path);
  3101. }
  3102. std::vector<std::string>& GetFlushedFiles(const std::string& cf_name) {
  3103. InstrumentedMutexLock lock(&mutex_);
  3104. return cf_to_flushed_files_[cf_name];
  3105. }
  3106. private:
  3107. InstrumentedMutex mutex_;
  3108. std::unordered_map<std::string, std::vector<std::string>>
  3109. cf_to_flushed_files_;
  3110. };
  3111. class FlushBlobFileListener : public EventListener {
  3112. public:
  3113. void OnBlobFileCreated(const BlobFileCreationInfo& info) override {
  3114. InstrumentedMutexLock lock(&mutex_);
  3115. if (info.reason != BlobFileCreationReason::kFlush) {
  3116. return;
  3117. }
  3118. cf_to_flushed_blobs_files_[info.cf_name].push_back(info.file_path);
  3119. }
  3120. std::vector<std::string>& GetFlushedBlobFiles(const std::string& cf_name) {
  3121. InstrumentedMutexLock lock(&mutex_);
  3122. return cf_to_flushed_blobs_files_[cf_name];
  3123. }
  3124. private:
  3125. InstrumentedMutex mutex_;
  3126. std::unordered_map<std::string, std::vector<std::string>>
  3127. cf_to_flushed_blobs_files_;
  3128. };
  3129. } // anonymous namespace
  3130. TEST_F(DBBasicTest, LastSstFileNotInManifest) {
  3131. // If the last sst file is not tracked in MANIFEST,
  3132. // or the VersionEdit for the last sst file is not synced,
  3133. // on recovery, the last sst file should be deleted,
  3134. // and new sst files shouldn't reuse its file number.
  3135. Options options = CurrentOptions();
  3136. DestroyAndReopen(options);
  3137. Close();
  3138. // Manually add a sst file.
  3139. constexpr uint64_t kSstFileNumber = 100;
  3140. const std::string kSstFile = MakeTableFileName(dbname_, kSstFileNumber);
  3141. ASSERT_OK(WriteStringToFile(env_,
  3142. /* data = */ "bad sst file content",
  3143. /* fname = */ kSstFile,
  3144. /* should_sync = */ true));
  3145. ASSERT_OK(env_->FileExists(kSstFile));
  3146. TableFileListener* listener = new TableFileListener();
  3147. options.listeners.emplace_back(listener);
  3148. Reopen(options);
  3149. // kSstFile should already be deleted.
  3150. ASSERT_TRUE(env_->FileExists(kSstFile).IsNotFound());
  3151. ASSERT_OK(Put("k", "v"));
  3152. ASSERT_OK(Flush());
  3153. // New sst file should have file number > kSstFileNumber.
  3154. std::vector<std::string>& files =
  3155. listener->GetFiles(kDefaultColumnFamilyName);
  3156. ASSERT_EQ(files.size(), 1);
  3157. const std::string fname = files[0].erase(0, (dbname_ + "/").size());
  3158. uint64_t number = 0;
  3159. FileType type = kTableFile;
  3160. ASSERT_TRUE(ParseFileName(fname, &number, &type));
  3161. ASSERT_EQ(type, kTableFile);
  3162. ASSERT_GT(number, kSstFileNumber);
  3163. }
  3164. TEST_F(DBBasicTest, RecoverWithMissingFiles) {
  3165. Options options = CurrentOptions();
  3166. DestroyAndReopen(options);
  3167. TableFileListener* listener = new TableFileListener();
  3168. // Disable auto compaction to simplify SST file name tracking.
  3169. options.disable_auto_compactions = true;
  3170. options.listeners.emplace_back(listener);
  3171. CreateAndReopenWithCF({"pikachu", "eevee"}, options);
  3172. std::vector<std::string> all_cf_names = {kDefaultColumnFamilyName, "pikachu",
  3173. "eevee"};
  3174. size_t num_cfs = handles_.size();
  3175. ASSERT_EQ(3, num_cfs);
  3176. for (size_t cf = 0; cf != num_cfs; ++cf) {
  3177. ASSERT_OK(Put(static_cast<int>(cf), "a", "0_value"));
  3178. ASSERT_OK(Flush(static_cast<int>(cf)));
  3179. ASSERT_OK(Put(static_cast<int>(cf), "b", "0_value"));
  3180. ASSERT_OK(Flush(static_cast<int>(cf)));
  3181. ASSERT_OK(Put(static_cast<int>(cf), "c", "0_value"));
  3182. ASSERT_OK(Flush(static_cast<int>(cf)));
  3183. }
  3184. // Delete and corrupt files
  3185. for (size_t i = 0; i < all_cf_names.size(); ++i) {
  3186. std::vector<std::string>& files = listener->GetFiles(all_cf_names[i]);
  3187. ASSERT_EQ(3, files.size());
  3188. std::string corrupted_data;
  3189. ASSERT_OK(ReadFileToString(env_, files[files.size() - 1], &corrupted_data));
  3190. ASSERT_OK(WriteStringToFile(
  3191. env_, corrupted_data.substr(0, corrupted_data.size() - 2),
  3192. files[files.size() - 1], /*should_sync=*/true));
  3193. for (int j = static_cast<int>(files.size() - 2); j >= static_cast<int>(i);
  3194. --j) {
  3195. ASSERT_OK(env_->DeleteFile(files[j]));
  3196. }
  3197. }
  3198. options.best_efforts_recovery = true;
  3199. ReopenWithColumnFamilies(all_cf_names, options);
  3200. // Verify data
  3201. ReadOptions read_opts;
  3202. read_opts.total_order_seek = true;
  3203. {
  3204. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts, handles_[0]));
  3205. iter->SeekToFirst();
  3206. ASSERT_FALSE(iter->Valid());
  3207. ASSERT_OK(iter->status());
  3208. iter.reset(db_->NewIterator(read_opts, handles_[1]));
  3209. iter->SeekToFirst();
  3210. ASSERT_TRUE(iter->Valid());
  3211. ASSERT_EQ("a", iter->key());
  3212. iter->Next();
  3213. ASSERT_FALSE(iter->Valid());
  3214. ASSERT_OK(iter->status());
  3215. iter.reset(db_->NewIterator(read_opts, handles_[2]));
  3216. iter->SeekToFirst();
  3217. ASSERT_TRUE(iter->Valid());
  3218. ASSERT_EQ("a", iter->key());
  3219. iter->Next();
  3220. ASSERT_TRUE(iter->Valid());
  3221. ASSERT_EQ("b", iter->key());
  3222. iter->Next();
  3223. ASSERT_FALSE(iter->Valid());
  3224. ASSERT_OK(iter->status());
  3225. }
  3226. }
  3227. // Param 0: whether to enable blob DB.
  3228. // Param 1: when blob DB is enabled, whether to also delete the missing L0
  3229. // file's associated blob file.
  3230. class BestEffortsRecoverIncompleteVersionTest
  3231. : public DBTestBase,
  3232. public testing::WithParamInterface<std::tuple<bool, bool>> {
  3233. public:
  3234. BestEffortsRecoverIncompleteVersionTest()
  3235. : DBTestBase("best_efforts_recover_incomplete_version_test",
  3236. /*env_do_fsync=*/false) {}
  3237. };
  3238. TEST_P(BestEffortsRecoverIncompleteVersionTest, Basic) {
  3239. Options options = CurrentOptions();
  3240. options.enable_blob_files = std::get<0>(GetParam());
  3241. bool delete_blob_file_too = std::get<1>(GetParam());
  3242. DestroyAndReopen(options);
  3243. FlushTableFileListener* flush_table_listener = new FlushTableFileListener();
  3244. FlushBlobFileListener* flush_blob_listener = new FlushBlobFileListener();
  3245. // Disable auto compaction to simplify SST file name tracking.
  3246. options.disable_auto_compactions = true;
  3247. options.listeners.emplace_back(flush_table_listener);
  3248. options.listeners.emplace_back(flush_blob_listener);
  3249. CreateAndReopenWithCF({"pikachu", "eevee"}, options);
  3250. std::vector<std::string> all_cf_names = {kDefaultColumnFamilyName, "pikachu",
  3251. "eevee"};
  3252. int num_cfs = static_cast<int>(handles_.size());
  3253. ASSERT_EQ(3, num_cfs);
  3254. std::string start = "a";
  3255. Slice start_slice = start;
  3256. std::string end = "d";
  3257. Slice end_slice = end;
  3258. for (int cf = 0; cf != num_cfs; ++cf) {
  3259. ASSERT_OK(Put(cf, "a", "a_value"));
  3260. ASSERT_OK(Flush(cf));
  3261. // Compact file to L1 to avoid trivial file move in the next compaction
  3262. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), handles_[cf],
  3263. &start_slice, &end_slice));
  3264. ASSERT_OK(Put(cf, "a", "a_value_new"));
  3265. ASSERT_OK(Flush(cf));
  3266. ASSERT_OK(Put(cf, "b", "b_value"));
  3267. ASSERT_OK(Flush(cf));
  3268. ASSERT_OK(Put(cf, "f", "f_value"));
  3269. ASSERT_OK(Flush(cf));
  3270. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), handles_[cf],
  3271. &start_slice, &end_slice));
  3272. }
  3273. dbfull()->TEST_DeleteObsoleteFiles();
  3274. // Delete the most recent L0 file which is before a compaction.
  3275. for (int i = 0; i < num_cfs; ++i) {
  3276. std::vector<std::string>& files =
  3277. flush_table_listener->GetFlushedFiles(all_cf_names[i]);
  3278. ASSERT_EQ(4, files.size());
  3279. ASSERT_OK(env_->DeleteFile(files[files.size() - 1]));
  3280. if (options.enable_blob_files) {
  3281. std::vector<std::string>& blob_files =
  3282. flush_blob_listener->GetFlushedBlobFiles(all_cf_names[i]);
  3283. ASSERT_EQ(4, blob_files.size());
  3284. if (delete_blob_file_too) {
  3285. ASSERT_OK(env_->DeleteFile(blob_files[files.size() - 1]));
  3286. }
  3287. }
  3288. }
  3289. options.best_efforts_recovery = true;
  3290. ReopenWithColumnFamilies(all_cf_names, options);
  3291. for (int i = 0; i < num_cfs; ++i) {
  3292. auto cfh = static_cast<ColumnFamilyHandleImpl*>(handles_[i]);
  3293. ColumnFamilyData* cfd = cfh->cfd();
  3294. VersionStorageInfo* vstorage = cfd->current()->storage_info();
  3295. // The L0 file flushed right before the last compaction is missing.
  3296. ASSERT_EQ(0, vstorage->LevelFiles(0).size());
  3297. // Only the output of the last compaction is available.
  3298. ASSERT_EQ(1, vstorage->LevelFiles(1).size());
  3299. }
  3300. // Verify data
  3301. ReadOptions read_opts;
  3302. read_opts.total_order_seek = true;
  3303. for (int i = 0; i < num_cfs; ++i) {
  3304. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts, handles_[i]));
  3305. iter->SeekToFirst();
  3306. ASSERT_TRUE(iter->Valid());
  3307. ASSERT_OK(iter->status());
  3308. ASSERT_EQ("a", iter->key());
  3309. ASSERT_EQ("a_value_new", iter->value());
  3310. iter->Next();
  3311. ASSERT_TRUE(iter->Valid());
  3312. ASSERT_OK(iter->status());
  3313. ASSERT_EQ("b", iter->key());
  3314. ASSERT_EQ("b_value", iter->value());
  3315. iter->Next();
  3316. ASSERT_FALSE(iter->Valid());
  3317. ASSERT_OK(iter->status());
  3318. }
  3319. // Write more data.
  3320. for (int cf = 0; cf < num_cfs; ++cf) {
  3321. ASSERT_OK(Put(cf, "g", "g_value"));
  3322. ASSERT_OK(Flush(cf));
  3323. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), handles_[cf], nullptr,
  3324. nullptr));
  3325. std::string value;
  3326. ASSERT_OK(db_->Get(ReadOptions(), handles_[cf], "g", &value));
  3327. ASSERT_EQ("g_value", value);
  3328. }
  3329. }
  3330. INSTANTIATE_TEST_CASE_P(BestEffortsRecoverIncompleteVersionTest,
  3331. BestEffortsRecoverIncompleteVersionTest,
  3332. testing::Values(std::make_tuple(false, false),
  3333. std::make_tuple(true, false),
  3334. std::make_tuple(true, true)));
  3335. TEST_F(DBBasicTest, BestEffortsRecoveryTryMultipleManifests) {
  3336. Options options = CurrentOptions();
  3337. options.env = env_;
  3338. DestroyAndReopen(options);
  3339. ASSERT_OK(Put("foo", "value0"));
  3340. ASSERT_OK(Flush());
  3341. Close();
  3342. {
  3343. // Hack by adding a new MANIFEST with high file number
  3344. std::string garbage(10, '\0');
  3345. ASSERT_OK(WriteStringToFile(env_, garbage, dbname_ + "/MANIFEST-001000",
  3346. /*should_sync=*/true));
  3347. }
  3348. {
  3349. // Hack by adding a corrupted SST not referenced by any MANIFEST
  3350. std::string garbage(10, '\0');
  3351. ASSERT_OK(WriteStringToFile(env_, garbage, dbname_ + "/001001.sst",
  3352. /*should_sync=*/true));
  3353. }
  3354. options.best_efforts_recovery = true;
  3355. Reopen(options);
  3356. ASSERT_OK(Put("bar", "value"));
  3357. }
  3358. TEST_F(DBBasicTest, RecoverWithNoCurrentFile) {
  3359. Options options = CurrentOptions();
  3360. options.env = env_;
  3361. DestroyAndReopen(options);
  3362. CreateAndReopenWithCF({"pikachu"}, options);
  3363. options.best_efforts_recovery = true;
  3364. ReopenWithColumnFamilies({kDefaultColumnFamilyName, "pikachu"}, options);
  3365. ASSERT_EQ(2, handles_.size());
  3366. ASSERT_OK(Put("foo", "value"));
  3367. ASSERT_OK(Put(1, "bar", "value"));
  3368. ASSERT_OK(Flush());
  3369. ASSERT_OK(Flush(1));
  3370. Close();
  3371. ASSERT_OK(env_->DeleteFile(CurrentFileName(dbname_)));
  3372. ReopenWithColumnFamilies({kDefaultColumnFamilyName, "pikachu"}, options);
  3373. std::vector<std::string> cf_names;
  3374. ASSERT_OK(DB::ListColumnFamilies(DBOptions(options), dbname_, &cf_names));
  3375. ASSERT_EQ(2, cf_names.size());
  3376. for (const auto& name : cf_names) {
  3377. ASSERT_TRUE(name == kDefaultColumnFamilyName || name == "pikachu");
  3378. }
  3379. }
  3380. TEST_F(DBBasicTest, RecoverWithNoManifest) {
  3381. Options options = CurrentOptions();
  3382. options.env = env_;
  3383. DestroyAndReopen(options);
  3384. ASSERT_OK(Put("foo", "value"));
  3385. ASSERT_OK(Flush());
  3386. Close();
  3387. {
  3388. // Delete all MANIFEST.
  3389. std::vector<std::string> files;
  3390. ASSERT_OK(env_->GetChildren(dbname_, &files));
  3391. for (const auto& file : files) {
  3392. uint64_t number = 0;
  3393. FileType type = kWalFile;
  3394. if (ParseFileName(file, &number, &type) && type == kDescriptorFile) {
  3395. ASSERT_OK(env_->DeleteFile(dbname_ + "/" + file));
  3396. }
  3397. }
  3398. }
  3399. options.best_efforts_recovery = true;
  3400. options.create_if_missing = false;
  3401. Status s = TryReopen(options);
  3402. ASSERT_TRUE(s.IsInvalidArgument());
  3403. options.create_if_missing = true;
  3404. Reopen(options);
  3405. // Since no MANIFEST exists, best-efforts recovery creates a new, empty db.
  3406. ASSERT_EQ("NOT_FOUND", Get("foo"));
  3407. }
  3408. TEST_F(DBBasicTest, SkipWALIfMissingTableFiles) {
  3409. Options options = CurrentOptions();
  3410. DestroyAndReopen(options);
  3411. TableFileListener* listener = new TableFileListener();
  3412. options.listeners.emplace_back(listener);
  3413. CreateAndReopenWithCF({"pikachu"}, options);
  3414. std::vector<std::string> kAllCfNames = {kDefaultColumnFamilyName, "pikachu"};
  3415. size_t num_cfs = handles_.size();
  3416. ASSERT_EQ(2, num_cfs);
  3417. for (int cf = 0; cf < static_cast<int>(kAllCfNames.size()); ++cf) {
  3418. ASSERT_OK(Put(cf, "a", "0_value"));
  3419. ASSERT_OK(Flush(cf));
  3420. ASSERT_OK(Put(cf, "b", "0_value"));
  3421. }
  3422. // Delete files
  3423. for (size_t i = 0; i < kAllCfNames.size(); ++i) {
  3424. std::vector<std::string>& files = listener->GetFiles(kAllCfNames[i]);
  3425. ASSERT_EQ(1, files.size());
  3426. for (int j = static_cast<int>(files.size() - 1); j >= static_cast<int>(i);
  3427. --j) {
  3428. ASSERT_OK(env_->DeleteFile(files[j]));
  3429. }
  3430. }
  3431. options.best_efforts_recovery = true;
  3432. ReopenWithColumnFamilies(kAllCfNames, options);
  3433. // Verify WAL is not applied
  3434. ReadOptions read_opts;
  3435. read_opts.total_order_seek = true;
  3436. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts, handles_[0]));
  3437. iter->SeekToFirst();
  3438. ASSERT_FALSE(iter->Valid());
  3439. ASSERT_OK(iter->status());
  3440. iter.reset(db_->NewIterator(read_opts, handles_[1]));
  3441. iter->SeekToFirst();
  3442. ASSERT_TRUE(iter->Valid());
  3443. ASSERT_EQ("a", iter->key());
  3444. iter->Next();
  3445. ASSERT_FALSE(iter->Valid());
  3446. ASSERT_OK(iter->status());
  3447. }
  3448. TEST_F(DBBasicTest, DisableTrackWal) {
  3449. // If WAL tracking was enabled, and then disabled during reopen,
  3450. // the previously tracked WALs should be removed from MANIFEST.
  3451. Options options = CurrentOptions();
  3452. options.track_and_verify_wals_in_manifest = true;
  3453. // extremely small write buffer size,
  3454. // so that new WALs are created more frequently.
  3455. options.write_buffer_size = 100;
  3456. options.env = env_;
  3457. DestroyAndReopen(options);
  3458. for (int i = 0; i < 100; i++) {
  3459. ASSERT_OK(Put("foo" + std::to_string(i), "value" + std::to_string(i)));
  3460. }
  3461. ASSERT_OK(dbfull()->TEST_SwitchMemtable());
  3462. ASSERT_OK(db_->SyncWAL());
  3463. // Some WALs are tracked.
  3464. ASSERT_FALSE(dbfull()->GetVersionSet()->GetWalSet().GetWals().empty());
  3465. Close();
  3466. // Disable WAL tracking.
  3467. options.track_and_verify_wals_in_manifest = false;
  3468. options.create_if_missing = false;
  3469. ASSERT_OK(TryReopen(options));
  3470. // Previously tracked WALs are cleared.
  3471. ASSERT_TRUE(dbfull()->GetVersionSet()->GetWalSet().GetWals().empty());
  3472. Close();
  3473. // Re-enable WAL tracking again.
  3474. options.track_and_verify_wals_in_manifest = true;
  3475. options.create_if_missing = false;
  3476. ASSERT_OK(TryReopen(options));
  3477. ASSERT_TRUE(dbfull()->GetVersionSet()->GetWalSet().GetWals().empty());
  3478. Close();
  3479. }
  3480. TEST_F(DBBasicTest, ManifestChecksumMismatch) {
  3481. Options options = CurrentOptions();
  3482. DestroyAndReopen(options);
  3483. ASSERT_OK(Put("bar", "value"));
  3484. ASSERT_OK(Flush());
  3485. SyncPoint::GetInstance()->DisableProcessing();
  3486. SyncPoint::GetInstance()->ClearAllCallBacks();
  3487. SyncPoint::GetInstance()->SetCallBack(
  3488. "LogWriter::EmitPhysicalRecord:BeforeEncodeChecksum", [&](void* arg) {
  3489. auto* crc = reinterpret_cast<uint32_t*>(arg);
  3490. *crc = *crc + 1;
  3491. });
  3492. SyncPoint::GetInstance()->EnableProcessing();
  3493. WriteOptions write_opts;
  3494. write_opts.disableWAL = true;
  3495. Status s = db_->Put(write_opts, "foo", "value");
  3496. ASSERT_OK(s);
  3497. ASSERT_OK(Flush());
  3498. SyncPoint::GetInstance()->DisableProcessing();
  3499. SyncPoint::GetInstance()->ClearAllCallBacks();
  3500. ASSERT_OK(Put("foo", "value1"));
  3501. ASSERT_OK(Flush());
  3502. s = TryReopen(options);
  3503. ASSERT_TRUE(s.IsCorruption());
  3504. }
  3505. TEST_F(DBBasicTest, ConcurrentlyCloseDB) {
  3506. Options options = CurrentOptions();
  3507. DestroyAndReopen(options);
  3508. std::vector<std::thread> workers;
  3509. for (int i = 0; i < 10; i++) {
  3510. workers.emplace_back([&]() {
  3511. auto s = db_->Close();
  3512. ASSERT_OK(s);
  3513. });
  3514. }
  3515. for (auto& w : workers) {
  3516. w.join();
  3517. }
  3518. }
  3519. class DBBasicTestTrackWal : public DBTestBase,
  3520. public testing::WithParamInterface<bool> {
  3521. public:
  3522. DBBasicTestTrackWal()
  3523. : DBTestBase("db_basic_test_track_wal", /*env_do_fsync=*/false) {}
  3524. int CountWalFiles() {
  3525. VectorLogPtr log_files;
  3526. EXPECT_OK(dbfull()->GetSortedWalFiles(log_files));
  3527. return static_cast<int>(log_files.size());
  3528. };
  3529. };
  3530. TEST_P(DBBasicTestTrackWal, DoNotTrackObsoleteWal) {
  3531. // If a WAL becomes obsolete after flushing, but is not deleted from disk yet,
  3532. // then if SyncWAL is called afterwards, the obsolete WAL should not be
  3533. // tracked in MANIFEST.
  3534. Options options = CurrentOptions();
  3535. options.create_if_missing = true;
  3536. options.track_and_verify_wals_in_manifest = true;
  3537. options.atomic_flush = GetParam();
  3538. DestroyAndReopen(options);
  3539. CreateAndReopenWithCF({"cf"}, options);
  3540. ASSERT_EQ(handles_.size(), 2); // default, cf
  3541. // Do not delete WALs.
  3542. ASSERT_OK(db_->DisableFileDeletions());
  3543. constexpr int n = 10;
  3544. std::vector<std::unique_ptr<LogFile>> wals(n);
  3545. for (size_t i = 0; i < n; i++) {
  3546. // Generate a new WAL for each key-value.
  3547. const int cf = i % 2;
  3548. ASSERT_OK(db_->GetCurrentWalFile(&wals[i]));
  3549. ASSERT_OK(Put(cf, "k" + std::to_string(i), "v" + std::to_string(i)));
  3550. ASSERT_OK(Flush({0, 1}));
  3551. }
  3552. ASSERT_EQ(CountWalFiles(), n);
  3553. // Since all WALs are obsolete, no WAL should be tracked in MANIFEST.
  3554. ASSERT_OK(db_->SyncWAL());
  3555. // Manually delete all WALs.
  3556. Close();
  3557. for (const auto& wal : wals) {
  3558. ASSERT_OK(env_->DeleteFile(LogFileName(dbname_, wal->LogNumber())));
  3559. }
  3560. // If SyncWAL tracks the obsolete WALs in MANIFEST,
  3561. // reopen will fail because the WALs are missing from disk.
  3562. ASSERT_OK(TryReopenWithColumnFamilies({"default", "cf"}, options));
  3563. Destroy(options);
  3564. }
  3565. INSTANTIATE_TEST_CASE_P(DBBasicTestTrackWal, DBBasicTestTrackWal,
  3566. testing::Bool());
  3567. class DBBasicTestMultiGet : public DBTestBase {
  3568. public:
  3569. DBBasicTestMultiGet(std::string test_dir, int num_cfs,
  3570. bool uncompressed_cache, bool _compression_enabled,
  3571. bool _fill_cache, uint32_t compression_parallel_threads)
  3572. : DBTestBase(test_dir, /*env_do_fsync=*/false) {
  3573. compression_enabled_ = _compression_enabled;
  3574. fill_cache_ = _fill_cache;
  3575. if (uncompressed_cache) {
  3576. std::shared_ptr<Cache> cache = NewLRUCache(1048576);
  3577. uncompressed_cache_ = std::make_shared<MyBlockCache>(cache);
  3578. }
  3579. env_->count_random_reads_ = true;
  3580. Options options = CurrentOptions();
  3581. Random rnd(301);
  3582. BlockBasedTableOptions table_options;
  3583. if (compression_enabled_) {
  3584. std::vector<CompressionType> compression_types;
  3585. compression_types = GetSupportedCompressions();
  3586. // Not every platform may have compression libraries available, so
  3587. // dynamically pick based on what's available
  3588. CompressionType tmp_type = kNoCompression;
  3589. for (auto c_type : compression_types) {
  3590. if (c_type != kNoCompression) {
  3591. tmp_type = c_type;
  3592. break;
  3593. }
  3594. }
  3595. if (tmp_type != kNoCompression) {
  3596. options.compression = tmp_type;
  3597. } else {
  3598. compression_enabled_ = false;
  3599. }
  3600. }
  3601. table_options.block_cache = uncompressed_cache_;
  3602. if (table_options.block_cache == nullptr) {
  3603. table_options.no_block_cache = true;
  3604. } else {
  3605. table_options.pin_l0_filter_and_index_blocks_in_cache = true;
  3606. }
  3607. table_options.flush_block_policy_factory.reset(
  3608. new MyFlushBlockPolicyFactory(10));
  3609. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3610. if (!compression_enabled_) {
  3611. options.compression = kNoCompression;
  3612. } else {
  3613. options.compression_opts.parallel_threads = compression_parallel_threads;
  3614. }
  3615. options_ = options;
  3616. Reopen(options);
  3617. if (num_cfs > 1) {
  3618. for (int cf = 0; cf < num_cfs; ++cf) {
  3619. cf_names_.emplace_back("cf" + std::to_string(cf));
  3620. }
  3621. CreateColumnFamilies(cf_names_, options);
  3622. cf_names_.emplace_back("default");
  3623. }
  3624. std::string zero_str(128, '\0');
  3625. for (int cf = 0; cf < num_cfs; ++cf) {
  3626. for (int i = 0; i < 100; ++i) {
  3627. // Make the value compressible. A purely random string doesn't compress
  3628. // and the resultant data block will not be compressed
  3629. values_.emplace_back(rnd.RandomString(128) + zero_str);
  3630. assert(((num_cfs == 1) ? Put(Key(i), values_[i])
  3631. : Put(cf, Key(i), values_[i])) == Status::OK());
  3632. }
  3633. if (num_cfs == 1) {
  3634. EXPECT_OK(Flush());
  3635. } else {
  3636. EXPECT_OK(dbfull()->Flush(FlushOptions(), handles_[cf]));
  3637. }
  3638. for (int i = 0; i < 100; ++i) {
  3639. // block cannot gain space by compression
  3640. uncompressable_values_.emplace_back(rnd.RandomString(256) + '\0');
  3641. std::string tmp_key = "a" + Key(i);
  3642. assert(((num_cfs == 1) ? Put(tmp_key, uncompressable_values_[i])
  3643. : Put(cf, tmp_key, uncompressable_values_[i])) ==
  3644. Status::OK());
  3645. }
  3646. if (num_cfs == 1) {
  3647. EXPECT_OK(Flush());
  3648. } else {
  3649. EXPECT_OK(dbfull()->Flush(FlushOptions(), handles_[cf]));
  3650. }
  3651. }
  3652. // Clear compressed cache, which is always pre-populated
  3653. if (compressed_cache_) {
  3654. compressed_cache_->SetCapacity(0);
  3655. compressed_cache_->SetCapacity(1048576);
  3656. }
  3657. }
  3658. bool CheckValue(int i, const std::string& value) {
  3659. if (values_[i].compare(value) == 0) {
  3660. return true;
  3661. }
  3662. return false;
  3663. }
  3664. bool CheckUncompressableValue(int i, const std::string& value) {
  3665. if (uncompressable_values_[i].compare(value) == 0) {
  3666. return true;
  3667. }
  3668. return false;
  3669. }
  3670. const std::vector<std::string>& GetCFNames() const { return cf_names_; }
  3671. int num_lookups() { return uncompressed_cache_->num_lookups(); }
  3672. int num_found() { return uncompressed_cache_->num_found(); }
  3673. int num_inserts() { return uncompressed_cache_->num_inserts(); }
  3674. int num_lookups_compressed() { return compressed_cache_->num_lookups(); }
  3675. int num_found_compressed() { return compressed_cache_->num_found(); }
  3676. int num_inserts_compressed() { return compressed_cache_->num_inserts(); }
  3677. bool fill_cache() { return fill_cache_; }
  3678. bool compression_enabled() { return compression_enabled_; }
  3679. bool has_compressed_cache() { return compressed_cache_ != nullptr; }
  3680. bool has_uncompressed_cache() { return uncompressed_cache_ != nullptr; }
  3681. Options get_options() { return options_; }
  3682. static void SetUpTestCase() {}
  3683. static void TearDownTestCase() {}
  3684. protected:
  3685. class MyBlockCache : public CacheWrapper {
  3686. public:
  3687. explicit MyBlockCache(std::shared_ptr<Cache> target)
  3688. : CacheWrapper(target),
  3689. num_lookups_(0),
  3690. num_found_(0),
  3691. num_inserts_(0) {}
  3692. const char* Name() const override { return "MyBlockCache"; }
  3693. Status Insert(const Slice& key, Cache::ObjectPtr value,
  3694. const CacheItemHelper* helper, size_t charge,
  3695. Handle** handle = nullptr, Priority priority = Priority::LOW,
  3696. const Slice& compressed = Slice(),
  3697. CompressionType type = kNoCompression) override {
  3698. num_inserts_++;
  3699. return target_->Insert(key, value, helper, charge, handle, priority,
  3700. compressed, type);
  3701. }
  3702. Handle* Lookup(const Slice& key, const CacheItemHelper* helper,
  3703. CreateContext* create_context,
  3704. Priority priority = Priority::LOW,
  3705. Statistics* stats = nullptr) override {
  3706. num_lookups_++;
  3707. Handle* handle =
  3708. target_->Lookup(key, helper, create_context, priority, stats);
  3709. if (handle != nullptr) {
  3710. num_found_++;
  3711. }
  3712. return handle;
  3713. }
  3714. int num_lookups() { return num_lookups_; }
  3715. int num_found() { return num_found_; }
  3716. int num_inserts() { return num_inserts_; }
  3717. private:
  3718. int num_lookups_;
  3719. int num_found_;
  3720. int num_inserts_;
  3721. };
  3722. std::shared_ptr<MyBlockCache> compressed_cache_;
  3723. std::shared_ptr<MyBlockCache> uncompressed_cache_;
  3724. Options options_;
  3725. bool compression_enabled_;
  3726. std::vector<std::string> values_;
  3727. std::vector<std::string> uncompressable_values_;
  3728. bool fill_cache_;
  3729. std::vector<std::string> cf_names_;
  3730. };
  3731. class DBBasicTestWithParallelIO : public DBBasicTestMultiGet,
  3732. public testing::WithParamInterface<
  3733. std::tuple<bool, bool, bool, uint32_t>> {
  3734. public:
  3735. DBBasicTestWithParallelIO()
  3736. : DBBasicTestMultiGet("/db_basic_test_with_parallel_io", 1,
  3737. std::get<0>(GetParam()), std::get<1>(GetParam()),
  3738. std::get<2>(GetParam()), std::get<3>(GetParam())) {}
  3739. };
  3740. TEST_P(DBBasicTestWithParallelIO, MultiGet) {
  3741. std::vector<std::string> key_data(10);
  3742. std::vector<Slice> keys;
  3743. // We cannot resize a PinnableSlice vector, so just set initial size to
  3744. // largest we think we will need
  3745. std::vector<PinnableSlice> values(10);
  3746. std::vector<Status> statuses;
  3747. ReadOptions ro;
  3748. ro.fill_cache = fill_cache();
  3749. // Warm up the cache first
  3750. key_data.emplace_back(Key(0));
  3751. keys.emplace_back(key_data.back());
  3752. key_data.emplace_back(Key(50));
  3753. keys.emplace_back(key_data.back());
  3754. statuses.resize(keys.size());
  3755. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  3756. keys.data(), values.data(), statuses.data(), true);
  3757. ASSERT_TRUE(CheckValue(0, values[0].ToString()));
  3758. ASSERT_TRUE(CheckValue(50, values[1].ToString()));
  3759. int random_reads = env_->random_read_counter_.Read();
  3760. key_data[0] = Key(1);
  3761. key_data[1] = Key(51);
  3762. keys[0] = Slice(key_data[0]);
  3763. keys[1] = Slice(key_data[1]);
  3764. values[0].Reset();
  3765. values[1].Reset();
  3766. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  3767. keys.data(), values.data(), statuses.data(), true);
  3768. ASSERT_TRUE(CheckValue(1, values[0].ToString()));
  3769. ASSERT_TRUE(CheckValue(51, values[1].ToString()));
  3770. bool read_from_cache = false;
  3771. if (fill_cache()) {
  3772. if (has_uncompressed_cache()) {
  3773. read_from_cache = true;
  3774. } else if (has_compressed_cache() && compression_enabled()) {
  3775. read_from_cache = true;
  3776. }
  3777. }
  3778. int expected_reads = random_reads + (read_from_cache ? 0 : 2);
  3779. ASSERT_EQ(env_->random_read_counter_.Read(), expected_reads);
  3780. keys.resize(10);
  3781. statuses.resize(10);
  3782. std::vector<int> key_ints{1, 2, 15, 16, 55, 81, 82, 83, 84, 85};
  3783. for (size_t i = 0; i < key_ints.size(); ++i) {
  3784. key_data[i] = Key(key_ints[i]);
  3785. keys[i] = Slice(key_data[i]);
  3786. statuses[i] = Status::OK();
  3787. values[i].Reset();
  3788. }
  3789. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  3790. keys.data(), values.data(), statuses.data(), true);
  3791. for (size_t i = 0; i < key_ints.size(); ++i) {
  3792. ASSERT_OK(statuses[i]);
  3793. ASSERT_TRUE(CheckValue(key_ints[i], values[i].ToString()));
  3794. }
  3795. if (compression_enabled() && !has_compressed_cache()) {
  3796. expected_reads += (read_from_cache ? 2 : 3);
  3797. } else {
  3798. expected_reads += (read_from_cache ? 2 : 4);
  3799. }
  3800. ASSERT_EQ(env_->random_read_counter_.Read(), expected_reads);
  3801. keys.resize(10);
  3802. statuses.resize(10);
  3803. std::vector<int> key_uncmp{1, 2, 15, 16, 55, 81, 82, 83, 84, 85};
  3804. for (size_t i = 0; i < key_uncmp.size(); ++i) {
  3805. key_data[i] = "a" + Key(key_uncmp[i]);
  3806. keys[i] = Slice(key_data[i]);
  3807. statuses[i] = Status::OK();
  3808. values[i].Reset();
  3809. }
  3810. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  3811. keys.data(), values.data(), statuses.data(), true);
  3812. for (size_t i = 0; i < key_uncmp.size(); ++i) {
  3813. ASSERT_OK(statuses[i]);
  3814. ASSERT_TRUE(CheckUncompressableValue(key_uncmp[i], values[i].ToString()));
  3815. }
  3816. if (compression_enabled() && !has_compressed_cache()) {
  3817. expected_reads += (read_from_cache ? 3 : 3);
  3818. } else {
  3819. expected_reads += (read_from_cache ? 4 : 4);
  3820. }
  3821. ASSERT_EQ(env_->random_read_counter_.Read(), expected_reads);
  3822. keys.resize(5);
  3823. statuses.resize(5);
  3824. std::vector<int> key_tr{1, 2, 15, 16, 55};
  3825. for (size_t i = 0; i < key_tr.size(); ++i) {
  3826. key_data[i] = "a" + Key(key_tr[i]);
  3827. keys[i] = Slice(key_data[i]);
  3828. statuses[i] = Status::OK();
  3829. values[i].Reset();
  3830. }
  3831. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  3832. keys.data(), values.data(), statuses.data(), true);
  3833. for (size_t i = 0; i < key_tr.size(); ++i) {
  3834. ASSERT_OK(statuses[i]);
  3835. ASSERT_TRUE(CheckUncompressableValue(key_tr[i], values[i].ToString()));
  3836. }
  3837. if (compression_enabled() && !has_compressed_cache()) {
  3838. expected_reads += (read_from_cache ? 0 : 2);
  3839. ASSERT_EQ(env_->random_read_counter_.Read(), expected_reads);
  3840. } else {
  3841. if (has_uncompressed_cache()) {
  3842. expected_reads += (read_from_cache ? 0 : 3);
  3843. ASSERT_EQ(env_->random_read_counter_.Read(), expected_reads);
  3844. } else {
  3845. // A rare case, even we enable the block compression but some of data
  3846. // blocks are not compressed due to content. If user only enable the
  3847. // compressed cache, the uncompressed blocks will not tbe cached, and
  3848. // block reads will be triggered. The number of reads is related to
  3849. // the compression algorithm.
  3850. ASSERT_TRUE(env_->random_read_counter_.Read() >= expected_reads);
  3851. }
  3852. }
  3853. }
  3854. TEST_P(DBBasicTestWithParallelIO, MultiGetDirectIO) {
  3855. class FakeDirectIOEnv : public EnvWrapper {
  3856. class FakeDirectIOSequentialFile;
  3857. class FakeDirectIORandomAccessFile;
  3858. public:
  3859. FakeDirectIOEnv(Env* env) : EnvWrapper(env) {}
  3860. static const char* kClassName() { return "FakeDirectIOEnv"; }
  3861. const char* Name() const override { return kClassName(); }
  3862. Status NewRandomAccessFile(const std::string& fname,
  3863. std::unique_ptr<RandomAccessFile>* result,
  3864. const EnvOptions& options) override {
  3865. std::unique_ptr<RandomAccessFile> file;
  3866. assert(options.use_direct_reads);
  3867. EnvOptions opts = options;
  3868. opts.use_direct_reads = false;
  3869. Status s = target()->NewRandomAccessFile(fname, &file, opts);
  3870. if (!s.ok()) {
  3871. return s;
  3872. }
  3873. result->reset(new FakeDirectIORandomAccessFile(std::move(file)));
  3874. return s;
  3875. }
  3876. private:
  3877. class FakeDirectIOSequentialFile : public SequentialFileWrapper {
  3878. public:
  3879. FakeDirectIOSequentialFile(std::unique_ptr<SequentialFile>&& file)
  3880. : SequentialFileWrapper(file.get()), file_(std::move(file)) {}
  3881. ~FakeDirectIOSequentialFile() {}
  3882. bool use_direct_io() const override { return true; }
  3883. size_t GetRequiredBufferAlignment() const override { return 1; }
  3884. private:
  3885. std::unique_ptr<SequentialFile> file_;
  3886. };
  3887. class FakeDirectIORandomAccessFile : public RandomAccessFileWrapper {
  3888. public:
  3889. FakeDirectIORandomAccessFile(std::unique_ptr<RandomAccessFile>&& file)
  3890. : RandomAccessFileWrapper(file.get()), file_(std::move(file)) {}
  3891. ~FakeDirectIORandomAccessFile() {}
  3892. bool use_direct_io() const override { return true; }
  3893. size_t GetRequiredBufferAlignment() const override { return 1; }
  3894. private:
  3895. std::unique_ptr<RandomAccessFile> file_;
  3896. };
  3897. };
  3898. std::unique_ptr<FakeDirectIOEnv> env(new FakeDirectIOEnv(env_));
  3899. Options opts = get_options();
  3900. opts.env = env.get();
  3901. opts.use_direct_reads = true;
  3902. Reopen(opts);
  3903. std::vector<std::string> key_data(10);
  3904. std::vector<Slice> keys;
  3905. // We cannot resize a PinnableSlice vector, so just set initial size to
  3906. // largest we think we will need
  3907. std::vector<PinnableSlice> values(10);
  3908. std::vector<Status> statuses;
  3909. ReadOptions ro;
  3910. ro.fill_cache = fill_cache();
  3911. // Warm up the cache first
  3912. key_data.emplace_back(Key(0));
  3913. keys.emplace_back(key_data.back());
  3914. key_data.emplace_back(Key(50));
  3915. keys.emplace_back(key_data.back());
  3916. statuses.resize(keys.size());
  3917. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  3918. keys.data(), values.data(), statuses.data(), true);
  3919. ASSERT_TRUE(CheckValue(0, values[0].ToString()));
  3920. ASSERT_TRUE(CheckValue(50, values[1].ToString()));
  3921. int random_reads = env_->random_read_counter_.Read();
  3922. key_data[0] = Key(1);
  3923. key_data[1] = Key(51);
  3924. keys[0] = Slice(key_data[0]);
  3925. keys[1] = Slice(key_data[1]);
  3926. values[0].Reset();
  3927. values[1].Reset();
  3928. if (uncompressed_cache_) {
  3929. uncompressed_cache_->SetCapacity(0);
  3930. uncompressed_cache_->SetCapacity(1048576);
  3931. }
  3932. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  3933. keys.data(), values.data(), statuses.data(), true);
  3934. ASSERT_TRUE(CheckValue(1, values[0].ToString()));
  3935. ASSERT_TRUE(CheckValue(51, values[1].ToString()));
  3936. bool read_from_cache = false;
  3937. if (fill_cache()) {
  3938. if (has_uncompressed_cache()) {
  3939. read_from_cache = true;
  3940. } else if (has_compressed_cache() && compression_enabled()) {
  3941. read_from_cache = true;
  3942. }
  3943. }
  3944. int expected_reads = random_reads;
  3945. if (!compression_enabled() || !has_compressed_cache()) {
  3946. expected_reads += 2;
  3947. } else {
  3948. expected_reads += (read_from_cache ? 0 : 2);
  3949. }
  3950. if (env_->random_read_counter_.Read() != expected_reads) {
  3951. ASSERT_EQ(env_->random_read_counter_.Read(), expected_reads);
  3952. }
  3953. Close();
  3954. }
  3955. TEST_P(DBBasicTestWithParallelIO, MultiGetWithChecksumMismatch) {
  3956. std::vector<std::string> key_data(10);
  3957. std::vector<Slice> keys;
  3958. // We cannot resize a PinnableSlice vector, so just set initial size to
  3959. // largest we think we will need
  3960. std::vector<PinnableSlice> values(10);
  3961. std::vector<Status> statuses;
  3962. int read_count = 0;
  3963. ReadOptions ro;
  3964. ro.fill_cache = fill_cache();
  3965. SyncPoint::GetInstance()->SetCallBack(
  3966. "RetrieveMultipleBlocks:VerifyChecksum", [&](void* status) {
  3967. Status* s = static_cast<Status*>(status);
  3968. read_count++;
  3969. if (read_count == 2) {
  3970. *s = Status::Corruption();
  3971. }
  3972. });
  3973. SyncPoint::GetInstance()->EnableProcessing();
  3974. // Warm up the cache first
  3975. key_data.emplace_back(Key(0));
  3976. keys.emplace_back(key_data.back());
  3977. key_data.emplace_back(Key(50));
  3978. keys.emplace_back(key_data.back());
  3979. statuses.resize(keys.size());
  3980. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  3981. keys.data(), values.data(), statuses.data(), true);
  3982. ASSERT_TRUE(CheckValue(0, values[0].ToString()));
  3983. // ASSERT_TRUE(CheckValue(50, values[1].ToString()));
  3984. ASSERT_EQ(statuses[0], Status::OK());
  3985. ASSERT_EQ(statuses[1], Status::Corruption());
  3986. SyncPoint::GetInstance()->DisableProcessing();
  3987. }
  3988. TEST_P(DBBasicTestWithParallelIO, MultiGetWithMissingFile) {
  3989. std::vector<std::string> key_data(10);
  3990. std::vector<Slice> keys;
  3991. // We cannot resize a PinnableSlice vector, so just set initial size to
  3992. // largest we think we will need
  3993. std::vector<PinnableSlice> values(10);
  3994. std::vector<Status> statuses;
  3995. ReadOptions ro;
  3996. ro.fill_cache = fill_cache();
  3997. SyncPoint::GetInstance()->SetCallBack(
  3998. "TableCache::MultiGet:FindTable", [&](void* status) {
  3999. Status* s = static_cast<Status*>(status);
  4000. *s = Status::IOError();
  4001. });
  4002. // DB open will create table readers unless we reduce the table cache
  4003. // capacity.
  4004. // SanitizeOptions will set max_open_files to minimum of 20. Table cache
  4005. // is allocated with max_open_files - 10 as capacity. So override
  4006. // max_open_files to 11 so table cache capacity will become 1. This will
  4007. // prevent file open during DB open and force the file to be opened
  4008. // during MultiGet
  4009. SyncPoint::GetInstance()->SetCallBack(
  4010. "SanitizeOptions::AfterChangeMaxOpenFiles", [&](void* arg) {
  4011. int* max_open_files = (int*)arg;
  4012. *max_open_files = 11;
  4013. });
  4014. SyncPoint::GetInstance()->EnableProcessing();
  4015. Reopen(CurrentOptions());
  4016. // Warm up the cache first
  4017. key_data.emplace_back(Key(0));
  4018. keys.emplace_back(key_data.back());
  4019. key_data.emplace_back(Key(50));
  4020. keys.emplace_back(key_data.back());
  4021. statuses.resize(keys.size());
  4022. dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
  4023. keys.data(), values.data(), statuses.data(), true);
  4024. ASSERT_EQ(statuses[0], Status::IOError());
  4025. ASSERT_EQ(statuses[1], Status::IOError());
  4026. SyncPoint::GetInstance()->DisableProcessing();
  4027. }
  4028. INSTANTIATE_TEST_CASE_P(ParallelIO, DBBasicTestWithParallelIO,
  4029. // Params are as follows -
  4030. // Param 0 - Uncompressed cache enabled
  4031. // Param 1 - Data compression enabled
  4032. // Param 2 - ReadOptions::fill_cache
  4033. // Param 3 - CompressionOptions::parallel_threads
  4034. ::testing::Combine(::testing::Bool(), ::testing::Bool(),
  4035. ::testing::Bool(),
  4036. ::testing::Values(1, 4)));
  4037. // Forward declaration
  4038. class DeadlineFS;
  4039. class DeadlineRandomAccessFile : public FSRandomAccessFileOwnerWrapper {
  4040. public:
  4041. DeadlineRandomAccessFile(DeadlineFS& fs,
  4042. std::unique_ptr<FSRandomAccessFile>& file)
  4043. : FSRandomAccessFileOwnerWrapper(std::move(file)), fs_(fs) {}
  4044. IOStatus Read(uint64_t offset, size_t len, const IOOptions& opts,
  4045. Slice* result, char* scratch,
  4046. IODebugContext* dbg) const override;
  4047. IOStatus MultiRead(FSReadRequest* reqs, size_t num_reqs,
  4048. const IOOptions& options, IODebugContext* dbg) override;
  4049. IOStatus ReadAsync(FSReadRequest& req, const IOOptions& opts,
  4050. std::function<void(FSReadRequest&, void*)> cb,
  4051. void* cb_arg, void** io_handle, IOHandleDeleter* del_fn,
  4052. IODebugContext* dbg) override;
  4053. private:
  4054. DeadlineFS& fs_;
  4055. std::unique_ptr<FSRandomAccessFile> file_;
  4056. };
  4057. class DeadlineFS : public FileSystemWrapper {
  4058. public:
  4059. // The error_on_delay parameter specifies whether a IOStatus::TimedOut()
  4060. // status should be returned after delaying the IO to exceed the timeout,
  4061. // or to simply delay but return success anyway. The latter mimics the
  4062. // behavior of PosixFileSystem, which does not enforce any timeout
  4063. explicit DeadlineFS(SpecialEnv* env, bool error_on_delay)
  4064. : FileSystemWrapper(env->GetFileSystem()),
  4065. deadline_(std::chrono::microseconds::zero()),
  4066. io_timeout_(std::chrono::microseconds::zero()),
  4067. env_(env),
  4068. timedout_(false),
  4069. ignore_deadline_(false),
  4070. error_on_delay_(error_on_delay) {}
  4071. static const char* kClassName() { return "DeadlineFileSystem"; }
  4072. const char* Name() const override { return kClassName(); }
  4073. IOStatus NewRandomAccessFile(const std::string& fname,
  4074. const FileOptions& opts,
  4075. std::unique_ptr<FSRandomAccessFile>* result,
  4076. IODebugContext* dbg) override {
  4077. std::unique_ptr<FSRandomAccessFile> file;
  4078. IOStatus s = target()->NewRandomAccessFile(fname, opts, &file, dbg);
  4079. EXPECT_OK(s);
  4080. result->reset(new DeadlineRandomAccessFile(*this, file));
  4081. const std::chrono::microseconds deadline = GetDeadline();
  4082. const std::chrono::microseconds io_timeout = GetIOTimeout();
  4083. if (deadline.count() || io_timeout.count()) {
  4084. AssertDeadline(deadline, io_timeout, opts.io_options);
  4085. }
  4086. return ShouldDelay(opts.io_options);
  4087. }
  4088. // Set a vector of {IO counter, delay in microseconds, return status} tuples
  4089. // that control when to inject a delay and duration of the delay
  4090. void SetDelayTrigger(const std::chrono::microseconds deadline,
  4091. const std::chrono::microseconds io_timeout,
  4092. const int trigger) {
  4093. delay_trigger_ = trigger;
  4094. io_count_ = 0;
  4095. deadline_ = deadline;
  4096. io_timeout_ = io_timeout;
  4097. timedout_ = false;
  4098. }
  4099. // Increment the IO counter and return a delay in microseconds
  4100. IOStatus ShouldDelay(const IOOptions& opts) {
  4101. if (timedout_) {
  4102. return IOStatus::TimedOut();
  4103. } else if (!deadline_.count() && !io_timeout_.count()) {
  4104. return IOStatus::OK();
  4105. }
  4106. if (!ignore_deadline_ && delay_trigger_ == io_count_++) {
  4107. env_->SleepForMicroseconds(static_cast<int>(opts.timeout.count() + 1));
  4108. timedout_ = true;
  4109. if (error_on_delay_) {
  4110. return IOStatus::TimedOut();
  4111. }
  4112. }
  4113. return IOStatus::OK();
  4114. }
  4115. const std::chrono::microseconds GetDeadline() {
  4116. return ignore_deadline_ ? std::chrono::microseconds::zero() : deadline_;
  4117. }
  4118. const std::chrono::microseconds GetIOTimeout() {
  4119. return ignore_deadline_ ? std::chrono::microseconds::zero() : io_timeout_;
  4120. }
  4121. bool TimedOut() { return timedout_; }
  4122. void IgnoreDeadline(bool ignore) { ignore_deadline_ = ignore; }
  4123. void AssertDeadline(const std::chrono::microseconds deadline,
  4124. const std::chrono::microseconds io_timeout,
  4125. const IOOptions& opts) const {
  4126. // Give a leeway of +- 10us as it can take some time for the Get/
  4127. // MultiGet call to reach here, in order to avoid false alarms
  4128. std::chrono::microseconds now =
  4129. std::chrono::microseconds(env_->NowMicros());
  4130. std::chrono::microseconds timeout;
  4131. if (deadline.count()) {
  4132. timeout = deadline - now;
  4133. if (io_timeout.count()) {
  4134. timeout = std::min(timeout, io_timeout);
  4135. }
  4136. } else {
  4137. timeout = io_timeout;
  4138. }
  4139. if (opts.timeout != timeout) {
  4140. ASSERT_EQ(timeout, opts.timeout);
  4141. }
  4142. }
  4143. private:
  4144. // The number of IOs to trigger the delay after
  4145. int delay_trigger_;
  4146. // Current IO count
  4147. int io_count_;
  4148. // ReadOptions deadline for the Get/MultiGet/Iterator
  4149. std::chrono::microseconds deadline_;
  4150. // ReadOptions io_timeout for the Get/MultiGet/Iterator
  4151. std::chrono::microseconds io_timeout_;
  4152. SpecialEnv* env_;
  4153. // Flag to indicate whether we injected a delay
  4154. bool timedout_;
  4155. // Temporarily ignore deadlines/timeouts
  4156. bool ignore_deadline_;
  4157. // Return IOStatus::TimedOut() or IOStatus::OK()
  4158. bool error_on_delay_;
  4159. };
  4160. IOStatus DeadlineRandomAccessFile::Read(uint64_t offset, size_t len,
  4161. const IOOptions& opts, Slice* result,
  4162. char* scratch,
  4163. IODebugContext* dbg) const {
  4164. const std::chrono::microseconds deadline = fs_.GetDeadline();
  4165. const std::chrono::microseconds io_timeout = fs_.GetIOTimeout();
  4166. IOStatus s;
  4167. if (deadline.count() || io_timeout.count()) {
  4168. fs_.AssertDeadline(deadline, io_timeout, opts);
  4169. }
  4170. if (s.ok()) {
  4171. s = FSRandomAccessFileWrapper::Read(offset, len, opts, result, scratch,
  4172. dbg);
  4173. }
  4174. if (s.ok()) {
  4175. s = fs_.ShouldDelay(opts);
  4176. }
  4177. return s;
  4178. }
  4179. IOStatus DeadlineRandomAccessFile::ReadAsync(
  4180. FSReadRequest& req, const IOOptions& opts,
  4181. std::function<void(FSReadRequest&, void*)> cb, void* cb_arg,
  4182. void** io_handle, IOHandleDeleter* del_fn, IODebugContext* dbg) {
  4183. const std::chrono::microseconds deadline = fs_.GetDeadline();
  4184. const std::chrono::microseconds io_timeout = fs_.GetIOTimeout();
  4185. IOStatus s;
  4186. if (deadline.count() || io_timeout.count()) {
  4187. fs_.AssertDeadline(deadline, io_timeout, opts);
  4188. }
  4189. if (s.ok()) {
  4190. s = FSRandomAccessFileWrapper::ReadAsync(req, opts, cb, cb_arg, io_handle,
  4191. del_fn, dbg);
  4192. }
  4193. if (s.ok()) {
  4194. s = fs_.ShouldDelay(opts);
  4195. }
  4196. return s;
  4197. }
  4198. IOStatus DeadlineRandomAccessFile::MultiRead(FSReadRequest* reqs,
  4199. size_t num_reqs,
  4200. const IOOptions& options,
  4201. IODebugContext* dbg) {
  4202. const std::chrono::microseconds deadline = fs_.GetDeadline();
  4203. const std::chrono::microseconds io_timeout = fs_.GetIOTimeout();
  4204. IOStatus s;
  4205. if (deadline.count() || io_timeout.count()) {
  4206. fs_.AssertDeadline(deadline, io_timeout, options);
  4207. }
  4208. if (s.ok()) {
  4209. s = FSRandomAccessFileWrapper::MultiRead(reqs, num_reqs, options, dbg);
  4210. }
  4211. if (s.ok()) {
  4212. s = fs_.ShouldDelay(options);
  4213. }
  4214. return s;
  4215. }
  4216. // A test class for intercepting random reads and injecting artificial
  4217. // delays. Used for testing the MultiGet deadline feature
  4218. class DBBasicTestMultiGetDeadline : public DBBasicTestMultiGet,
  4219. public testing::WithParamInterface<bool> {
  4220. public:
  4221. DBBasicTestMultiGetDeadline()
  4222. : DBBasicTestMultiGet(
  4223. "db_basic_test_multiget_deadline" /*Test dir*/,
  4224. 10 /*# of column families*/, true /*uncompressed cache enabled*/,
  4225. true /*compression enabled*/, true /*ReadOptions.fill_cache*/,
  4226. 1 /*# of parallel compression threads*/) {}
  4227. inline void CheckStatus(std::vector<Status>& statuses, size_t num_ok) {
  4228. for (size_t i = 0; i < statuses.size(); ++i) {
  4229. if (i < num_ok) {
  4230. EXPECT_OK(statuses[i]);
  4231. } else {
  4232. if (statuses[i] != Status::TimedOut()) {
  4233. EXPECT_EQ(statuses[i], Status::TimedOut());
  4234. }
  4235. }
  4236. }
  4237. }
  4238. };
  4239. TEST_P(DBBasicTestMultiGetDeadline, MultiGetDeadlineExceeded) {
  4240. #ifndef USE_COROUTINES
  4241. if (GetParam()) {
  4242. ROCKSDB_GTEST_SKIP("This test requires coroutine support");
  4243. return;
  4244. }
  4245. #endif // USE_COROUTINES
  4246. std::shared_ptr<DeadlineFS> fs = std::make_shared<DeadlineFS>(env_, false);
  4247. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  4248. Options options = CurrentOptions();
  4249. std::shared_ptr<Cache> cache = NewLRUCache(1048576);
  4250. BlockBasedTableOptions table_options;
  4251. table_options.block_cache = cache;
  4252. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  4253. options.env = env.get();
  4254. SetTimeElapseOnlySleepOnReopen(&options);
  4255. ReopenWithColumnFamilies(GetCFNames(), options);
  4256. // Test batched MultiGet with an IO delay in the first data block read.
  4257. // Both keys in the first CF should succeed as they're in the same data
  4258. // block and would form one batch, and we check for deadline between
  4259. // batches.
  4260. std::vector<std::string> key_str;
  4261. size_t i;
  4262. for (i = 0; i < 10; ++i) {
  4263. key_str.emplace_back(Key(static_cast<int>(i)));
  4264. }
  4265. std::vector<ColumnFamilyHandle*> cfs(key_str.size());
  4266. std::vector<Slice> keys(key_str.size());
  4267. std::vector<PinnableSlice> pin_values(keys.size());
  4268. for (i = 0; i < key_str.size(); ++i) {
  4269. // 2 keys per CF
  4270. cfs[i] = handles_[i / 2];
  4271. keys[i] = Slice(key_str[i].data(), key_str[i].size());
  4272. }
  4273. ReadOptions ro;
  4274. ro.deadline = std::chrono::microseconds{env->NowMicros() + 10000};
  4275. ro.async_io = GetParam();
  4276. // Delay the first IO
  4277. fs->SetDelayTrigger(ro.deadline, ro.io_timeout, 0);
  4278. std::vector<Status> statuses(key_str.size());
  4279. dbfull()->MultiGet(ro, keys.size(), cfs.data(), keys.data(),
  4280. pin_values.data(), statuses.data());
  4281. // The first key is successful because we check after the lookup, but
  4282. // subsequent keys fail due to deadline exceeded
  4283. CheckStatus(statuses, 2);
  4284. // Similar to the previous one, but an IO delay in the third CF data block
  4285. // read
  4286. for (PinnableSlice& value : pin_values) {
  4287. value.Reset();
  4288. }
  4289. cache->SetCapacity(0);
  4290. cache->SetCapacity(1048576);
  4291. statuses.clear();
  4292. statuses.resize(keys.size());
  4293. ro.deadline = std::chrono::microseconds{env->NowMicros() + 10000};
  4294. fs->SetDelayTrigger(ro.deadline, ro.io_timeout, 2);
  4295. dbfull()->MultiGet(ro, keys.size(), cfs.data(), keys.data(),
  4296. pin_values.data(), statuses.data());
  4297. CheckStatus(statuses, 6);
  4298. // Similar to the previous one, but an IO delay in the last but one CF
  4299. for (PinnableSlice& value : pin_values) {
  4300. value.Reset();
  4301. }
  4302. cache->SetCapacity(0);
  4303. cache->SetCapacity(1048576);
  4304. statuses.clear();
  4305. statuses.resize(keys.size());
  4306. ro.deadline = std::chrono::microseconds{env->NowMicros() + 10000};
  4307. fs->SetDelayTrigger(ro.deadline, ro.io_timeout, 3);
  4308. dbfull()->MultiGet(ro, keys.size(), cfs.data(), keys.data(),
  4309. pin_values.data(), statuses.data());
  4310. CheckStatus(statuses, 8);
  4311. // Test batched MultiGet with single CF and lots of keys. Inject delay
  4312. // into the second batch of keys. As each batch is 32, the first 64 keys,
  4313. // i.e first two batches, should succeed and the rest should time out
  4314. for (PinnableSlice& value : pin_values) {
  4315. value.Reset();
  4316. }
  4317. cache->SetCapacity(0);
  4318. cache->SetCapacity(1048576);
  4319. key_str.clear();
  4320. for (i = 0; i < 100; ++i) {
  4321. key_str.emplace_back(Key(static_cast<int>(i)));
  4322. }
  4323. keys.resize(key_str.size());
  4324. pin_values.clear();
  4325. pin_values.resize(key_str.size());
  4326. for (i = 0; i < key_str.size(); ++i) {
  4327. keys[i] = Slice(key_str[i].data(), key_str[i].size());
  4328. }
  4329. statuses.clear();
  4330. statuses.resize(keys.size());
  4331. ro.deadline = std::chrono::microseconds{env->NowMicros() + 10000};
  4332. fs->SetDelayTrigger(ro.deadline, ro.io_timeout, 1);
  4333. dbfull()->MultiGet(ro, handles_[0], keys.size(), keys.data(),
  4334. pin_values.data(), statuses.data());
  4335. CheckStatus(statuses, 64);
  4336. Close();
  4337. }
  4338. INSTANTIATE_TEST_CASE_P(DeadlineIO, DBBasicTestMultiGetDeadline,
  4339. ::testing::Bool());
  4340. TEST_F(DBBasicTest, ManifestWriteFailure) {
  4341. Options options = GetDefaultOptions();
  4342. options.create_if_missing = true;
  4343. options.disable_auto_compactions = true;
  4344. options.env = env_;
  4345. options.enable_blob_files = true;
  4346. options.blob_file_size = 0;
  4347. DestroyAndReopen(options);
  4348. ASSERT_OK(Put("foo", "bar"));
  4349. ASSERT_OK(Flush());
  4350. SyncPoint::GetInstance()->DisableProcessing();
  4351. SyncPoint::GetInstance()->ClearAllCallBacks();
  4352. SyncPoint::GetInstance()->SetCallBack(
  4353. "VersionSet::ProcessManifestWrites:AfterSyncManifest", [&](void* arg) {
  4354. ASSERT_NE(nullptr, arg);
  4355. auto* s = static_cast<Status*>(arg);
  4356. ASSERT_OK(*s);
  4357. // Manually overwrite return status
  4358. *s = Status::IOError();
  4359. });
  4360. SyncPoint::GetInstance()->EnableProcessing();
  4361. ASSERT_OK(Put("key", "value"));
  4362. ASSERT_NOK(Flush());
  4363. SyncPoint::GetInstance()->DisableProcessing();
  4364. SyncPoint::GetInstance()->ClearAllCallBacks();
  4365. SyncPoint::GetInstance()->EnableProcessing();
  4366. Reopen(options);
  4367. // The IO error was a mocked one from the `AfterSyncManifest` callback. The
  4368. // Flush's VersionEdit actually made it into the Manifest. So these keys can
  4369. // be read back. Read them to check all live sst files and blob files.
  4370. ASSERT_EQ("bar", Get("foo"));
  4371. ASSERT_EQ("value", Get("key"));
  4372. }
  4373. TEST_F(DBBasicTest, DestroyDefaultCfHandle) {
  4374. Options options = GetDefaultOptions();
  4375. options.create_if_missing = true;
  4376. DestroyAndReopen(options);
  4377. CreateAndReopenWithCF({"pikachu"}, options);
  4378. for (const auto* h : handles_) {
  4379. ASSERT_NE(db_->DefaultColumnFamily(), h);
  4380. }
  4381. // We have two handles to the default column family. The two handles point to
  4382. // different ColumnFamilyHandle objects.
  4383. assert(db_->DefaultColumnFamily());
  4384. ASSERT_EQ(0U, db_->DefaultColumnFamily()->GetID());
  4385. assert(handles_[0]);
  4386. ASSERT_EQ(0U, handles_[0]->GetID());
  4387. // You can destroy handles_[...].
  4388. for (auto* h : handles_) {
  4389. ASSERT_OK(db_->DestroyColumnFamilyHandle(h));
  4390. }
  4391. handles_.clear();
  4392. // But you should not destroy db_->DefaultColumnFamily(), since it's going to
  4393. // be deleted in `DBImpl::CloseHelper()`. Before that, it may be used
  4394. // elsewhere internally too.
  4395. ColumnFamilyHandle* default_cf = db_->DefaultColumnFamily();
  4396. ASSERT_TRUE(db_->DestroyColumnFamilyHandle(default_cf).IsInvalidArgument());
  4397. }
  4398. TEST_F(DBBasicTest, FailOpenIfLoggerCreationFail) {
  4399. Options options = GetDefaultOptions();
  4400. options.create_if_missing = true;
  4401. SyncPoint::GetInstance()->DisableProcessing();
  4402. SyncPoint::GetInstance()->ClearAllCallBacks();
  4403. SyncPoint::GetInstance()->SetCallBack(
  4404. "rocksdb::CreateLoggerFromOptions:AfterGetPath", [&](void* arg) {
  4405. auto* s = static_cast<Status*>(arg);
  4406. assert(s);
  4407. *s = Status::IOError("Injected");
  4408. });
  4409. SyncPoint::GetInstance()->EnableProcessing();
  4410. Status s = TryReopen(options);
  4411. ASSERT_EQ(nullptr, options.info_log);
  4412. ASSERT_TRUE(s.IsIOError());
  4413. SyncPoint::GetInstance()->DisableProcessing();
  4414. SyncPoint::GetInstance()->ClearAllCallBacks();
  4415. }
  4416. TEST_F(DBBasicTest, VerifyFileChecksums) {
  4417. Options options = GetDefaultOptions();
  4418. options.create_if_missing = true;
  4419. options.env = env_;
  4420. DestroyAndReopen(options);
  4421. ASSERT_OK(Put("a", "value"));
  4422. ASSERT_OK(Flush());
  4423. ASSERT_TRUE(db_->VerifyFileChecksums(ReadOptions()).IsInvalidArgument());
  4424. options.file_checksum_gen_factory = GetFileChecksumGenCrc32cFactory();
  4425. Reopen(options);
  4426. ASSERT_OK(db_->VerifyFileChecksums(ReadOptions()));
  4427. // Write an L0 with checksum computed.
  4428. ASSERT_OK(Put("b", "value"));
  4429. ASSERT_OK(Flush());
  4430. ASSERT_OK(db_->VerifyFileChecksums(ReadOptions()));
  4431. // Does the right thing but with the wrong name -- using it should lead to an
  4432. // error.
  4433. class MisnamedFileChecksumGenerator : public FileChecksumGenCrc32c {
  4434. public:
  4435. MisnamedFileChecksumGenerator(const FileChecksumGenContext& context)
  4436. : FileChecksumGenCrc32c(context) {}
  4437. const char* Name() const override { return "sha1"; }
  4438. };
  4439. class MisnamedFileChecksumGenFactory : public FileChecksumGenCrc32cFactory {
  4440. public:
  4441. std::unique_ptr<FileChecksumGenerator> CreateFileChecksumGenerator(
  4442. const FileChecksumGenContext& context) override {
  4443. return std::unique_ptr<FileChecksumGenerator>(
  4444. new MisnamedFileChecksumGenerator(context));
  4445. }
  4446. };
  4447. options.file_checksum_gen_factory.reset(new MisnamedFileChecksumGenFactory());
  4448. Reopen(options);
  4449. ASSERT_TRUE(db_->VerifyFileChecksums(ReadOptions()).IsInvalidArgument());
  4450. }
  4451. TEST_F(DBBasicTest, VerifyFileChecksumsReadahead) {
  4452. Options options = GetDefaultOptions();
  4453. options.create_if_missing = true;
  4454. options.env = env_;
  4455. options.file_checksum_gen_factory = GetFileChecksumGenCrc32cFactory();
  4456. DestroyAndReopen(options);
  4457. Random rnd(301);
  4458. int alignment = 256 * 1024;
  4459. for (int i = 0; i < 16; ++i) {
  4460. ASSERT_OK(Put("key" + std::to_string(i), rnd.RandomString(alignment)));
  4461. }
  4462. ASSERT_OK(Flush());
  4463. std::vector<std::string> filenames;
  4464. int sst_cnt = 0;
  4465. std::string sst_name;
  4466. uint64_t sst_size;
  4467. uint64_t number;
  4468. FileType type;
  4469. ASSERT_OK(env_->GetChildren(dbname_, &filenames));
  4470. for (const auto& name : filenames) {
  4471. if (ParseFileName(name, &number, &type)) {
  4472. if (type == kTableFile) {
  4473. sst_cnt++;
  4474. sst_name = name;
  4475. }
  4476. }
  4477. }
  4478. ASSERT_EQ(sst_cnt, 1);
  4479. ASSERT_OK(env_->GetFileSize(dbname_ + '/' + sst_name, &sst_size));
  4480. bool last_read = false;
  4481. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  4482. "GenerateOneFileChecksum::Chunk:0", [&](void* /*arg*/) {
  4483. if (env_->random_read_bytes_counter_.load() == sst_size) {
  4484. EXPECT_FALSE(last_read);
  4485. last_read = true;
  4486. } else {
  4487. ASSERT_EQ(env_->random_read_bytes_counter_.load() & (alignment - 1),
  4488. 0);
  4489. }
  4490. });
  4491. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  4492. env_->count_random_reads_ = true;
  4493. env_->random_read_bytes_counter_ = 0;
  4494. env_->random_read_counter_.Reset();
  4495. ReadOptions ro;
  4496. ro.readahead_size = alignment;
  4497. ASSERT_OK(db_->VerifyFileChecksums(ro));
  4498. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  4499. ASSERT_TRUE(last_read);
  4500. ASSERT_EQ(env_->random_read_counter_.Read(),
  4501. (sst_size + alignment - 1) / (alignment));
  4502. }
  4503. TEST_F(DBBasicTest, DisallowMemtableWrite) {
  4504. // This test is mostly about what you can't do with memtable writes
  4505. // disallowed. For what you can do, see
  4506. // ExternalSSTFileBasicTest.FailIfNotBottommostLevelAndDisallowMemtable
  4507. Options options_allow = GetDefaultOptions();
  4508. options_allow.create_if_missing = true;
  4509. Options options_disallow = options_allow;
  4510. options_disallow.disallow_memtable_writes = true;
  4511. options_disallow.paranoid_memory_checks = true;
  4512. options_disallow.memtable_veirfy_per_key_checksum_on_seek = true;
  4513. DestroyAndReopen(options_allow);
  4514. // CFs allowing and disallowing memtable write
  4515. CreateColumnFamilies({"cf1", "cf2"}, options_allow);
  4516. CreateColumnFamilies({"cf3"}, options_disallow);
  4517. // XXX: needed to get consistent handles_ mappings
  4518. ReopenWithColumnFamilies(
  4519. {"default", "cf1", "cf2", "cf3"},
  4520. {options_allow, options_allow, options_allow, options_disallow});
  4521. EXPECT_EQ(Put(0, "a0", "1").code(), Status::Code::kOk);
  4522. EXPECT_EQ(Put(1, "a1", "1").code(), Status::Code::kOk);
  4523. EXPECT_EQ(Put(2, "a2", "1").code(), Status::Code::kOk);
  4524. EXPECT_EQ(Put(3, "a3", "1").code(), Status::Code::kInvalidArgument);
  4525. EXPECT_EQ(Get(0, "a0"), "1");
  4526. EXPECT_EQ(Get(1, "a1"), "1");
  4527. EXPECT_EQ(Get(2, "a2"), "1");
  4528. EXPECT_EQ(Get(3, "a3"), "NOT_FOUND");
  4529. EXPECT_EQ(Delete(0, "z0").code(), Status::Code::kOk);
  4530. EXPECT_EQ(Delete(1, "z1").code(), Status::Code::kOk);
  4531. EXPECT_EQ(Delete(2, "z2").code(), Status::Code::kOk);
  4532. EXPECT_EQ(Delete(3, "z3").code(), Status::Code::kInvalidArgument);
  4533. WriteBatch wb;
  4534. EXPECT_EQ(wb.Put(handles_[0], "b0", "2").code(), Status::Code::kOk);
  4535. EXPECT_EQ(wb.Put(handles_[1], "b1", "2").code(), Status::Code::kOk);
  4536. EXPECT_EQ(wb.Put(handles_[2], "b2", "2").code(), Status::Code::kOk);
  4537. EXPECT_EQ(wb.Put(handles_[3], "b3", "2").code(),
  4538. Status::Code::kInvalidArgument);
  4539. ASSERT_OK(db_->Write({}, &wb));
  4540. wb.Clear();
  4541. EXPECT_EQ(Get(0, "b0"), "2");
  4542. EXPECT_EQ(Get(1, "b1"), "2");
  4543. EXPECT_EQ(Get(2, "b2"), "2");
  4544. EXPECT_EQ(Get(3, "b3"), "NOT_FOUND");
  4545. std::unique_ptr<Iterator> iter(
  4546. dbfull()->NewIterator(ReadOptions(), handles_[3]));
  4547. iter->Seek("a3");
  4548. ASSERT_OK(iter->status());
  4549. iter.reset();
  4550. // When the DB is re-opened with WAL entries for a CF that is newly setting
  4551. // disallow_memtable_writes, we detect that and fail the open gracefully.
  4552. ASSERT_EQ(TryReopenWithColumnFamilies(
  4553. {"default", "cf1", "cf2", "cf3"},
  4554. {options_allow, options_allow, options_disallow, options_allow})
  4555. .code(),
  4556. Status::Code::kInvalidArgument);
  4557. // Successfully opening with allow creates L0 files from the WAL
  4558. ReopenWithColumnFamilies({"default", "cf1", "cf2", "cf3"}, options_allow);
  4559. EXPECT_EQ(Get(0, "a0"), "1");
  4560. EXPECT_EQ(Get(1, "a1"), "1");
  4561. EXPECT_EQ(Get(2, "a2"), "1");
  4562. EXPECT_EQ(Get(3, "a3"), "NOT_FOUND");
  4563. // Now able to disallow on CF2 because no relevant WAL entries
  4564. ReopenWithColumnFamilies(
  4565. {"default", "cf1", "cf2", "cf3"},
  4566. {options_allow, options_allow, options_disallow, options_allow});
  4567. EXPECT_EQ(Get(0, "a0"), "1");
  4568. EXPECT_EQ(Get(1, "a1"), "1");
  4569. EXPECT_EQ(Get(2, "a2"), "1");
  4570. EXPECT_EQ(Get(3, "a3"), "NOT_FOUND");
  4571. // Now able to write to CF 3 but not CF 2
  4572. EXPECT_EQ(Put(0, "c0", "3").code(), Status::Code::kOk);
  4573. EXPECT_EQ(Put(1, "c1", "3").code(), Status::Code::kOk);
  4574. EXPECT_EQ(Put(2, "c2", "3").code(), Status::Code::kInvalidArgument);
  4575. EXPECT_EQ(Put(3, "c3", "3").code(), Status::Code::kOk);
  4576. EXPECT_EQ(Get(0, "c0"), "3");
  4577. EXPECT_EQ(Get(1, "c1"), "3");
  4578. EXPECT_EQ(Get(2, "c2"), "NOT_FOUND");
  4579. EXPECT_EQ(Get(3, "c3"), "3");
  4580. // disallow_memtable_writes not supported on default column family.
  4581. // (Would be complicated to make a WriteBatch aware of the setting in order
  4582. // to reject the write before entering the write path.)
  4583. Destroy(options_allow);
  4584. EXPECT_EQ(TryReopen(options_disallow).code(), Status::Code::kInvalidArgument);
  4585. }
  4586. // TODO: re-enable after we provide finer-grained control for WAL tracking to
  4587. // meet the needs of different use cases, durability levels and recovery modes.
  4588. TEST_F(DBBasicTest, DISABLED_ManualWalSync) {
  4589. Options options = CurrentOptions();
  4590. options.track_and_verify_wals_in_manifest = true;
  4591. options.wal_recovery_mode = WALRecoveryMode::kAbsoluteConsistency;
  4592. DestroyAndReopen(options);
  4593. ASSERT_OK(Put("x", "y"));
  4594. // This does not create a new WAL.
  4595. ASSERT_OK(db_->SyncWAL());
  4596. EXPECT_FALSE(dbfull()->GetVersionSet()->GetWalSet().GetWals().empty());
  4597. std::unique_ptr<LogFile> wal;
  4598. Status s = db_->GetCurrentWalFile(&wal);
  4599. ASSERT_OK(s);
  4600. Close();
  4601. EXPECT_OK(env_->DeleteFile(LogFileName(dbname_, wal->LogNumber())));
  4602. ASSERT_TRUE(TryReopen(options).IsCorruption());
  4603. }
  4604. // A test class for intercepting random reads and injecting artificial
  4605. // delays. Used for testing the deadline/timeout feature
  4606. class DBBasicTestDeadline
  4607. : public DBBasicTest,
  4608. public testing::WithParamInterface<std::tuple<bool, bool>> {};
  4609. TEST_P(DBBasicTestDeadline, PointLookupDeadline) {
  4610. std::shared_ptr<DeadlineFS> fs = std::make_shared<DeadlineFS>(env_, true);
  4611. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  4612. bool set_deadline = std::get<0>(GetParam());
  4613. bool set_timeout = std::get<1>(GetParam());
  4614. for (int option_config = kDefault; option_config < kEnd; ++option_config) {
  4615. if (ShouldSkipOptions(option_config, kSkipPlainTable | kSkipMmapReads)) {
  4616. continue;
  4617. }
  4618. option_config_ = option_config;
  4619. Options options = CurrentOptions();
  4620. if (options.use_direct_reads) {
  4621. continue;
  4622. }
  4623. options.env = env.get();
  4624. options.disable_auto_compactions = true;
  4625. Cache* block_cache = nullptr;
  4626. // Fileter block reads currently don't cause the request to get
  4627. // aborted on a read timeout, so its possible those block reads
  4628. // may get issued even if the deadline is past
  4629. SyncPoint::GetInstance()->SetCallBack(
  4630. "BlockBasedTable::Get:BeforeFilterMatch",
  4631. [&](void* /*arg*/) { fs->IgnoreDeadline(true); });
  4632. SyncPoint::GetInstance()->SetCallBack(
  4633. "BlockBasedTable::Get:AfterFilterMatch",
  4634. [&](void* /*arg*/) { fs->IgnoreDeadline(false); });
  4635. // DB open will create table readers unless we reduce the table cache
  4636. // capacity.
  4637. // SanitizeOptions will set max_open_files to minimum of 20. Table cache
  4638. // is allocated with max_open_files - 10 as capacity. So override
  4639. // max_open_files to 11 so table cache capacity will become 1. This will
  4640. // prevent file open during DB open and force the file to be opened
  4641. // during MultiGet
  4642. SyncPoint::GetInstance()->SetCallBack(
  4643. "SanitizeOptions::AfterChangeMaxOpenFiles", [&](void* arg) {
  4644. int* max_open_files = (int*)arg;
  4645. *max_open_files = 11;
  4646. });
  4647. SyncPoint::GetInstance()->EnableProcessing();
  4648. SetTimeElapseOnlySleepOnReopen(&options);
  4649. Reopen(options);
  4650. if (options.table_factory) {
  4651. block_cache = options.table_factory->GetOptions<Cache>(
  4652. TableFactory::kBlockCacheOpts());
  4653. }
  4654. Random rnd(301);
  4655. for (int i = 0; i < 400; ++i) {
  4656. std::string key = "k" + std::to_string(i);
  4657. ASSERT_OK(Put(key, rnd.RandomString(100)));
  4658. }
  4659. ASSERT_OK(Flush());
  4660. bool timedout = true;
  4661. // A timeout will be forced when the IO counter reaches this value
  4662. int io_deadline_trigger = 0;
  4663. // Keep incrementing io_deadline_trigger and call Get() until there is an
  4664. // iteration that doesn't cause a timeout. This ensures that we cover
  4665. // all file reads in the point lookup path that can potentially timeout
  4666. // and cause the Get() to fail.
  4667. while (timedout) {
  4668. ReadOptions ro;
  4669. if (set_deadline) {
  4670. ro.deadline = std::chrono::microseconds{env->NowMicros() + 10000};
  4671. }
  4672. if (set_timeout) {
  4673. ro.io_timeout = std::chrono::microseconds{5000};
  4674. }
  4675. fs->SetDelayTrigger(ro.deadline, ro.io_timeout, io_deadline_trigger);
  4676. block_cache->SetCapacity(0);
  4677. block_cache->SetCapacity(1048576);
  4678. std::string value;
  4679. Status s = dbfull()->Get(ro, "k50", &value);
  4680. if (fs->TimedOut()) {
  4681. ASSERT_EQ(s, Status::TimedOut());
  4682. } else {
  4683. timedout = false;
  4684. ASSERT_OK(s);
  4685. }
  4686. io_deadline_trigger++;
  4687. }
  4688. // Reset the delay sequence in order to avoid false alarms during Reopen
  4689. fs->SetDelayTrigger(std::chrono::microseconds::zero(),
  4690. std::chrono::microseconds::zero(), 0);
  4691. }
  4692. Close();
  4693. }
  4694. TEST_P(DBBasicTestDeadline, IteratorDeadline) {
  4695. std::shared_ptr<DeadlineFS> fs = std::make_shared<DeadlineFS>(env_, true);
  4696. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  4697. bool set_deadline = std::get<0>(GetParam());
  4698. bool set_timeout = std::get<1>(GetParam());
  4699. for (int option_config = kDefault; option_config < kEnd; ++option_config) {
  4700. if (ShouldSkipOptions(option_config, kSkipPlainTable | kSkipMmapReads)) {
  4701. continue;
  4702. }
  4703. Options options = CurrentOptions();
  4704. if (options.use_direct_reads) {
  4705. continue;
  4706. }
  4707. options.env = env.get();
  4708. options.disable_auto_compactions = true;
  4709. Cache* block_cache = nullptr;
  4710. // DB open will create table readers unless we reduce the table cache
  4711. // capacity.
  4712. // SanitizeOptions will set max_open_files to minimum of 20. Table cache
  4713. // is allocated with max_open_files - 10 as capacity. So override
  4714. // max_open_files to 11 so table cache capacity will become 1. This will
  4715. // prevent file open during DB open and force the file to be opened
  4716. // during MultiGet
  4717. SyncPoint::GetInstance()->SetCallBack(
  4718. "SanitizeOptions::AfterChangeMaxOpenFiles", [&](void* arg) {
  4719. int* max_open_files = (int*)arg;
  4720. *max_open_files = 11;
  4721. });
  4722. SyncPoint::GetInstance()->EnableProcessing();
  4723. SetTimeElapseOnlySleepOnReopen(&options);
  4724. Reopen(options);
  4725. if (options.table_factory) {
  4726. block_cache = options.table_factory->GetOptions<Cache>(
  4727. TableFactory::kBlockCacheOpts());
  4728. }
  4729. Random rnd(301);
  4730. for (int i = 0; i < 400; ++i) {
  4731. std::string key = "k" + std::to_string(i);
  4732. ASSERT_OK(Put(key, rnd.RandomString(100)));
  4733. }
  4734. ASSERT_OK(Flush());
  4735. bool timedout = true;
  4736. // A timeout will be forced when the IO counter reaches this value
  4737. int io_deadline_trigger = 0;
  4738. // Keep incrementing io_deadline_trigger and call Get() until there is an
  4739. // iteration that doesn't cause a timeout. This ensures that we cover
  4740. // all file reads in the point lookup path that can potentially timeout
  4741. while (timedout) {
  4742. ReadOptions ro;
  4743. if (set_deadline) {
  4744. ro.deadline = std::chrono::microseconds{env->NowMicros() + 10000};
  4745. }
  4746. if (set_timeout) {
  4747. ro.io_timeout = std::chrono::microseconds{5000};
  4748. }
  4749. fs->SetDelayTrigger(ro.deadline, ro.io_timeout, io_deadline_trigger);
  4750. block_cache->SetCapacity(0);
  4751. block_cache->SetCapacity(1048576);
  4752. Iterator* iter = dbfull()->NewIterator(ro);
  4753. int count = 0;
  4754. iter->Seek("k50");
  4755. while (iter->Valid() && count++ < 100) {
  4756. iter->Next();
  4757. }
  4758. if (fs->TimedOut()) {
  4759. ASSERT_FALSE(iter->Valid());
  4760. ASSERT_EQ(iter->status(), Status::TimedOut());
  4761. } else {
  4762. timedout = false;
  4763. ASSERT_OK(iter->status());
  4764. }
  4765. delete iter;
  4766. io_deadline_trigger++;
  4767. }
  4768. // Reset the delay sequence in order to avoid false alarms during Reopen
  4769. fs->SetDelayTrigger(std::chrono::microseconds::zero(),
  4770. std::chrono::microseconds::zero(), 0);
  4771. }
  4772. Close();
  4773. }
  4774. // Param 0: If true, set read_options.deadline
  4775. // Param 1: If true, set read_options.io_timeout
  4776. INSTANTIATE_TEST_CASE_P(DBBasicTestDeadline, DBBasicTestDeadline,
  4777. ::testing::Values(std::make_tuple(true, false),
  4778. std::make_tuple(false, true),
  4779. std::make_tuple(true, true)));
  4780. } // namespace ROCKSDB_NAMESPACE
  4781. int main(int argc, char** argv) {
  4782. ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
  4783. ::testing::InitGoogleTest(&argc, argv);
  4784. RegisterCustomObjects(argc, argv);
  4785. return RUN_ALL_TESTS();
  4786. }