ldb_cmd.cc 188 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392
  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. #include "rocksdb/utilities/ldb_cmd.h"
  7. #include <cstddef>
  8. #include <cstdlib>
  9. #include <ctime>
  10. #include <fstream>
  11. #include <functional>
  12. #include <iostream>
  13. #include <limits>
  14. #include <sstream>
  15. #include <stdexcept>
  16. #include <string>
  17. #include "db/blob/blob_index.h"
  18. #include "db/db_impl/db_impl.h"
  19. #include "db/dbformat.h"
  20. #include "db/log_reader.h"
  21. #include "db/version_util.h"
  22. #include "db/wide/wide_column_serialization.h"
  23. #include "db/wide/wide_columns_helper.h"
  24. #include "db/write_batch_internal.h"
  25. #include "db_stress_tool/db_stress_compression_manager.h"
  26. #include "file/filename.h"
  27. #include "rocksdb/cache.h"
  28. #include "rocksdb/comparator.h"
  29. #include "rocksdb/experimental.h"
  30. #include "rocksdb/file_checksum.h"
  31. #include "rocksdb/filter_policy.h"
  32. #include "rocksdb/options.h"
  33. #include "rocksdb/table_properties.h"
  34. #include "rocksdb/utilities/backup_engine.h"
  35. #include "rocksdb/utilities/checkpoint.h"
  36. #include "rocksdb/utilities/debug.h"
  37. #include "rocksdb/utilities/options_util.h"
  38. #include "rocksdb/write_batch.h"
  39. #include "rocksdb/write_buffer_manager.h"
  40. #include "table/sst_file_dumper.h"
  41. #include "tools/ldb_cmd_impl.h"
  42. #include "util/cast_util.h"
  43. #include "util/coding.h"
  44. #include "util/file_checksum_helper.h"
  45. #include "util/simple_mixed_compressor.h"
  46. #include "util/stderr_logger.h"
  47. #include "util/string_util.h"
  48. #include "util/write_batch_util.h"
  49. #include "utilities/blob_db/blob_dump_tool.h"
  50. #include "utilities/merge_operators.h"
  51. #include "utilities/ttl/db_ttl_impl.h"
  52. namespace ROCKSDB_NAMESPACE {
  53. class FileChecksumGenCrc32c;
  54. class FileChecksumGenCrc32cFactory;
  55. const std::string LDBCommand::ARG_ENV_URI = "env_uri";
  56. const std::string LDBCommand::ARG_FS_URI = "fs_uri";
  57. const std::string LDBCommand::ARG_DB = "db";
  58. const std::string LDBCommand::ARG_PATH = "path";
  59. const std::string LDBCommand::ARG_SECONDARY_PATH = "secondary_path";
  60. const std::string LDBCommand::ARG_LEADER_PATH = "leader_path";
  61. const std::string LDBCommand::ARG_HEX = "hex";
  62. const std::string LDBCommand::ARG_KEY_HEX = "key_hex";
  63. const std::string LDBCommand::ARG_VALUE_HEX = "value_hex";
  64. const std::string LDBCommand::ARG_CF_NAME = "column_family";
  65. const std::string LDBCommand::ARG_TTL = "ttl";
  66. const std::string LDBCommand::ARG_TTL_START = "start_time";
  67. const std::string LDBCommand::ARG_TTL_END = "end_time";
  68. const std::string LDBCommand::ARG_TIMESTAMP = "timestamp";
  69. const std::string LDBCommand::ARG_TRY_LOAD_OPTIONS = "try_load_options";
  70. const std::string LDBCommand::ARG_DISABLE_CONSISTENCY_CHECKS =
  71. "disable_consistency_checks";
  72. const std::string LDBCommand::ARG_IGNORE_UNKNOWN_OPTIONS =
  73. "ignore_unknown_options";
  74. const std::string LDBCommand::ARG_FROM = "from";
  75. const std::string LDBCommand::ARG_TO = "to";
  76. const std::string LDBCommand::ARG_MAX_KEYS = "max_keys";
  77. const std::string LDBCommand::ARG_BLOOM_BITS = "bloom_bits";
  78. const std::string LDBCommand::ARG_FIX_PREFIX_LEN = "fix_prefix_len";
  79. const std::string LDBCommand::ARG_COMPRESSION_TYPE = "compression_type";
  80. const std::string LDBCommand::ARG_COMPRESSION_MAX_DICT_BYTES =
  81. "compression_max_dict_bytes";
  82. const std::string LDBCommand::ARG_BLOCK_SIZE = "block_size";
  83. const std::string LDBCommand::ARG_AUTO_COMPACTION = "auto_compaction";
  84. const std::string LDBCommand::ARG_DB_WRITE_BUFFER_SIZE = "db_write_buffer_size";
  85. const std::string LDBCommand::ARG_WRITE_BUFFER_SIZE = "write_buffer_size";
  86. const std::string LDBCommand::ARG_FILE_SIZE = "file_size";
  87. const std::string LDBCommand::ARG_CREATE_IF_MISSING = "create_if_missing";
  88. const std::string LDBCommand::ARG_NO_VALUE = "no_value";
  89. const std::string LDBCommand::ARG_ENABLE_BLOB_FILES = "enable_blob_files";
  90. const std::string LDBCommand::ARG_MIN_BLOB_SIZE = "min_blob_size";
  91. const std::string LDBCommand::ARG_BLOB_FILE_SIZE = "blob_file_size";
  92. const std::string LDBCommand::ARG_BLOB_COMPRESSION_TYPE =
  93. "blob_compression_type";
  94. const std::string LDBCommand::ARG_ENABLE_BLOB_GARBAGE_COLLECTION =
  95. "enable_blob_garbage_collection";
  96. const std::string LDBCommand::ARG_BLOB_GARBAGE_COLLECTION_AGE_CUTOFF =
  97. "blob_garbage_collection_age_cutoff";
  98. const std::string LDBCommand::ARG_BLOB_GARBAGE_COLLECTION_FORCE_THRESHOLD =
  99. "blob_garbage_collection_force_threshold";
  100. const std::string LDBCommand::ARG_BLOB_COMPACTION_READAHEAD_SIZE =
  101. "blob_compaction_readahead_size";
  102. const std::string LDBCommand::ARG_BLOB_FILE_STARTING_LEVEL =
  103. "blob_file_starting_level";
  104. const std::string LDBCommand::ARG_PREPOPULATE_BLOB_CACHE =
  105. "prepopulate_blob_cache";
  106. const std::string LDBCommand::ARG_DECODE_BLOB_INDEX = "decode_blob_index";
  107. const std::string LDBCommand::ARG_DUMP_UNCOMPRESSED_BLOBS =
  108. "dump_uncompressed_blobs";
  109. const std::string LDBCommand::ARG_READ_TIMESTAMP = "read_timestamp";
  110. const std::string LDBCommand::ARG_GET_WRITE_UNIX_TIME = "get_write_unix_time";
  111. const char* LDBCommand::DELIM = " ==> ";
  112. namespace {
  113. // Helper class to iterate WAL logs in a directory in chronological order.
  114. class WALFileIterator {
  115. public:
  116. explicit WALFileIterator(const std::string& parent_dir,
  117. const std::vector<std::string>& filenames);
  118. // REQUIRES Valid() == true
  119. std::string GetNextWAL();
  120. bool Valid() const { return wal_file_iter_ != log_files_.end(); }
  121. private:
  122. // WAL log file names(s)
  123. std::string parent_dir_;
  124. std::vector<std::string> log_files_;
  125. std::vector<std::string>::const_iterator wal_file_iter_;
  126. };
  127. WALFileIterator::WALFileIterator(const std::string& parent_dir,
  128. const std::vector<std::string>& filenames)
  129. : parent_dir_(parent_dir) {
  130. // populate wal logs
  131. assert(!filenames.empty());
  132. for (const auto& fname : filenames) {
  133. uint64_t file_num = 0;
  134. FileType file_type;
  135. bool parse_ok = ParseFileName(fname, &file_num, &file_type);
  136. if (parse_ok && file_type == kWalFile) {
  137. log_files_.push_back(fname);
  138. }
  139. }
  140. std::sort(log_files_.begin(), log_files_.end(),
  141. [](const std::string& lhs, const std::string& rhs) {
  142. uint64_t num1 = 0;
  143. uint64_t num2 = 0;
  144. FileType type1;
  145. FileType type2;
  146. bool parse_ok1 = ParseFileName(lhs, &num1, &type1);
  147. bool parse_ok2 = ParseFileName(rhs, &num2, &type2);
  148. #ifndef NDEBUG
  149. assert(parse_ok1);
  150. assert(parse_ok2);
  151. #else
  152. (void)parse_ok1;
  153. (void)parse_ok2;
  154. #endif
  155. return num1 < num2;
  156. });
  157. wal_file_iter_ = log_files_.begin();
  158. }
  159. std::string WALFileIterator::GetNextWAL() {
  160. assert(Valid());
  161. std::string ret;
  162. if (wal_file_iter_ != log_files_.end()) {
  163. ret.assign(parent_dir_);
  164. if (ret.back() != kFilePathSeparator) {
  165. ret.push_back(kFilePathSeparator);
  166. }
  167. ret.append(*wal_file_iter_);
  168. ++wal_file_iter_;
  169. }
  170. return ret;
  171. }
  172. void DumpWalFiles(Options options, const std::string& dir_or_file,
  173. bool print_header, bool print_values,
  174. bool only_print_seqno_gaps, bool is_write_committed,
  175. const std::map<uint32_t, const Comparator*>& ucmps,
  176. LDBCommandExecuteResult* exec_state);
  177. void DumpWalFile(Options options, const std::string& wal_file,
  178. bool print_header, bool print_values,
  179. bool only_print_seqno_gaps, bool is_write_committed,
  180. const std::map<uint32_t, const Comparator*>& ucmps,
  181. LDBCommandExecuteResult* exec_state,
  182. std::optional<SequenceNumber>* prev_batch_seqno,
  183. std::optional<uint32_t>* prev_batch_count);
  184. void DumpSstFile(Options options, std::string filename, bool output_hex,
  185. bool show_properties, bool decode_blob_index,
  186. std::string from_key = "", std::string to_key = "");
  187. void DumpBlobFile(const std::string& filename, bool is_key_hex,
  188. bool is_value_hex, bool dump_uncompressed_blobs);
  189. Status EncodeUserProvidedTimestamp(const std::string& user_timestamp,
  190. std::string* ts_buf);
  191. } // namespace
  192. LDBCommand* LDBCommand::InitFromCmdLineArgs(
  193. int argc, char const* const* argv, const Options& options,
  194. const LDBOptions& ldb_options,
  195. const std::vector<ColumnFamilyDescriptor>* column_families) {
  196. std::vector<std::string> args;
  197. for (int i = 1; i < argc; i++) {
  198. args.emplace_back(argv[i]);
  199. }
  200. return InitFromCmdLineArgs(args, options, ldb_options, column_families,
  201. SelectCommand);
  202. }
  203. void LDBCommand::ParseSingleParam(const std::string& param,
  204. ParsedParams& parsed_params,
  205. std::vector<std::string>& cmd_tokens) {
  206. const std::string OPTION_PREFIX = "--";
  207. if (param[0] == '-' && param[1] == '-') {
  208. std::vector<std::string> splits = StringSplit(param, '=');
  209. // --option_name=option_value
  210. if (splits.size() == 2) {
  211. std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
  212. parsed_params.option_map[optionKey] = splits[1];
  213. } else if (splits.size() == 1) {
  214. // --flag_name
  215. std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
  216. parsed_params.flags.push_back(optionKey);
  217. } else {
  218. // --option_name=option_value, option_value contains '='
  219. std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
  220. parsed_params.option_map[optionKey] =
  221. param.substr(splits[0].length() + 1);
  222. }
  223. } else {
  224. cmd_tokens.push_back(param);
  225. }
  226. }
  227. /**
  228. * Parse the command-line arguments and create the appropriate LDBCommand2
  229. * instance.
  230. * The command line arguments must be in the following format:
  231. * ./ldb --db=PATH_TO_DB [--commonOpt1=commonOpt1Val] ..
  232. * COMMAND <PARAM1> <PARAM2> ... [-cmdSpecificOpt1=cmdSpecificOpt1Val] ..
  233. * This is similar to the command line format used by HBaseClientTool.
  234. * Command name is not included in args.
  235. * Returns nullptr if the command-line cannot be parsed.
  236. */
  237. LDBCommand* LDBCommand::InitFromCmdLineArgs(
  238. const std::vector<std::string>& args, const Options& options,
  239. const LDBOptions& ldb_options,
  240. const std::vector<ColumnFamilyDescriptor>* column_families,
  241. const std::function<LDBCommand*(const ParsedParams&)>& selector) {
  242. // --x=y command line arguments are added as x->y map entries in
  243. // parsed_params.option_map.
  244. //
  245. // Command-line arguments of the form --hex end up in this array as hex to
  246. // parsed_params.flags
  247. ParsedParams parsed_params;
  248. // Everything other than option_map and flags. Represents commands
  249. // and their parameters. For eg: put key1 value1 go into this vector.
  250. std::vector<std::string> cmdTokens;
  251. for (const auto& arg : args) {
  252. ParseSingleParam(arg, parsed_params, cmdTokens);
  253. }
  254. if (cmdTokens.size() < 1) {
  255. fprintf(stderr, "Command not specified!");
  256. return nullptr;
  257. }
  258. parsed_params.cmd = cmdTokens[0];
  259. parsed_params.cmd_params.assign(cmdTokens.begin() + 1, cmdTokens.end());
  260. LDBCommand* command = selector(parsed_params);
  261. if (command) {
  262. command->SetDBOptions(options);
  263. command->SetLDBOptions(ldb_options);
  264. command->SetColumnFamilies(column_families);
  265. }
  266. return command;
  267. }
  268. LDBCommand* LDBCommand::SelectCommand(const ParsedParams& parsed_params) {
  269. if (parsed_params.cmd == GetCommand::Name()) {
  270. return new GetCommand(parsed_params.cmd_params, parsed_params.option_map,
  271. parsed_params.flags);
  272. } else if (parsed_params.cmd == MultiGetCommand::Name()) {
  273. return new MultiGetCommand(parsed_params.cmd_params,
  274. parsed_params.option_map, parsed_params.flags);
  275. } else if (parsed_params.cmd == GetEntityCommand::Name()) {
  276. return new GetEntityCommand(parsed_params.cmd_params,
  277. parsed_params.option_map, parsed_params.flags);
  278. } else if (parsed_params.cmd == MultiGetEntityCommand::Name()) {
  279. return new MultiGetEntityCommand(parsed_params.cmd_params,
  280. parsed_params.option_map,
  281. parsed_params.flags);
  282. } else if (parsed_params.cmd == PutCommand::Name()) {
  283. return new PutCommand(parsed_params.cmd_params, parsed_params.option_map,
  284. parsed_params.flags);
  285. } else if (parsed_params.cmd == PutEntityCommand::Name()) {
  286. return new PutEntityCommand(parsed_params.cmd_params,
  287. parsed_params.option_map, parsed_params.flags);
  288. } else if (parsed_params.cmd == BatchPutCommand::Name()) {
  289. return new BatchPutCommand(parsed_params.cmd_params,
  290. parsed_params.option_map, parsed_params.flags);
  291. } else if (parsed_params.cmd == ScanCommand::Name()) {
  292. return new ScanCommand(parsed_params.cmd_params, parsed_params.option_map,
  293. parsed_params.flags);
  294. } else if (parsed_params.cmd == DeleteCommand::Name()) {
  295. return new DeleteCommand(parsed_params.cmd_params, parsed_params.option_map,
  296. parsed_params.flags);
  297. } else if (parsed_params.cmd == SingleDeleteCommand::Name()) {
  298. return new SingleDeleteCommand(parsed_params.cmd_params,
  299. parsed_params.option_map,
  300. parsed_params.flags);
  301. } else if (parsed_params.cmd == DeleteRangeCommand::Name()) {
  302. return new DeleteRangeCommand(parsed_params.cmd_params,
  303. parsed_params.option_map,
  304. parsed_params.flags);
  305. } else if (parsed_params.cmd == ApproxSizeCommand::Name()) {
  306. return new ApproxSizeCommand(parsed_params.cmd_params,
  307. parsed_params.option_map, parsed_params.flags);
  308. } else if (parsed_params.cmd == DBQuerierCommand::Name()) {
  309. return new DBQuerierCommand(parsed_params.cmd_params,
  310. parsed_params.option_map, parsed_params.flags);
  311. } else if (parsed_params.cmd == CompactorCommand::Name()) {
  312. return new CompactorCommand(parsed_params.cmd_params,
  313. parsed_params.option_map, parsed_params.flags);
  314. } else if (parsed_params.cmd == WALDumperCommand::Name()) {
  315. return new WALDumperCommand(parsed_params.cmd_params,
  316. parsed_params.option_map, parsed_params.flags);
  317. } else if (parsed_params.cmd == ReduceDBLevelsCommand::Name()) {
  318. return new ReduceDBLevelsCommand(parsed_params.cmd_params,
  319. parsed_params.option_map,
  320. parsed_params.flags);
  321. } else if (parsed_params.cmd == ChangeCompactionStyleCommand::Name()) {
  322. return new ChangeCompactionStyleCommand(parsed_params.cmd_params,
  323. parsed_params.option_map,
  324. parsed_params.flags);
  325. } else if (parsed_params.cmd == DBDumperCommand::Name()) {
  326. return new DBDumperCommand(parsed_params.cmd_params,
  327. parsed_params.option_map, parsed_params.flags);
  328. } else if (parsed_params.cmd == DBLoaderCommand::Name()) {
  329. return new DBLoaderCommand(parsed_params.cmd_params,
  330. parsed_params.option_map, parsed_params.flags);
  331. } else if (parsed_params.cmd == ManifestDumpCommand::Name()) {
  332. return new ManifestDumpCommand(parsed_params.cmd_params,
  333. parsed_params.option_map,
  334. parsed_params.flags);
  335. } else if (parsed_params.cmd == FileChecksumDumpCommand::Name()) {
  336. return new FileChecksumDumpCommand(parsed_params.cmd_params,
  337. parsed_params.option_map,
  338. parsed_params.flags);
  339. } else if (parsed_params.cmd == GetPropertyCommand::Name()) {
  340. return new GetPropertyCommand(parsed_params.cmd_params,
  341. parsed_params.option_map,
  342. parsed_params.flags);
  343. } else if (parsed_params.cmd == ListColumnFamiliesCommand::Name()) {
  344. return new ListColumnFamiliesCommand(parsed_params.cmd_params,
  345. parsed_params.option_map,
  346. parsed_params.flags);
  347. } else if (parsed_params.cmd == CreateColumnFamilyCommand::Name()) {
  348. return new CreateColumnFamilyCommand(parsed_params.cmd_params,
  349. parsed_params.option_map,
  350. parsed_params.flags);
  351. } else if (parsed_params.cmd == DropColumnFamilyCommand::Name()) {
  352. return new DropColumnFamilyCommand(parsed_params.cmd_params,
  353. parsed_params.option_map,
  354. parsed_params.flags);
  355. } else if (parsed_params.cmd == DBFileDumperCommand::Name()) {
  356. return new DBFileDumperCommand(parsed_params.cmd_params,
  357. parsed_params.option_map,
  358. parsed_params.flags);
  359. } else if (parsed_params.cmd == DBLiveFilesMetadataDumperCommand::Name()) {
  360. return new DBLiveFilesMetadataDumperCommand(parsed_params.cmd_params,
  361. parsed_params.option_map,
  362. parsed_params.flags);
  363. } else if (parsed_params.cmd == InternalDumpCommand::Name()) {
  364. return new InternalDumpCommand(parsed_params.cmd_params,
  365. parsed_params.option_map,
  366. parsed_params.flags);
  367. } else if (parsed_params.cmd == CheckConsistencyCommand::Name()) {
  368. return new CheckConsistencyCommand(parsed_params.cmd_params,
  369. parsed_params.option_map,
  370. parsed_params.flags);
  371. } else if (parsed_params.cmd == CheckPointCommand::Name()) {
  372. return new CheckPointCommand(parsed_params.cmd_params,
  373. parsed_params.option_map, parsed_params.flags);
  374. } else if (parsed_params.cmd == RepairCommand::Name()) {
  375. return new RepairCommand(parsed_params.cmd_params, parsed_params.option_map,
  376. parsed_params.flags);
  377. } else if (parsed_params.cmd == BackupCommand::Name()) {
  378. return new BackupCommand(parsed_params.cmd_params, parsed_params.option_map,
  379. parsed_params.flags);
  380. } else if (parsed_params.cmd == RestoreCommand::Name()) {
  381. return new RestoreCommand(parsed_params.cmd_params,
  382. parsed_params.option_map, parsed_params.flags);
  383. } else if (parsed_params.cmd == WriteExternalSstFilesCommand::Name()) {
  384. return new WriteExternalSstFilesCommand(parsed_params.cmd_params,
  385. parsed_params.option_map,
  386. parsed_params.flags);
  387. } else if (parsed_params.cmd == IngestExternalSstFilesCommand::Name()) {
  388. return new IngestExternalSstFilesCommand(parsed_params.cmd_params,
  389. parsed_params.option_map,
  390. parsed_params.flags);
  391. } else if (parsed_params.cmd == ListFileRangeDeletesCommand::Name()) {
  392. return new ListFileRangeDeletesCommand(parsed_params.option_map,
  393. parsed_params.flags);
  394. } else if (parsed_params.cmd == UnsafeRemoveSstFileCommand::Name()) {
  395. return new UnsafeRemoveSstFileCommand(parsed_params.cmd_params,
  396. parsed_params.option_map,
  397. parsed_params.flags);
  398. } else if (parsed_params.cmd == UpdateManifestCommand::Name()) {
  399. return new UpdateManifestCommand(parsed_params.cmd_params,
  400. parsed_params.option_map,
  401. parsed_params.flags);
  402. } else if (parsed_params.cmd == CompactionProgressDumpCommand::Name()) {
  403. return new CompactionProgressDumpCommand(parsed_params.cmd_params,
  404. parsed_params.option_map,
  405. parsed_params.flags);
  406. }
  407. return nullptr;
  408. }
  409. /* Run the command, and return the execute result. */
  410. void LDBCommand::Run() {
  411. if (!exec_state_.IsNotStarted()) {
  412. return;
  413. }
  414. if (!options_.env || options_.env == Env::Default()) {
  415. Env* env = Env::Default();
  416. Status s = Env::CreateFromUri(config_options_, env_uri_, fs_uri_, &env,
  417. &env_guard_);
  418. if (!s.ok()) {
  419. fprintf(stderr, "%s\n", s.ToString().c_str());
  420. exec_state_ = LDBCommandExecuteResult::Failed(s.ToString());
  421. return;
  422. }
  423. options_.env = env;
  424. }
  425. if (db_ == nullptr && !NoDBOpen()) {
  426. OpenDB();
  427. if (exec_state_.IsFailed() && try_load_options_) {
  428. // We don't always return if there is a failure because a WAL file or
  429. // manifest file can be given to "dump" command so we should continue.
  430. // --try_load_options is not valid in those cases.
  431. return;
  432. }
  433. }
  434. // We'll intentionally proceed even if the DB can't be opened because users
  435. // can also specify a filename, not just a directory.
  436. DoCommand();
  437. if (exec_state_.IsNotStarted()) {
  438. exec_state_ = LDBCommandExecuteResult::Succeed("");
  439. }
  440. if (db_ != nullptr) {
  441. CloseDB();
  442. }
  443. }
  444. LDBCommand::LDBCommand(const std::map<std::string, std::string>& options,
  445. const std::vector<std::string>& flags, bool is_read_only,
  446. const std::vector<std::string>& valid_cmd_line_options)
  447. : db_(nullptr),
  448. db_ttl_(nullptr),
  449. is_read_only_(is_read_only),
  450. is_key_hex_(false),
  451. is_value_hex_(false),
  452. is_db_ttl_(false),
  453. timestamp_(false),
  454. try_load_options_(false),
  455. create_if_missing_(false),
  456. option_map_(options),
  457. flags_(flags),
  458. valid_cmd_line_options_(valid_cmd_line_options) {
  459. auto itr = options.find(ARG_DB);
  460. if (itr != options.end()) {
  461. db_path_ = itr->second;
  462. }
  463. itr = options.find(ARG_ENV_URI);
  464. if (itr != options.end()) {
  465. env_uri_ = itr->second;
  466. }
  467. itr = options.find(ARG_FS_URI);
  468. if (itr != options.end()) {
  469. fs_uri_ = itr->second;
  470. }
  471. itr = options.find(ARG_CF_NAME);
  472. if (itr != options.end()) {
  473. column_family_name_ = itr->second;
  474. } else {
  475. column_family_name_ = kDefaultColumnFamilyName;
  476. }
  477. itr = options.find(ARG_SECONDARY_PATH);
  478. secondary_path_ = "";
  479. if (itr != options.end()) {
  480. secondary_path_ = itr->second;
  481. }
  482. itr = options.find(ARG_LEADER_PATH);
  483. leader_path_ = "";
  484. if (itr != options.end()) {
  485. leader_path_ = itr->second;
  486. }
  487. is_key_hex_ = IsKeyHex(options, flags);
  488. is_value_hex_ = IsValueHex(options, flags);
  489. is_db_ttl_ = IsFlagPresent(flags, ARG_TTL);
  490. timestamp_ = IsFlagPresent(flags, ARG_TIMESTAMP);
  491. try_load_options_ = IsTryLoadOptions(options, flags);
  492. force_consistency_checks_ =
  493. !IsFlagPresent(flags, ARG_DISABLE_CONSISTENCY_CHECKS);
  494. enable_blob_files_ = IsFlagPresent(flags, ARG_ENABLE_BLOB_FILES);
  495. enable_blob_garbage_collection_ =
  496. IsFlagPresent(flags, ARG_ENABLE_BLOB_GARBAGE_COLLECTION);
  497. config_options_.ignore_unknown_options =
  498. IsFlagPresent(flags, ARG_IGNORE_UNKNOWN_OPTIONS);
  499. }
  500. void LDBCommand::OpenDB() {
  501. PrepareOptions();
  502. if (!exec_state_.IsNotStarted()) {
  503. return;
  504. }
  505. if (column_families_.empty() && !options_.merge_operator) {
  506. // No harm to add a general merge operator if it is not specified.
  507. options_.merge_operator = MergeOperators::CreateStringAppendOperator(':');
  508. }
  509. // Open the DB.
  510. Status st;
  511. std::vector<ColumnFamilyHandle*> handles_opened;
  512. if (is_db_ttl_) {
  513. // ldb doesn't yet support TTL DB with multiple column families
  514. if (!column_family_name_.empty() || !column_families_.empty()) {
  515. exec_state_ = LDBCommandExecuteResult::Failed(
  516. "ldb doesn't support TTL DB with multiple column families");
  517. }
  518. if (!secondary_path_.empty() || !leader_path_.empty()) {
  519. exec_state_ = LDBCommandExecuteResult::Failed(
  520. "Open as secondary or follower is not supported for TTL DB yet.");
  521. }
  522. if (is_read_only_) {
  523. st = DBWithTTL::Open(options_, db_path_, &db_ttl_, 0, true);
  524. } else {
  525. st = DBWithTTL::Open(options_, db_path_, &db_ttl_);
  526. }
  527. db_ = db_ttl_;
  528. } else {
  529. if (!secondary_path_.empty() && !leader_path_.empty()) {
  530. exec_state_ = LDBCommandExecuteResult::Failed(
  531. "Cannot provide both secondary and leader paths");
  532. }
  533. if (is_read_only_ && secondary_path_.empty() && leader_path_.empty()) {
  534. if (column_families_.empty()) {
  535. st = DB::OpenForReadOnly(options_, db_path_, &db_);
  536. } else {
  537. st = DB::OpenForReadOnly(options_, db_path_, column_families_,
  538. &handles_opened, &db_);
  539. }
  540. } else {
  541. if (column_families_.empty()) {
  542. if (secondary_path_.empty() && leader_path_.empty()) {
  543. st = DB::Open(options_, db_path_, &db_);
  544. } else if (!secondary_path_.empty()) {
  545. st = DB::OpenAsSecondary(options_, db_path_, secondary_path_, &db_);
  546. } else {
  547. std::unique_ptr<DB> dbptr;
  548. st = DB::OpenAsFollower(options_, db_path_, leader_path_, &dbptr);
  549. db_ = dbptr.release();
  550. }
  551. } else {
  552. if (secondary_path_.empty() && leader_path_.empty()) {
  553. st = DB::Open(options_, db_path_, column_families_, &handles_opened,
  554. &db_);
  555. } else if (!secondary_path_.empty()) {
  556. st = DB::OpenAsSecondary(options_, db_path_, secondary_path_,
  557. column_families_, &handles_opened, &db_);
  558. } else {
  559. std::unique_ptr<DB> dbptr;
  560. st = DB::OpenAsFollower(options_, db_path_, leader_path_,
  561. column_families_, &handles_opened, &dbptr);
  562. db_ = dbptr.release();
  563. }
  564. }
  565. }
  566. }
  567. if (!st.ok()) {
  568. std::string msg = st.ToString();
  569. exec_state_ = LDBCommandExecuteResult::Failed(msg);
  570. } else if (!handles_opened.empty()) {
  571. assert(handles_opened.size() == column_families_.size());
  572. bool found_cf_name = false;
  573. for (size_t i = 0; i < handles_opened.size(); i++) {
  574. cf_handles_[column_families_[i].name] = handles_opened[i];
  575. ucmps_[handles_opened[i]->GetID()] = handles_opened[i]->GetComparator();
  576. if (column_family_name_ == column_families_[i].name) {
  577. found_cf_name = true;
  578. }
  579. }
  580. if (!found_cf_name) {
  581. exec_state_ = LDBCommandExecuteResult::Failed(
  582. "Non-existing column family " + column_family_name_);
  583. CloseDB();
  584. }
  585. ColumnFamilyHandle* default_cf = db_->DefaultColumnFamily();
  586. ucmps_[default_cf->GetID()] = default_cf->GetComparator();
  587. } else {
  588. // We successfully opened DB in single column family mode.
  589. assert(column_families_.empty());
  590. if (column_family_name_ != kDefaultColumnFamilyName) {
  591. exec_state_ = LDBCommandExecuteResult::Failed(
  592. "Non-existing column family " + column_family_name_);
  593. CloseDB();
  594. }
  595. ColumnFamilyHandle* default_cf = db_->DefaultColumnFamily();
  596. ucmps_[default_cf->GetID()] = default_cf->GetComparator();
  597. }
  598. }
  599. void LDBCommand::CloseDB() {
  600. if (db_ != nullptr) {
  601. for (auto& pair : cf_handles_) {
  602. delete pair.second;
  603. }
  604. Status s = db_->Close();
  605. s.PermitUncheckedError();
  606. delete db_;
  607. db_ = nullptr;
  608. }
  609. }
  610. ColumnFamilyHandle* LDBCommand::GetCfHandle() {
  611. if (!cf_handles_.empty()) {
  612. auto it = cf_handles_.find(column_family_name_);
  613. if (it == cf_handles_.end()) {
  614. exec_state_ = LDBCommandExecuteResult::Failed(
  615. "Cannot find column family " + column_family_name_);
  616. } else {
  617. return it->second;
  618. }
  619. }
  620. return db_->DefaultColumnFamily();
  621. }
  622. std::vector<std::string> LDBCommand::BuildCmdLineOptions(
  623. std::vector<std::string> options) {
  624. std::vector<std::string> ret = {ARG_ENV_URI,
  625. ARG_FS_URI,
  626. ARG_DB,
  627. ARG_SECONDARY_PATH,
  628. ARG_LEADER_PATH,
  629. ARG_BLOOM_BITS,
  630. ARG_BLOCK_SIZE,
  631. ARG_AUTO_COMPACTION,
  632. ARG_COMPRESSION_TYPE,
  633. ARG_COMPRESSION_MAX_DICT_BYTES,
  634. ARG_WRITE_BUFFER_SIZE,
  635. ARG_FILE_SIZE,
  636. ARG_FIX_PREFIX_LEN,
  637. ARG_TRY_LOAD_OPTIONS,
  638. ARG_DISABLE_CONSISTENCY_CHECKS,
  639. ARG_ENABLE_BLOB_FILES,
  640. ARG_MIN_BLOB_SIZE,
  641. ARG_BLOB_FILE_SIZE,
  642. ARG_BLOB_COMPRESSION_TYPE,
  643. ARG_ENABLE_BLOB_GARBAGE_COLLECTION,
  644. ARG_BLOB_GARBAGE_COLLECTION_AGE_CUTOFF,
  645. ARG_BLOB_GARBAGE_COLLECTION_FORCE_THRESHOLD,
  646. ARG_BLOB_COMPACTION_READAHEAD_SIZE,
  647. ARG_BLOB_FILE_STARTING_LEVEL,
  648. ARG_PREPOPULATE_BLOB_CACHE,
  649. ARG_IGNORE_UNKNOWN_OPTIONS,
  650. ARG_CF_NAME};
  651. ret.insert(ret.end(), options.begin(), options.end());
  652. return ret;
  653. }
  654. /**
  655. * Parses the specific double option and fills in the value.
  656. * Returns true if the option is found.
  657. * Returns false if the option is not found or if there is an error parsing the
  658. * value. If there is an error, the specified exec_state is also
  659. * updated.
  660. */
  661. bool LDBCommand::ParseDoubleOption(
  662. const std::map<std::string, std::string>& /*options*/,
  663. const std::string& option, double& value,
  664. LDBCommandExecuteResult& exec_state) {
  665. auto itr = option_map_.find(option);
  666. if (itr != option_map_.end()) {
  667. #if defined(CYGWIN)
  668. char* str_end = nullptr;
  669. value = std::strtod(itr->second.c_str(), &str_end);
  670. if (str_end == itr->second.c_str()) {
  671. exec_state =
  672. LDBCommandExecuteResult::Failed(option + " has an invalid value.");
  673. } else if (errno == ERANGE) {
  674. exec_state = LDBCommandExecuteResult::Failed(
  675. option + " has a value out-of-range.");
  676. } else {
  677. return true;
  678. }
  679. #else
  680. try {
  681. value = std::stod(itr->second);
  682. return true;
  683. } catch (const std::invalid_argument&) {
  684. exec_state =
  685. LDBCommandExecuteResult::Failed(option + " has an invalid value.");
  686. } catch (const std::out_of_range&) {
  687. exec_state = LDBCommandExecuteResult::Failed(
  688. option + " has a value out-of-range.");
  689. }
  690. #endif
  691. }
  692. return false;
  693. }
  694. /**
  695. * Parses the specific integer option and fills in the value.
  696. * Returns true if the option is found.
  697. * Returns false if the option is not found or if there is an error parsing the
  698. * value. If there is an error, the specified exec_state is also
  699. * updated.
  700. */
  701. bool LDBCommand::ParseIntOption(
  702. const std::map<std::string, std::string>& /*options*/,
  703. const std::string& option, int& value,
  704. LDBCommandExecuteResult& exec_state) {
  705. auto itr = option_map_.find(option);
  706. if (itr != option_map_.end()) {
  707. #if defined(CYGWIN)
  708. char* str_end = nullptr;
  709. value = strtol(itr->second.c_str(), &str_end, 10);
  710. if (str_end == itr->second.c_str()) {
  711. exec_state =
  712. LDBCommandExecuteResult::Failed(option + " has an invalid value.");
  713. } else if (errno == ERANGE) {
  714. exec_state = LDBCommandExecuteResult::Failed(
  715. option + " has a value out-of-range.");
  716. } else {
  717. return true;
  718. }
  719. #else
  720. try {
  721. value = std::stoi(itr->second);
  722. return true;
  723. } catch (const std::invalid_argument&) {
  724. exec_state =
  725. LDBCommandExecuteResult::Failed(option + " has an invalid value.");
  726. } catch (const std::out_of_range&) {
  727. exec_state = LDBCommandExecuteResult::Failed(
  728. option + " has a value out-of-range.");
  729. }
  730. #endif
  731. }
  732. return false;
  733. }
  734. /**
  735. * Parses the specified option and fills in the value.
  736. * Returns true if the option is found.
  737. * Returns false otherwise.
  738. */
  739. bool LDBCommand::ParseStringOption(
  740. const std::map<std::string, std::string>& /*options*/,
  741. const std::string& option, std::string* value) {
  742. auto itr = option_map_.find(option);
  743. if (itr != option_map_.end()) {
  744. *value = itr->second;
  745. return true;
  746. }
  747. return false;
  748. }
  749. /**
  750. * Parses the specified compression type and fills in the value.
  751. * Returns true if the compression type is found.
  752. * Returns false otherwise.
  753. */
  754. bool LDBCommand::ParseCompressionTypeOption(
  755. const std::map<std::string, std::string>& /*options*/,
  756. const std::string& option, CompressionType& value,
  757. LDBCommandExecuteResult& exec_state) {
  758. auto itr = option_map_.find(option);
  759. if (itr != option_map_.end()) {
  760. const std::string& comp = itr->second;
  761. if (comp == "no") {
  762. value = kNoCompression;
  763. return true;
  764. } else if (comp == "snappy") {
  765. if (!Snappy_Supported()) {
  766. exec_state = LDBCommandExecuteResult::Failed(
  767. "Snappy compression is not supported in this build.");
  768. } else {
  769. value = kSnappyCompression;
  770. return true;
  771. }
  772. } else if (comp == "zlib") {
  773. if (!Zlib_Supported()) {
  774. exec_state = LDBCommandExecuteResult::Failed(
  775. "zlib compression is not supported in this build.");
  776. } else {
  777. value = kZlibCompression;
  778. return true;
  779. }
  780. } else if (comp == "bzip2") {
  781. if (!BZip2_Supported()) {
  782. exec_state = LDBCommandExecuteResult::Failed(
  783. "bzip2 compression is not supported in this build.");
  784. } else {
  785. value = kBZip2Compression;
  786. return true;
  787. }
  788. } else if (comp == "lz4") {
  789. if (!LZ4_Supported()) {
  790. exec_state = LDBCommandExecuteResult::Failed(
  791. "lz4 compression is not supported in this build.");
  792. } else {
  793. value = kLZ4Compression;
  794. return true;
  795. }
  796. } else if (comp == "lz4hc") {
  797. if (!LZ4_Supported()) {
  798. exec_state = LDBCommandExecuteResult::Failed(
  799. "lz4hc compression is not supported in this build.");
  800. } else {
  801. value = kLZ4HCCompression;
  802. return true;
  803. }
  804. } else if (comp == "xpress") {
  805. if (!XPRESS_Supported()) {
  806. exec_state = LDBCommandExecuteResult::Failed(
  807. "xpress compression is not supported in this build.");
  808. } else {
  809. value = kXpressCompression;
  810. return true;
  811. }
  812. } else if (comp == "zstd") {
  813. if (!ZSTD_Supported()) {
  814. exec_state = LDBCommandExecuteResult::Failed(
  815. "zstd compression is not supported in this build.");
  816. } else {
  817. value = kZSTD;
  818. return true;
  819. }
  820. #ifndef NDEBUG
  821. } else if (comp == "mixed" && option == ARG_COMPRESSION_TYPE) {
  822. if (GetSupportedCompressions().empty()) {
  823. exec_state = LDBCommandExecuteResult::Failed(
  824. "No compressions are supported in this build for \"mixed\".");
  825. return false;
  826. }
  827. options_.compression = kZSTD;
  828. options_.bottommost_compression = kZSTD;
  829. auto mgr =
  830. std::make_shared<RoundRobinManager>(GetBuiltinV2CompressionManager());
  831. options_.compression_manager = mgr;
  832. // Need to list zstd in the compression_name table property if it's
  833. // potentially used by being in the mix (i.e., potentially at least one
  834. // data block in the table is compressed by zstd). This ensures proper
  835. // context and dictionary handling, and prevents crashes in older RocksDB
  836. // versions.
  837. //
  838. // To achieve this, set `value` (the compression_type in Options which
  839. // will be used to set compression_name table property) to kZSTD, even if
  840. // multiple compression types are used within a single table.
  841. value = ZSTD_Supported() ? kZSTD : GetSupportedCompressions()[0];
  842. return true;
  843. #endif // !NDEBUG
  844. } else {
  845. // Unknown compression.
  846. exec_state = LDBCommandExecuteResult::Failed(
  847. "Unknown compression algorithm: " + comp);
  848. }
  849. }
  850. return false;
  851. }
  852. Status LDBCommand::MaybePopulateReadTimestamp(ColumnFamilyHandle* cfh,
  853. ReadOptions& ropts,
  854. Slice* read_timestamp) {
  855. const size_t ts_sz = cfh->GetComparator()->timestamp_size();
  856. auto iter = option_map_.find(ARG_READ_TIMESTAMP);
  857. if (iter == option_map_.end()) {
  858. if (ts_sz == 0) {
  859. return Status::OK();
  860. }
  861. return Status::InvalidArgument(
  862. "column family enables user-defined timestamp while --read_timestamp "
  863. "is not provided.");
  864. }
  865. if (iter->second.empty()) {
  866. if (ts_sz == 0) {
  867. return Status::OK();
  868. }
  869. return Status::InvalidArgument(
  870. "column family enables user-defined timestamp while --read_timestamp "
  871. "is empty.");
  872. }
  873. if (ts_sz == 0) {
  874. return Status::InvalidArgument(
  875. "column family does not enable user-defined timestamps while "
  876. "--read_timestamp is provided.");
  877. }
  878. Status s = EncodeUserProvidedTimestamp(iter->second, &read_timestamp_);
  879. if (!s.ok()) {
  880. return s;
  881. }
  882. *read_timestamp = read_timestamp_;
  883. ropts.timestamp = read_timestamp;
  884. return Status::OK();
  885. }
  886. void LDBCommand::OverrideBaseOptions() {
  887. options_.create_if_missing = false;
  888. int db_write_buffer_size;
  889. if (ParseIntOption(option_map_, ARG_DB_WRITE_BUFFER_SIZE,
  890. db_write_buffer_size, exec_state_)) {
  891. if (db_write_buffer_size >= 0) {
  892. options_.db_write_buffer_size = db_write_buffer_size;
  893. } else {
  894. exec_state_ = LDBCommandExecuteResult::Failed(ARG_DB_WRITE_BUFFER_SIZE +
  895. " must be >= 0.");
  896. }
  897. }
  898. if (options_.db_paths.size() == 0) {
  899. options_.db_paths.emplace_back(db_path_,
  900. std::numeric_limits<uint64_t>::max());
  901. }
  902. OverrideBaseCFOptions(static_cast<ColumnFamilyOptions*>(&options_));
  903. }
  904. void LDBCommand::OverrideBaseCFOptions(ColumnFamilyOptions* cf_opts) {
  905. BlockBasedTableOptions table_options;
  906. bool use_table_options = false;
  907. int bits;
  908. if (ParseIntOption(option_map_, ARG_BLOOM_BITS, bits, exec_state_)) {
  909. if (bits > 0) {
  910. use_table_options = true;
  911. table_options.filter_policy.reset(NewBloomFilterPolicy(bits));
  912. } else {
  913. exec_state_ =
  914. LDBCommandExecuteResult::Failed(ARG_BLOOM_BITS + " must be > 0.");
  915. }
  916. }
  917. int block_size;
  918. if (ParseIntOption(option_map_, ARG_BLOCK_SIZE, block_size, exec_state_)) {
  919. if (block_size > 0) {
  920. use_table_options = true;
  921. table_options.block_size = block_size;
  922. } else {
  923. exec_state_ =
  924. LDBCommandExecuteResult::Failed(ARG_BLOCK_SIZE + " must be > 0.");
  925. }
  926. }
  927. // Default comparator is BytewiseComparator, so only when it's not, it
  928. // means user has a command line override.
  929. if (options_.comparator != nullptr &&
  930. options_.comparator != BytewiseComparator()) {
  931. cf_opts->comparator = options_.comparator;
  932. }
  933. cf_opts->force_consistency_checks = force_consistency_checks_;
  934. if (use_table_options) {
  935. cf_opts->table_factory.reset(NewBlockBasedTableFactory(table_options));
  936. }
  937. cf_opts->enable_blob_files = enable_blob_files_;
  938. int min_blob_size;
  939. if (ParseIntOption(option_map_, ARG_MIN_BLOB_SIZE, min_blob_size,
  940. exec_state_)) {
  941. if (min_blob_size >= 0) {
  942. cf_opts->min_blob_size = min_blob_size;
  943. } else {
  944. exec_state_ =
  945. LDBCommandExecuteResult::Failed(ARG_MIN_BLOB_SIZE + " must be >= 0.");
  946. }
  947. }
  948. int blob_file_size;
  949. if (ParseIntOption(option_map_, ARG_BLOB_FILE_SIZE, blob_file_size,
  950. exec_state_)) {
  951. if (blob_file_size > 0) {
  952. cf_opts->blob_file_size = blob_file_size;
  953. } else {
  954. exec_state_ =
  955. LDBCommandExecuteResult::Failed(ARG_BLOB_FILE_SIZE + " must be > 0.");
  956. }
  957. }
  958. cf_opts->enable_blob_garbage_collection = enable_blob_garbage_collection_;
  959. double blob_garbage_collection_age_cutoff;
  960. if (ParseDoubleOption(option_map_, ARG_BLOB_GARBAGE_COLLECTION_AGE_CUTOFF,
  961. blob_garbage_collection_age_cutoff, exec_state_)) {
  962. if (blob_garbage_collection_age_cutoff >= 0 &&
  963. blob_garbage_collection_age_cutoff <= 1) {
  964. cf_opts->blob_garbage_collection_age_cutoff =
  965. blob_garbage_collection_age_cutoff;
  966. } else {
  967. exec_state_ = LDBCommandExecuteResult::Failed(
  968. ARG_BLOB_GARBAGE_COLLECTION_AGE_CUTOFF + " must be >= 0 and <= 1.");
  969. }
  970. }
  971. double blob_garbage_collection_force_threshold;
  972. if (ParseDoubleOption(option_map_,
  973. ARG_BLOB_GARBAGE_COLLECTION_FORCE_THRESHOLD,
  974. blob_garbage_collection_force_threshold, exec_state_)) {
  975. if (blob_garbage_collection_force_threshold >= 0 &&
  976. blob_garbage_collection_force_threshold <= 1) {
  977. cf_opts->blob_garbage_collection_force_threshold =
  978. blob_garbage_collection_force_threshold;
  979. } else {
  980. exec_state_ = LDBCommandExecuteResult::Failed(
  981. ARG_BLOB_GARBAGE_COLLECTION_FORCE_THRESHOLD +
  982. " must be >= 0 and <= 1.");
  983. }
  984. }
  985. int blob_compaction_readahead_size;
  986. if (ParseIntOption(option_map_, ARG_BLOB_COMPACTION_READAHEAD_SIZE,
  987. blob_compaction_readahead_size, exec_state_)) {
  988. if (blob_compaction_readahead_size > 0) {
  989. cf_opts->blob_compaction_readahead_size = blob_compaction_readahead_size;
  990. } else {
  991. exec_state_ = LDBCommandExecuteResult::Failed(
  992. ARG_BLOB_COMPACTION_READAHEAD_SIZE + " must be > 0.");
  993. }
  994. }
  995. int blob_file_starting_level;
  996. if (ParseIntOption(option_map_, ARG_BLOB_FILE_STARTING_LEVEL,
  997. blob_file_starting_level, exec_state_)) {
  998. if (blob_file_starting_level >= 0) {
  999. cf_opts->blob_file_starting_level = blob_file_starting_level;
  1000. } else {
  1001. exec_state_ = LDBCommandExecuteResult::Failed(
  1002. ARG_BLOB_FILE_STARTING_LEVEL + " must be >= 0.");
  1003. }
  1004. }
  1005. int prepopulate_blob_cache;
  1006. if (ParseIntOption(option_map_, ARG_PREPOPULATE_BLOB_CACHE,
  1007. prepopulate_blob_cache, exec_state_)) {
  1008. switch (prepopulate_blob_cache) {
  1009. case 0:
  1010. cf_opts->prepopulate_blob_cache = PrepopulateBlobCache::kDisable;
  1011. break;
  1012. case 1:
  1013. cf_opts->prepopulate_blob_cache = PrepopulateBlobCache::kFlushOnly;
  1014. break;
  1015. default:
  1016. exec_state_ = LDBCommandExecuteResult::Failed(
  1017. ARG_PREPOPULATE_BLOB_CACHE +
  1018. " must be 0 (disable) or 1 (flush only).");
  1019. }
  1020. }
  1021. auto itr = option_map_.find(ARG_AUTO_COMPACTION);
  1022. if (itr != option_map_.end()) {
  1023. cf_opts->disable_auto_compactions = !StringToBool(itr->second);
  1024. }
  1025. CompressionType compression_type;
  1026. if (ParseCompressionTypeOption(option_map_, ARG_COMPRESSION_TYPE,
  1027. compression_type, exec_state_)) {
  1028. cf_opts->compression = compression_type;
  1029. }
  1030. CompressionType blob_compression_type;
  1031. if (ParseCompressionTypeOption(option_map_, ARG_BLOB_COMPRESSION_TYPE,
  1032. blob_compression_type, exec_state_)) {
  1033. cf_opts->blob_compression_type = blob_compression_type;
  1034. }
  1035. int compression_max_dict_bytes;
  1036. if (ParseIntOption(option_map_, ARG_COMPRESSION_MAX_DICT_BYTES,
  1037. compression_max_dict_bytes, exec_state_)) {
  1038. if (compression_max_dict_bytes >= 0) {
  1039. cf_opts->compression_opts.max_dict_bytes = compression_max_dict_bytes;
  1040. } else {
  1041. exec_state_ = LDBCommandExecuteResult::Failed(
  1042. ARG_COMPRESSION_MAX_DICT_BYTES + " must be >= 0.");
  1043. }
  1044. }
  1045. int write_buffer_size;
  1046. if (ParseIntOption(option_map_, ARG_WRITE_BUFFER_SIZE, write_buffer_size,
  1047. exec_state_)) {
  1048. if (write_buffer_size > 0) {
  1049. cf_opts->write_buffer_size = write_buffer_size;
  1050. } else {
  1051. exec_state_ = LDBCommandExecuteResult::Failed(ARG_WRITE_BUFFER_SIZE +
  1052. " must be > 0.");
  1053. }
  1054. }
  1055. int file_size;
  1056. if (ParseIntOption(option_map_, ARG_FILE_SIZE, file_size, exec_state_)) {
  1057. if (file_size > 0) {
  1058. cf_opts->target_file_size_base = file_size;
  1059. } else {
  1060. exec_state_ =
  1061. LDBCommandExecuteResult::Failed(ARG_FILE_SIZE + " must be > 0.");
  1062. }
  1063. }
  1064. int fix_prefix_len;
  1065. if (ParseIntOption(option_map_, ARG_FIX_PREFIX_LEN, fix_prefix_len,
  1066. exec_state_)) {
  1067. if (fix_prefix_len > 0) {
  1068. cf_opts->prefix_extractor.reset(
  1069. NewFixedPrefixTransform(static_cast<size_t>(fix_prefix_len)));
  1070. } else {
  1071. exec_state_ =
  1072. LDBCommandExecuteResult::Failed(ARG_FIX_PREFIX_LEN + " must be > 0.");
  1073. }
  1074. }
  1075. }
  1076. // First, initializes the options state using the OPTIONS file when enabled.
  1077. // Second, overrides the options according to the CLI arguments and the
  1078. // specific subcommand being run.
  1079. void LDBCommand::PrepareOptions() {
  1080. DbStressCustomCompressionManager::Register();
  1081. std::vector<ColumnFamilyDescriptor> column_families_from_options;
  1082. if (!create_if_missing_ && try_load_options_) {
  1083. config_options_.env = options_.env;
  1084. Status s = LoadLatestOptions(config_options_, db_path_, &options_,
  1085. &column_families_from_options);
  1086. if (!s.ok() && !s.IsNotFound()) {
  1087. // Option file exists but load option file error.
  1088. std::string current_version = std::to_string(ROCKSDB_MAJOR) + "." +
  1089. std::to_string(ROCKSDB_MINOR) + "." +
  1090. std::to_string(ROCKSDB_PATCH);
  1091. std::string msg =
  1092. s.ToString() + "\nThis tool was built with version " +
  1093. current_version +
  1094. ". If your db is in a different version, please try again "
  1095. "with option --" +
  1096. LDBCommand::ARG_IGNORE_UNKNOWN_OPTIONS + ".";
  1097. exec_state_ = LDBCommandExecuteResult::Failed(msg);
  1098. db_ = nullptr;
  1099. return;
  1100. }
  1101. if (!options_.wal_dir.empty()) {
  1102. if (options_.env->FileExists(options_.wal_dir).IsNotFound()) {
  1103. options_.wal_dir = db_path_;
  1104. fprintf(
  1105. stderr,
  1106. "wal_dir loaded from the option file doesn't exist. Ignore it.\n");
  1107. }
  1108. }
  1109. // If merge operator is not set, set a string append operator.
  1110. for (auto& cf_entry : column_families_from_options) {
  1111. if (!cf_entry.options.merge_operator) {
  1112. cf_entry.options.merge_operator =
  1113. MergeOperators::CreateStringAppendOperator(':');
  1114. }
  1115. }
  1116. }
  1117. if (options_.env == Env::Default()) {
  1118. options_.env = config_options_.env;
  1119. }
  1120. OverrideBaseOptions();
  1121. if (exec_state_.IsFailed()) {
  1122. return;
  1123. }
  1124. if (column_families_.empty()) {
  1125. // column_families not set. Either set it from MANIFEST or OPTIONS file.
  1126. if (column_families_from_options.empty()) {
  1127. // Reads the MANIFEST to figure out what column families exist. In this
  1128. // case, the option overrides from the CLI argument/specific subcommand
  1129. // apply to all column families.
  1130. std::vector<std::string> cf_list;
  1131. Status st = DB::ListColumnFamilies(options_, db_path_, &cf_list);
  1132. // It is possible the DB doesn't exist yet, for "create if not
  1133. // existing" case. The failure is ignored here. We rely on DB::Open()
  1134. // to give us the correct error message for problem with opening
  1135. // existing DB.
  1136. if (st.ok() && cf_list.size() > 1) {
  1137. // Ignore single column family DB.
  1138. for (const auto& cf_name : cf_list) {
  1139. column_families_.emplace_back(cf_name, options_);
  1140. }
  1141. }
  1142. } else {
  1143. SetColumnFamilies(&column_families_from_options);
  1144. }
  1145. }
  1146. if (!column_families_from_options.empty()) {
  1147. // We got column families from the OPTIONS file. In this case, the option
  1148. // overrides from the CLI argument/specific subcommand only apply to the
  1149. // column family specified by `--column_family_name`.
  1150. auto column_families_iter =
  1151. std::find_if(column_families_.begin(), column_families_.end(),
  1152. [this](const ColumnFamilyDescriptor& cf_desc) {
  1153. return cf_desc.name == column_family_name_;
  1154. });
  1155. if (column_families_iter == column_families_.end()) {
  1156. exec_state_ = LDBCommandExecuteResult::Failed(
  1157. "Non-existing column family " + column_family_name_);
  1158. return;
  1159. }
  1160. OverrideBaseCFOptions(&column_families_iter->options);
  1161. }
  1162. }
  1163. bool LDBCommand::ParseKeyValue(const std::string& line, std::string* key,
  1164. std::string* value, bool is_key_hex,
  1165. bool is_value_hex) {
  1166. size_t pos = line.find(DELIM);
  1167. if (pos != std::string::npos) {
  1168. *key = line.substr(0, pos);
  1169. *value = line.substr(pos + strlen(DELIM));
  1170. if (is_key_hex) {
  1171. *key = HexToString(*key);
  1172. }
  1173. if (is_value_hex) {
  1174. *value = HexToString(*value);
  1175. }
  1176. return true;
  1177. } else {
  1178. return false;
  1179. }
  1180. }
  1181. /**
  1182. * Make sure that ONLY the command-line options and flags expected by this
  1183. * command are specified on the command-line. Extraneous options are usually
  1184. * the result of user error.
  1185. * Returns true if all checks pass. Else returns false, and prints an
  1186. * appropriate error msg to stderr.
  1187. */
  1188. bool LDBCommand::ValidateCmdLineOptions() {
  1189. for (auto itr = option_map_.begin(); itr != option_map_.end(); ++itr) {
  1190. if (std::find(valid_cmd_line_options_.begin(),
  1191. valid_cmd_line_options_.end(),
  1192. itr->first) == valid_cmd_line_options_.end()) {
  1193. fprintf(stderr, "Invalid command-line option %s\n", itr->first.c_str());
  1194. return false;
  1195. }
  1196. }
  1197. for (std::vector<std::string>::const_iterator itr = flags_.begin();
  1198. itr != flags_.end(); ++itr) {
  1199. if (std::find(valid_cmd_line_options_.begin(),
  1200. valid_cmd_line_options_.end(),
  1201. *itr) == valid_cmd_line_options_.end()) {
  1202. fprintf(stderr, "Invalid command-line flag %s\n", itr->c_str());
  1203. return false;
  1204. }
  1205. }
  1206. if (!NoDBOpen() && option_map_.find(ARG_DB) == option_map_.end() &&
  1207. option_map_.find(ARG_PATH) == option_map_.end()) {
  1208. fprintf(stderr, "Either %s or %s must be specified.\n", ARG_DB.c_str(),
  1209. ARG_PATH.c_str());
  1210. return false;
  1211. }
  1212. return true;
  1213. }
  1214. std::string LDBCommand::HexToString(const std::string& str) {
  1215. std::string result;
  1216. std::string::size_type len = str.length();
  1217. if (len < 2 || str[0] != '0' || str[1] != 'x') {
  1218. fprintf(stderr, "Invalid hex input %s. Must start with 0x\n", str.c_str());
  1219. throw "Invalid hex input";
  1220. }
  1221. if (!Slice(str.data() + 2, len - 2).DecodeHex(&result)) {
  1222. throw "Invalid hex input";
  1223. }
  1224. return result;
  1225. }
  1226. std::string LDBCommand::StringToHex(const std::string& str) {
  1227. std::string result("0x");
  1228. result.append(Slice(str).ToString(true));
  1229. return result;
  1230. }
  1231. std::string LDBCommand::PrintKeyValue(const std::string& key,
  1232. const std::string& timestamp,
  1233. const std::string& value, bool is_key_hex,
  1234. bool is_value_hex,
  1235. const Comparator* ucmp) {
  1236. std::string result;
  1237. result.append(is_key_hex ? StringToHex(key) : key);
  1238. if (!timestamp.empty()) {
  1239. result.append("|timestamp:");
  1240. result.append(ucmp->TimestampToString(timestamp));
  1241. }
  1242. result.append(DELIM);
  1243. result.append(is_value_hex ? StringToHex(value) : value);
  1244. return result;
  1245. }
  1246. std::string LDBCommand::PrintKeyValue(const std::string& key,
  1247. const std::string& timestamp,
  1248. const std::string& value, bool is_hex,
  1249. const Comparator* ucmp) {
  1250. return PrintKeyValue(key, timestamp, value, is_hex, is_hex, ucmp);
  1251. }
  1252. std::string LDBCommand::PrintKeyValueOrWideColumns(
  1253. const Slice& key, const Slice& timestamp, const Slice& value,
  1254. const WideColumns& wide_columns, bool is_key_hex, bool is_value_hex,
  1255. const Comparator* ucmp) {
  1256. if (wide_columns.empty() ||
  1257. WideColumnsHelper::HasDefaultColumnOnly(wide_columns)) {
  1258. return PrintKeyValue(key.ToString(), timestamp.ToString(), value.ToString(),
  1259. is_key_hex, is_value_hex, ucmp);
  1260. }
  1261. /*
  1262. // Sample plaintext output (first column is kDefaultWideColumnName)
  1263. key_1 ==> :foo attr_name1:bar attr_name2:baz
  1264. // Sample hex output (first column is kDefaultWideColumnName)
  1265. 0x6669727374 ==> :0x68656C6C6F 0x617474725F6E616D6531:0x666F6F
  1266. */
  1267. std::ostringstream oss;
  1268. WideColumnsHelper::DumpWideColumns(wide_columns, oss, is_value_hex);
  1269. return PrintKeyValue(key.ToString(), timestamp.ToString(), oss.str().c_str(),
  1270. is_key_hex, false,
  1271. ucmp); // is_value_hex_ is already honored in oss.
  1272. // avoid double-hexing it.
  1273. }
  1274. std::string LDBCommand::HelpRangeCmdArgs() {
  1275. std::ostringstream str_stream;
  1276. str_stream << " ";
  1277. str_stream << "[--" << ARG_FROM << "] ";
  1278. str_stream << "[--" << ARG_TO << "] ";
  1279. return str_stream.str();
  1280. }
  1281. bool LDBCommand::IsKeyHex(const std::map<std::string, std::string>& options,
  1282. const std::vector<std::string>& flags) {
  1283. return (IsFlagPresent(flags, ARG_HEX) || IsFlagPresent(flags, ARG_KEY_HEX) ||
  1284. ParseBooleanOption(options, ARG_HEX, false) ||
  1285. ParseBooleanOption(options, ARG_KEY_HEX, false));
  1286. }
  1287. bool LDBCommand::IsValueHex(const std::map<std::string, std::string>& options,
  1288. const std::vector<std::string>& flags) {
  1289. return (IsFlagPresent(flags, ARG_HEX) ||
  1290. IsFlagPresent(flags, ARG_VALUE_HEX) ||
  1291. ParseBooleanOption(options, ARG_HEX, false) ||
  1292. ParseBooleanOption(options, ARG_VALUE_HEX, false));
  1293. }
  1294. bool LDBCommand::IsTryLoadOptions(
  1295. const std::map<std::string, std::string>& options,
  1296. const std::vector<std::string>& flags) {
  1297. if (IsFlagPresent(flags, ARG_TRY_LOAD_OPTIONS)) {
  1298. return true;
  1299. }
  1300. // if `DB` is specified and not explicitly to create a new db, default
  1301. // `try_load_options` to true. The user could still disable that by set
  1302. // `try_load_options=false`.
  1303. // Note: Opening as TTL DB doesn't support `try_load_options`, so it's default
  1304. // to false. TODO: TTL_DB may need to fix that, otherwise it's unable to open
  1305. // DB which has incompatible setting with default options.
  1306. bool default_val = (options.find(ARG_DB) != options.end()) &&
  1307. !IsFlagPresent(flags, ARG_CREATE_IF_MISSING) &&
  1308. !IsFlagPresent(flags, ARG_TTL);
  1309. return ParseBooleanOption(options, ARG_TRY_LOAD_OPTIONS, default_val);
  1310. }
  1311. bool LDBCommand::ParseBooleanOption(
  1312. const std::map<std::string, std::string>& options,
  1313. const std::string& option, bool default_val) {
  1314. auto itr = options.find(option);
  1315. if (itr != options.end()) {
  1316. std::string option_val = itr->second;
  1317. return StringToBool(itr->second);
  1318. }
  1319. return default_val;
  1320. }
  1321. bool LDBCommand::StringToBool(std::string val) {
  1322. std::transform(val.begin(), val.end(), val.begin(),
  1323. [](char ch) -> char { return (char)::tolower(ch); });
  1324. if (val == "true") {
  1325. return true;
  1326. } else if (val == "false") {
  1327. return false;
  1328. } else {
  1329. throw "Invalid value for boolean argument";
  1330. }
  1331. }
  1332. CompactorCommand::CompactorCommand(
  1333. const std::vector<std::string>& /*params*/,
  1334. const std::map<std::string, std::string>& options,
  1335. const std::vector<std::string>& flags)
  1336. : LDBCommand(options, flags, false /* is_read_only */,
  1337. BuildCmdLineOptions({ARG_FROM, ARG_TO, ARG_HEX, ARG_KEY_HEX,
  1338. ARG_VALUE_HEX, ARG_TTL})),
  1339. null_from_(true),
  1340. null_to_(true) {
  1341. auto itr = options.find(ARG_FROM);
  1342. if (itr != options.end()) {
  1343. null_from_ = false;
  1344. from_ = itr->second;
  1345. }
  1346. itr = options.find(ARG_TO);
  1347. if (itr != options.end()) {
  1348. null_to_ = false;
  1349. to_ = itr->second;
  1350. }
  1351. if (is_key_hex_) {
  1352. if (!null_from_) {
  1353. from_ = HexToString(from_);
  1354. }
  1355. if (!null_to_) {
  1356. to_ = HexToString(to_);
  1357. }
  1358. }
  1359. }
  1360. void CompactorCommand::Help(std::string& ret) {
  1361. ret.append(" ");
  1362. ret.append(CompactorCommand::Name());
  1363. ret.append(HelpRangeCmdArgs());
  1364. ret.append("\n");
  1365. }
  1366. void CompactorCommand::DoCommand() {
  1367. if (!db_) {
  1368. assert(GetExecuteState().IsFailed());
  1369. return;
  1370. }
  1371. Slice* begin = nullptr;
  1372. Slice* end = nullptr;
  1373. if (!null_from_) {
  1374. begin = new Slice(from_);
  1375. }
  1376. if (!null_to_) {
  1377. end = new Slice(to_);
  1378. }
  1379. CompactRangeOptions cro;
  1380. cro.bottommost_level_compaction = BottommostLevelCompaction::kForceOptimized;
  1381. Status s = db_->CompactRange(cro, GetCfHandle(), begin, end);
  1382. if (!s.ok()) {
  1383. std::stringstream oss;
  1384. oss << "Compaction failed: " << s.ToString();
  1385. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  1386. } else {
  1387. exec_state_ = LDBCommandExecuteResult::Succeed("");
  1388. }
  1389. delete begin;
  1390. delete end;
  1391. }
  1392. // ---------------------------------------------------------------------------
  1393. const std::string DBLoaderCommand::ARG_DISABLE_WAL = "disable_wal";
  1394. const std::string DBLoaderCommand::ARG_BULK_LOAD = "bulk_load";
  1395. const std::string DBLoaderCommand::ARG_COMPACT = "compact";
  1396. DBLoaderCommand::DBLoaderCommand(
  1397. const std::vector<std::string>& /*params*/,
  1398. const std::map<std::string, std::string>& options,
  1399. const std::vector<std::string>& flags)
  1400. : LDBCommand(
  1401. options, flags, false /* is_read_only */,
  1402. BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM,
  1403. ARG_TO, ARG_CREATE_IF_MISSING, ARG_DISABLE_WAL,
  1404. ARG_BULK_LOAD, ARG_COMPACT})),
  1405. disable_wal_(false),
  1406. bulk_load_(false),
  1407. compact_(false) {
  1408. create_if_missing_ = IsFlagPresent(flags, ARG_CREATE_IF_MISSING);
  1409. disable_wal_ = IsFlagPresent(flags, ARG_DISABLE_WAL);
  1410. bulk_load_ = IsFlagPresent(flags, ARG_BULK_LOAD);
  1411. compact_ = IsFlagPresent(flags, ARG_COMPACT);
  1412. }
  1413. void DBLoaderCommand::Help(std::string& ret) {
  1414. ret.append(" ");
  1415. ret.append(DBLoaderCommand::Name());
  1416. ret.append(" [--" + ARG_CREATE_IF_MISSING + "]");
  1417. ret.append(" [--" + ARG_DISABLE_WAL + "]");
  1418. ret.append(" [--" + ARG_BULK_LOAD + "]");
  1419. ret.append(" [--" + ARG_COMPACT + "]");
  1420. ret.append("\n");
  1421. }
  1422. void DBLoaderCommand::OverrideBaseOptions() {
  1423. LDBCommand::OverrideBaseOptions();
  1424. options_.create_if_missing = create_if_missing_;
  1425. if (bulk_load_) {
  1426. options_.PrepareForBulkLoad();
  1427. }
  1428. }
  1429. void DBLoaderCommand::DoCommand() {
  1430. if (!db_) {
  1431. assert(GetExecuteState().IsFailed());
  1432. return;
  1433. }
  1434. WriteOptions write_options;
  1435. if (disable_wal_) {
  1436. write_options.disableWAL = true;
  1437. }
  1438. int bad_lines = 0;
  1439. std::string line;
  1440. // prefer ifstream getline performance vs that from std::cin istream
  1441. std::ifstream ifs_stdin("/dev/stdin");
  1442. std::istream* istream_p = ifs_stdin.is_open() ? &ifs_stdin : &std::cin;
  1443. Status s;
  1444. while (s.ok() && getline(*istream_p, line, '\n')) {
  1445. std::string key;
  1446. std::string value;
  1447. if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
  1448. s = db_->Put(write_options, GetCfHandle(), Slice(key), Slice(value));
  1449. } else if (0 == line.find("Keys in range:")) {
  1450. // ignore this line
  1451. } else if (0 == line.find("Created bg thread 0x")) {
  1452. // ignore this line
  1453. } else {
  1454. bad_lines++;
  1455. }
  1456. }
  1457. if (bad_lines > 0) {
  1458. std::cout << "Warning: " << bad_lines << " bad lines ignored." << std::endl;
  1459. }
  1460. if (!s.ok()) {
  1461. std::stringstream oss;
  1462. oss << "Load failed: " << s.ToString();
  1463. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  1464. }
  1465. if (compact_ && s.ok()) {
  1466. s = db_->CompactRange(CompactRangeOptions(), GetCfHandle(), nullptr,
  1467. nullptr);
  1468. }
  1469. if (!s.ok()) {
  1470. std::stringstream oss;
  1471. oss << "Compaction failed: " << s.ToString();
  1472. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  1473. }
  1474. }
  1475. // ----------------------------------------------------------------------------
  1476. namespace {
  1477. void DumpManifestFile(Options options, std::string file, bool verbose, bool hex,
  1478. bool json,
  1479. const std::vector<ColumnFamilyDescriptor>& cf_descs) {
  1480. EnvOptions sopt;
  1481. std::string dbname("dummy");
  1482. std::shared_ptr<Cache> tc(NewLRUCache(options.max_open_files - 10,
  1483. options.table_cache_numshardbits));
  1484. // Notice we are using the default options not through SanitizeOptions(),
  1485. // if VersionSet::DumpManifest() depends on any option done by
  1486. // SanitizeOptions(), we need to initialize it manually.
  1487. options.db_paths.emplace_back("dummy", 0);
  1488. options.num_levels = 64;
  1489. WriteController wc(options.delayed_write_rate);
  1490. WriteBufferManager wb(options.db_write_buffer_size);
  1491. ImmutableDBOptions immutable_db_options(options);
  1492. VersionSet versions(dbname, &immutable_db_options, sopt, tc.get(), &wb, &wc,
  1493. /*block_cache_tracer=*/nullptr, /*io_tracer=*/nullptr,
  1494. /*db_id=*/"", /*db_session_id=*/"",
  1495. options.daily_offpeak_time_utc,
  1496. /*error_handler=*/nullptr, /*unchanging=*/true);
  1497. Status s = versions.DumpManifest(options, file, verbose, hex, json, cf_descs);
  1498. if (!s.ok()) {
  1499. fprintf(stderr, "Error in processing file %s %s\n", file.c_str(),
  1500. s.ToString().c_str());
  1501. }
  1502. }
  1503. void DumpCompactionProgressFile(const std::string& file_path) {
  1504. Status s;
  1505. std::unique_ptr<SequentialFileReader> file_reader;
  1506. std::unique_ptr<FSSequentialFile> file;
  1507. const std::shared_ptr<FileSystem>& fs = Env::Default()->GetFileSystem();
  1508. s = fs->NewSequentialFile(file_path, FileOptions(), &file, nullptr);
  1509. if (!s.ok()) {
  1510. fprintf(stderr, "Failed to open compaction progress file %s: %s\n",
  1511. file_path.c_str(), s.ToString().c_str());
  1512. return;
  1513. }
  1514. file_reader = std::make_unique<SequentialFileReader>(std::move(file),
  1515. file_path, 0, nullptr);
  1516. log::Reader reader(nullptr, std::move(file_reader), nullptr,
  1517. true /* checksum */, 0);
  1518. Slice record;
  1519. std::string scratch;
  1520. int count = 0;
  1521. fprintf(stdout, "Compaction Progress File: %s\n", file_path.c_str());
  1522. fprintf(stdout, "============================================\n");
  1523. while (reader.ReadRecord(&record, &scratch)) {
  1524. VersionEdit edit;
  1525. s = edit.DecodeFrom(record);
  1526. if (!s.ok()) {
  1527. fprintf(stderr, "Failed to decode VersionEdit: %s\n",
  1528. s.ToString().c_str());
  1529. continue;
  1530. }
  1531. if (edit.HasSubcompactionProgress()) {
  1532. fprintf(stdout, "Progress Record %d:\n", count);
  1533. const auto& progress = edit.GetSubcompactionProgress();
  1534. fprintf(stdout, "%s\n", progress.ToString().c_str());
  1535. ++count;
  1536. }
  1537. }
  1538. if (count == 0) {
  1539. fprintf(stdout,
  1540. "No valid records found in the compaction progress file.\n");
  1541. } else {
  1542. fprintf(stdout, "\nTotal records: %d\n", count);
  1543. }
  1544. }
  1545. } // namespace
  1546. const std::string ManifestDumpCommand::ARG_VERBOSE = "verbose";
  1547. const std::string ManifestDumpCommand::ARG_JSON = "json";
  1548. const std::string ManifestDumpCommand::ARG_PATH = "path";
  1549. void ManifestDumpCommand::Help(std::string& ret) {
  1550. ret.append(" ");
  1551. ret.append(ManifestDumpCommand::Name());
  1552. ret.append(" [--" + ARG_VERBOSE + "]");
  1553. ret.append(" [--" + ARG_JSON + "]");
  1554. ret.append(" [--" + ARG_PATH + "=<path_to_manifest_file>]");
  1555. ret.append("\n");
  1556. }
  1557. ManifestDumpCommand::ManifestDumpCommand(
  1558. const std::vector<std::string>& /*params*/,
  1559. const std::map<std::string, std::string>& options,
  1560. const std::vector<std::string>& flags)
  1561. : LDBCommand(
  1562. options, flags, true /* is_read_only */,
  1563. BuildCmdLineOptions({ARG_VERBOSE, ARG_PATH, ARG_HEX, ARG_JSON})),
  1564. verbose_(false),
  1565. json_(false) {
  1566. verbose_ = IsFlagPresent(flags, ARG_VERBOSE);
  1567. json_ = IsFlagPresent(flags, ARG_JSON);
  1568. auto itr = options.find(ARG_PATH);
  1569. if (itr != options.end()) {
  1570. path_ = itr->second;
  1571. if (path_.empty()) {
  1572. exec_state_ = LDBCommandExecuteResult::Failed("--path: missing pathname");
  1573. }
  1574. }
  1575. }
  1576. void ManifestDumpCommand::DoCommand() {
  1577. PrepareOptions();
  1578. std::string manifestfile;
  1579. if (!path_.empty()) {
  1580. manifestfile = path_;
  1581. } else {
  1582. // We need to find the manifest file by searching the directory
  1583. // containing the db for files of the form MANIFEST_[0-9]+
  1584. std::vector<std::string> files;
  1585. Status s = options_.env->GetChildren(db_path_, &files);
  1586. if (!s.ok()) {
  1587. std::string err_msg = s.ToString();
  1588. err_msg.append(": Failed to list the content of ");
  1589. err_msg.append(db_path_);
  1590. exec_state_ = LDBCommandExecuteResult::Failed(err_msg);
  1591. return;
  1592. }
  1593. const std::string kManifestNamePrefix = "MANIFEST-";
  1594. std::string matched_file;
  1595. #ifdef OS_WIN
  1596. const char kPathDelim = '\\';
  1597. #else
  1598. const char kPathDelim = '/';
  1599. #endif
  1600. for (const auto& file_path : files) {
  1601. // Some Env::GetChildren() return absolute paths. Some directories' path
  1602. // end with path delim, e.g. '/' or '\\'.
  1603. size_t pos = file_path.find_last_of(kPathDelim);
  1604. if (pos == file_path.size() - 1) {
  1605. continue;
  1606. }
  1607. std::string fname;
  1608. if (pos != std::string::npos) {
  1609. // Absolute path.
  1610. fname.assign(file_path, pos + 1, file_path.size() - pos - 1);
  1611. } else {
  1612. fname = file_path;
  1613. }
  1614. uint64_t file_num = 0;
  1615. FileType file_type = kWalFile; // Just for initialization
  1616. if (ParseFileName(fname, &file_num, &file_type) &&
  1617. file_type == kDescriptorFile) {
  1618. if (!matched_file.empty()) {
  1619. exec_state_ = LDBCommandExecuteResult::Failed(
  1620. "Multiple MANIFEST files found; use --path to select one");
  1621. return;
  1622. } else {
  1623. matched_file.swap(fname);
  1624. }
  1625. }
  1626. }
  1627. if (matched_file.empty()) {
  1628. std::string err_msg("No MANIFEST found in ");
  1629. err_msg.append(db_path_);
  1630. exec_state_ = LDBCommandExecuteResult::Failed(err_msg);
  1631. return;
  1632. }
  1633. if (db_path_.back() != '/') {
  1634. db_path_.append("/");
  1635. }
  1636. manifestfile = db_path_ + matched_file;
  1637. }
  1638. if (verbose_) {
  1639. fprintf(stdout, "Processing Manifest file %s\n", manifestfile.c_str());
  1640. }
  1641. DumpManifestFile(options_, manifestfile, verbose_, is_key_hex_, json_,
  1642. column_families_);
  1643. if (verbose_) {
  1644. fprintf(stdout, "Processing Manifest file %s done\n", manifestfile.c_str());
  1645. }
  1646. }
  1647. // ----------------------------------------------------------------------------
  1648. namespace {
  1649. Status GetLiveFilesChecksumInfoFromVersionSet(Options options,
  1650. const std::string& db_path,
  1651. FileChecksumList* checksum_list) {
  1652. EnvOptions sopt;
  1653. Status s;
  1654. std::string dbname(db_path);
  1655. std::shared_ptr<Cache> tc(NewLRUCache(options.max_open_files - 10,
  1656. options.table_cache_numshardbits));
  1657. // Notice we are using the default options not through SanitizeOptions(),
  1658. // if VersionSet::GetLiveFilesChecksumInfo depends on any option done by
  1659. // SanitizeOptions(), we need to initialize it manually.
  1660. options.db_paths.emplace_back(db_path, 0);
  1661. options.num_levels = 64;
  1662. WriteController wc(options.delayed_write_rate);
  1663. WriteBufferManager wb(options.db_write_buffer_size);
  1664. ImmutableDBOptions immutable_db_options(options);
  1665. VersionSet versions(dbname, &immutable_db_options, sopt, tc.get(), &wb, &wc,
  1666. /*block_cache_tracer=*/nullptr, /*io_tracer=*/nullptr,
  1667. /*db_id=*/"", /*db_session_id=*/"",
  1668. options.daily_offpeak_time_utc,
  1669. /*error_handler=*/nullptr, /*unchanging=*/true);
  1670. std::vector<std::string> cf_name_list;
  1671. s = versions.ListColumnFamilies(&cf_name_list, db_path,
  1672. immutable_db_options.fs.get());
  1673. if (s.ok()) {
  1674. std::vector<ColumnFamilyDescriptor> cf_list;
  1675. for (const auto& name : cf_name_list) {
  1676. cf_list.emplace_back(name, ColumnFamilyOptions(options));
  1677. }
  1678. s = versions.Recover(cf_list, true);
  1679. }
  1680. if (s.ok()) {
  1681. s = versions.GetLiveFilesChecksumInfo(checksum_list);
  1682. }
  1683. return s;
  1684. }
  1685. } // namespace
  1686. const std::string FileChecksumDumpCommand::ARG_PATH = "path";
  1687. void FileChecksumDumpCommand::Help(std::string& ret) {
  1688. ret.append(" ");
  1689. ret.append(FileChecksumDumpCommand::Name());
  1690. ret.append(" [--" + ARG_PATH + "=<path_to_manifest_file>]");
  1691. ret.append("\n");
  1692. }
  1693. FileChecksumDumpCommand::FileChecksumDumpCommand(
  1694. const std::vector<std::string>& /*params*/,
  1695. const std::map<std::string, std::string>& options,
  1696. const std::vector<std::string>& flags)
  1697. : LDBCommand(options, flags, true /* is_read_only */,
  1698. BuildCmdLineOptions({ARG_PATH, ARG_HEX})) {
  1699. auto itr = options.find(ARG_PATH);
  1700. if (itr != options.end()) {
  1701. path_ = itr->second;
  1702. if (path_.empty()) {
  1703. exec_state_ = LDBCommandExecuteResult::Failed("--path: missing pathname");
  1704. }
  1705. }
  1706. is_checksum_hex_ = IsFlagPresent(flags, ARG_HEX);
  1707. }
  1708. void FileChecksumDumpCommand::DoCommand() {
  1709. PrepareOptions();
  1710. // print out the checksum information in the following format:
  1711. // sst file number, checksum function name, checksum value
  1712. // sst file number, checksum function name, checksum value
  1713. // ......
  1714. std::unique_ptr<FileChecksumList> checksum_list(NewFileChecksumList());
  1715. Status s = GetLiveFilesChecksumInfoFromVersionSet(options_, db_path_,
  1716. checksum_list.get());
  1717. if (s.ok() && checksum_list != nullptr) {
  1718. std::vector<uint64_t> file_numbers;
  1719. std::vector<std::string> checksums;
  1720. std::vector<std::string> checksum_func_names;
  1721. s = checksum_list->GetAllFileChecksums(&file_numbers, &checksums,
  1722. &checksum_func_names);
  1723. if (s.ok()) {
  1724. for (size_t i = 0; i < file_numbers.size(); i++) {
  1725. assert(i < file_numbers.size());
  1726. assert(i < checksums.size());
  1727. assert(i < checksum_func_names.size());
  1728. std::string checksum;
  1729. if (is_checksum_hex_) {
  1730. checksum = StringToHex(checksums[i]);
  1731. } else {
  1732. checksum = std::move(checksums[i]);
  1733. }
  1734. fprintf(stdout, "%" PRId64 ", %s, %s\n", file_numbers[i],
  1735. checksum_func_names[i].c_str(), checksum.c_str());
  1736. }
  1737. fprintf(stdout, "Print SST file checksum information finished \n");
  1738. }
  1739. }
  1740. if (!s.ok()) {
  1741. exec_state_ = LDBCommandExecuteResult::Failed(s.ToString());
  1742. }
  1743. }
  1744. // ----------------------------------------------------------------------------
  1745. void GetPropertyCommand::Help(std::string& ret) {
  1746. ret.append(" ");
  1747. ret.append(GetPropertyCommand::Name());
  1748. ret.append(" <property_name>");
  1749. ret.append("\n");
  1750. }
  1751. GetPropertyCommand::GetPropertyCommand(
  1752. const std::vector<std::string>& params,
  1753. const std::map<std::string, std::string>& options,
  1754. const std::vector<std::string>& flags)
  1755. : LDBCommand(options, flags, true /* is_read_only */,
  1756. BuildCmdLineOptions({})) {
  1757. if (params.size() != 1) {
  1758. exec_state_ =
  1759. LDBCommandExecuteResult::Failed("property name must be specified");
  1760. } else {
  1761. property_ = params[0];
  1762. }
  1763. }
  1764. void GetPropertyCommand::DoCommand() {
  1765. if (!db_) {
  1766. assert(GetExecuteState().IsFailed());
  1767. return;
  1768. }
  1769. std::map<std::string, std::string> value_map;
  1770. std::string value;
  1771. // Rather than having different ldb command for map properties vs. string
  1772. // properties, we simply try Map property first. (This order only chosen
  1773. // because I prefer the map-style output for
  1774. // "rocksdb.aggregated-table-properties".)
  1775. if (db_->GetMapProperty(GetCfHandle(), property_, &value_map)) {
  1776. if (value_map.empty()) {
  1777. fprintf(stdout, "%s: <empty map>\n", property_.c_str());
  1778. } else {
  1779. for (auto& e : value_map) {
  1780. fprintf(stdout, "%s.%s: %s\n", property_.c_str(), e.first.c_str(),
  1781. e.second.c_str());
  1782. }
  1783. }
  1784. } else if (db_->GetProperty(GetCfHandle(), property_, &value)) {
  1785. fprintf(stdout, "%s: %s\n", property_.c_str(), value.c_str());
  1786. } else {
  1787. exec_state_ =
  1788. LDBCommandExecuteResult::Failed("failed to get property: " + property_);
  1789. }
  1790. }
  1791. // ----------------------------------------------------------------------------
  1792. void ListColumnFamiliesCommand::Help(std::string& ret) {
  1793. ret.append(" ");
  1794. ret.append(ListColumnFamiliesCommand::Name());
  1795. ret.append("\n");
  1796. }
  1797. ListColumnFamiliesCommand::ListColumnFamiliesCommand(
  1798. const std::vector<std::string>& /*params*/,
  1799. const std::map<std::string, std::string>& options,
  1800. const std::vector<std::string>& flags)
  1801. : LDBCommand(options, flags, true /* is_read_only */,
  1802. BuildCmdLineOptions({})) {}
  1803. void ListColumnFamiliesCommand::DoCommand() {
  1804. PrepareOptions();
  1805. std::vector<std::string> column_families;
  1806. Status s = DB::ListColumnFamilies(options_, db_path_, &column_families);
  1807. if (!s.ok()) {
  1808. fprintf(stderr, "Error in processing db %s %s\n", db_path_.c_str(),
  1809. s.ToString().c_str());
  1810. } else {
  1811. fprintf(stdout, "Column families in %s: \n{", db_path_.c_str());
  1812. bool first = true;
  1813. for (const auto& cf : column_families) {
  1814. if (!first) {
  1815. fprintf(stdout, ", ");
  1816. }
  1817. first = false;
  1818. fprintf(stdout, "%s", cf.c_str());
  1819. }
  1820. fprintf(stdout, "}\n");
  1821. }
  1822. }
  1823. void CreateColumnFamilyCommand::Help(std::string& ret) {
  1824. ret.append(" ");
  1825. ret.append(CreateColumnFamilyCommand::Name());
  1826. ret.append(" --db=<db_path> <new_column_family_name>");
  1827. ret.append("\n");
  1828. }
  1829. CreateColumnFamilyCommand::CreateColumnFamilyCommand(
  1830. const std::vector<std::string>& params,
  1831. const std::map<std::string, std::string>& options,
  1832. const std::vector<std::string>& flags)
  1833. : LDBCommand(options, flags, false /* is_read_only */, {ARG_DB}) {
  1834. if (params.size() != 1) {
  1835. exec_state_ = LDBCommandExecuteResult::Failed(
  1836. "new column family name must be specified");
  1837. } else {
  1838. new_cf_name_ = params[0];
  1839. }
  1840. }
  1841. void CreateColumnFamilyCommand::DoCommand() {
  1842. if (!db_) {
  1843. assert(GetExecuteState().IsFailed());
  1844. return;
  1845. }
  1846. ColumnFamilyHandle* new_cf_handle = nullptr;
  1847. Status st = db_->CreateColumnFamily(options_, new_cf_name_, &new_cf_handle);
  1848. if (st.ok()) {
  1849. fprintf(stdout, "OK\n");
  1850. } else {
  1851. exec_state_ = LDBCommandExecuteResult::Failed(
  1852. "Fail to create new column family: " + st.ToString());
  1853. }
  1854. delete new_cf_handle;
  1855. CloseDB();
  1856. }
  1857. void DropColumnFamilyCommand::Help(std::string& ret) {
  1858. ret.append(" ");
  1859. ret.append(DropColumnFamilyCommand::Name());
  1860. ret.append(" --db=<db_path> <column_family_name_to_drop>");
  1861. ret.append("\n");
  1862. }
  1863. DropColumnFamilyCommand::DropColumnFamilyCommand(
  1864. const std::vector<std::string>& params,
  1865. const std::map<std::string, std::string>& options,
  1866. const std::vector<std::string>& flags)
  1867. : LDBCommand(options, flags, false /* is_read_only */, {ARG_DB}) {
  1868. if (params.size() != 1) {
  1869. exec_state_ = LDBCommandExecuteResult::Failed(
  1870. "The name of column family to drop must be specified");
  1871. } else {
  1872. cf_name_to_drop_ = params[0];
  1873. }
  1874. }
  1875. void DropColumnFamilyCommand::DoCommand() {
  1876. if (!db_) {
  1877. assert(GetExecuteState().IsFailed());
  1878. return;
  1879. }
  1880. auto iter = cf_handles_.find(cf_name_to_drop_);
  1881. if (iter == cf_handles_.end()) {
  1882. exec_state_ = LDBCommandExecuteResult::Failed(
  1883. "Column family: " + cf_name_to_drop_ + " doesn't exist in db.");
  1884. return;
  1885. }
  1886. ColumnFamilyHandle* cf_handle_to_drop = iter->second;
  1887. Status st = db_->DropColumnFamily(cf_handle_to_drop);
  1888. if (st.ok()) {
  1889. fprintf(stdout, "OK\n");
  1890. } else {
  1891. exec_state_ = LDBCommandExecuteResult::Failed(
  1892. "Fail to drop column family: " + st.ToString());
  1893. }
  1894. CloseDB();
  1895. }
  1896. // ----------------------------------------------------------------------------
  1897. namespace {
  1898. // This function only called when it's the sane case of >1 buckets in time-range
  1899. // Also called only when timekv falls between ttl_start and ttl_end provided
  1900. void IncBucketCounts(std::vector<uint64_t>& bucket_counts, int ttl_start,
  1901. int time_range, int bucket_size, int timekv,
  1902. int num_buckets) {
  1903. #ifdef NDEBUG
  1904. (void)time_range;
  1905. (void)num_buckets;
  1906. #endif
  1907. assert(time_range > 0 && timekv >= ttl_start && bucket_size > 0 &&
  1908. timekv < (ttl_start + time_range) && num_buckets > 1);
  1909. int bucket = (timekv - ttl_start) / bucket_size;
  1910. bucket_counts[bucket]++;
  1911. }
  1912. void PrintBucketCounts(const std::vector<uint64_t>& bucket_counts,
  1913. int ttl_start, int ttl_end, int bucket_size,
  1914. int num_buckets) {
  1915. int time_point = ttl_start;
  1916. for (int i = 0; i < num_buckets - 1; i++, time_point += bucket_size) {
  1917. fprintf(stdout, "Keys in range %s to %s : %lu\n",
  1918. TimeToHumanString(time_point).c_str(),
  1919. TimeToHumanString(time_point + bucket_size).c_str(),
  1920. (unsigned long)bucket_counts[i]);
  1921. }
  1922. fprintf(stdout, "Keys in range %s to %s : %lu\n",
  1923. TimeToHumanString(time_point).c_str(),
  1924. TimeToHumanString(ttl_end).c_str(),
  1925. (unsigned long)bucket_counts[num_buckets - 1]);
  1926. }
  1927. } // namespace
  1928. const std::string InternalDumpCommand::ARG_COUNT_ONLY = "count_only";
  1929. const std::string InternalDumpCommand::ARG_COUNT_DELIM = "count_delim";
  1930. const std::string InternalDumpCommand::ARG_STATS = "stats";
  1931. const std::string InternalDumpCommand::ARG_INPUT_KEY_HEX = "input_key_hex";
  1932. InternalDumpCommand::InternalDumpCommand(
  1933. const std::vector<std::string>& /*params*/,
  1934. const std::map<std::string, std::string>& options,
  1935. const std::vector<std::string>& flags)
  1936. : LDBCommand(options, flags, true /* is_read_only */,
  1937. BuildCmdLineOptions(
  1938. {ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM, ARG_TO,
  1939. ARG_MAX_KEYS, ARG_COUNT_ONLY, ARG_COUNT_DELIM, ARG_STATS,
  1940. ARG_INPUT_KEY_HEX, ARG_DECODE_BLOB_INDEX})),
  1941. has_from_(false),
  1942. has_to_(false),
  1943. max_keys_(-1),
  1944. delim_("."),
  1945. count_only_(false),
  1946. count_delim_(false),
  1947. print_stats_(false),
  1948. is_input_key_hex_(false),
  1949. decode_blob_index_(false) {
  1950. has_from_ = ParseStringOption(options, ARG_FROM, &from_);
  1951. has_to_ = ParseStringOption(options, ARG_TO, &to_);
  1952. ParseIntOption(options, ARG_MAX_KEYS, max_keys_, exec_state_);
  1953. auto itr = options.find(ARG_COUNT_DELIM);
  1954. if (itr != options.end()) {
  1955. delim_ = itr->second;
  1956. count_delim_ = true;
  1957. // fprintf(stdout,"delim = %c\n",delim_[0]);
  1958. } else {
  1959. count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
  1960. delim_ = ".";
  1961. }
  1962. print_stats_ = IsFlagPresent(flags, ARG_STATS);
  1963. count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);
  1964. is_input_key_hex_ = IsFlagPresent(flags, ARG_INPUT_KEY_HEX);
  1965. decode_blob_index_ = IsFlagPresent(flags, ARG_DECODE_BLOB_INDEX);
  1966. if (is_input_key_hex_) {
  1967. if (has_from_) {
  1968. from_ = HexToString(from_);
  1969. }
  1970. if (has_to_) {
  1971. to_ = HexToString(to_);
  1972. }
  1973. }
  1974. }
  1975. void InternalDumpCommand::Help(std::string& ret) {
  1976. ret.append(" ");
  1977. ret.append(InternalDumpCommand::Name());
  1978. ret.append(HelpRangeCmdArgs());
  1979. ret.append(" [--" + ARG_INPUT_KEY_HEX + "]");
  1980. ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
  1981. ret.append(" [--" + ARG_COUNT_ONLY + "]");
  1982. ret.append(" [--" + ARG_COUNT_DELIM + "=<char>]");
  1983. ret.append(" [--" + ARG_STATS + "]");
  1984. ret.append(" [--" + ARG_DECODE_BLOB_INDEX + "]");
  1985. ret.append("\n");
  1986. }
  1987. void InternalDumpCommand::DoCommand() {
  1988. if (!db_) {
  1989. assert(GetExecuteState().IsFailed());
  1990. return;
  1991. }
  1992. ColumnFamilyHandle* cfh = GetCfHandle();
  1993. const Comparator* ucmp = cfh->GetComparator();
  1994. size_t ts_sz = ucmp->timestamp_size();
  1995. if (print_stats_) {
  1996. std::string stats;
  1997. if (db_->GetProperty(cfh, "rocksdb.stats", &stats)) {
  1998. fprintf(stdout, "%s\n", stats.c_str());
  1999. }
  2000. }
  2001. // Cast as DBImpl to get internal iterator
  2002. std::vector<KeyVersion> key_versions;
  2003. Status st =
  2004. GetAllKeyVersions(db_, GetCfHandle(), has_from_ ? from_ : OptSlice{},
  2005. has_to_ ? to_ : OptSlice{}, max_keys_, &key_versions);
  2006. if (!st.ok()) {
  2007. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  2008. return;
  2009. }
  2010. std::string rtype1, rtype2, row, val;
  2011. rtype2 = "";
  2012. uint64_t c = 0;
  2013. uint64_t s1 = 0, s2 = 0;
  2014. long long count = 0;
  2015. for (auto& key_version : key_versions) {
  2016. ValueType value_type = static_cast<ValueType>(key_version.type);
  2017. InternalKey ikey(key_version.user_key, key_version.sequence, value_type);
  2018. Slice user_key_without_ts = ikey.user_key();
  2019. if (ts_sz > 0) {
  2020. user_key_without_ts.remove_suffix(ts_sz);
  2021. }
  2022. if (has_to_ && ucmp->Compare(user_key_without_ts, to_) == 0) {
  2023. // GetAllKeyVersions() includes keys with user key `to_`, but idump has
  2024. // traditionally excluded such keys.
  2025. break;
  2026. }
  2027. ++count;
  2028. int k;
  2029. if (count_delim_) {
  2030. rtype1 = "";
  2031. s1 = 0;
  2032. row = ikey.Encode().ToString();
  2033. val = key_version.value;
  2034. for (k = 0; row[k] != '\x01' && row[k] != '\0'; k++) {
  2035. s1++;
  2036. }
  2037. for (k = 0; val[k] != '\x01' && val[k] != '\0'; k++) {
  2038. s1++;
  2039. }
  2040. for (int j = 0; row[j] != delim_[0] && row[j] != '\0' && row[j] != '\x01';
  2041. j++) {
  2042. rtype1 += row[j];
  2043. }
  2044. if (rtype2.compare("") && rtype2.compare(rtype1) != 0) {
  2045. fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
  2046. rtype2.c_str(), c, s2);
  2047. c = 1;
  2048. s2 = s1;
  2049. rtype2 = rtype1;
  2050. } else {
  2051. c++;
  2052. s2 += s1;
  2053. rtype2 = rtype1;
  2054. }
  2055. }
  2056. if (!count_only_ && !count_delim_) {
  2057. std::string key = ikey.DebugString(is_key_hex_, ucmp);
  2058. Slice value(key_version.value);
  2059. if (!decode_blob_index_ || value_type != kTypeBlobIndex) {
  2060. if (value_type == kTypeWideColumnEntity) {
  2061. std::ostringstream oss;
  2062. const Status s = WideColumnsHelper::DumpSliceAsWideColumns(
  2063. value, oss, is_value_hex_);
  2064. if (!s.ok()) {
  2065. fprintf(stderr, "%s => error deserializing wide columns\n",
  2066. key.c_str());
  2067. } else {
  2068. fprintf(stdout, "%s => %s\n", key.c_str(), oss.str().c_str());
  2069. }
  2070. } else {
  2071. fprintf(stdout, "%s => %s\n", key.c_str(),
  2072. value.ToString(is_value_hex_).c_str());
  2073. }
  2074. } else {
  2075. BlobIndex blob_index;
  2076. const Status s = blob_index.DecodeFrom(value);
  2077. if (!s.ok()) {
  2078. fprintf(stderr, "%s => error decoding blob index =>\n", key.c_str());
  2079. } else {
  2080. fprintf(stdout, "%s => %s\n", key.c_str(),
  2081. blob_index.DebugString(is_value_hex_).c_str());
  2082. }
  2083. }
  2084. }
  2085. // Terminate if maximum number of keys have been dumped
  2086. if (max_keys_ > 0 && count >= max_keys_) {
  2087. break;
  2088. }
  2089. }
  2090. if (count_delim_) {
  2091. fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
  2092. rtype2.c_str(), c, s2);
  2093. } else {
  2094. fprintf(stdout, "Internal keys in range: %lld\n", count);
  2095. }
  2096. }
  2097. const std::string DBDumperCommand::ARG_COUNT_ONLY = "count_only";
  2098. const std::string DBDumperCommand::ARG_COUNT_DELIM = "count_delim";
  2099. const std::string DBDumperCommand::ARG_STATS = "stats";
  2100. const std::string DBDumperCommand::ARG_TTL_BUCKET = "bucket";
  2101. DBDumperCommand::DBDumperCommand(
  2102. const std::vector<std::string>& /*params*/,
  2103. const std::map<std::string, std::string>& options,
  2104. const std::vector<std::string>& flags)
  2105. : LDBCommand(
  2106. options, flags, true /* is_read_only */,
  2107. BuildCmdLineOptions(
  2108. {ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM, ARG_TO,
  2109. ARG_MAX_KEYS, ARG_COUNT_ONLY, ARG_COUNT_DELIM, ARG_STATS,
  2110. ARG_TTL_START, ARG_TTL_END, ARG_TTL_BUCKET, ARG_TIMESTAMP,
  2111. ARG_PATH, ARG_DECODE_BLOB_INDEX, ARG_DUMP_UNCOMPRESSED_BLOBS})),
  2112. null_from_(true),
  2113. null_to_(true),
  2114. max_keys_(-1),
  2115. count_only_(false),
  2116. count_delim_(false),
  2117. print_stats_(false),
  2118. decode_blob_index_(false) {
  2119. auto itr = options.find(ARG_FROM);
  2120. if (itr != options.end()) {
  2121. null_from_ = false;
  2122. from_ = itr->second;
  2123. }
  2124. itr = options.find(ARG_TO);
  2125. if (itr != options.end()) {
  2126. null_to_ = false;
  2127. to_ = itr->second;
  2128. }
  2129. itr = options.find(ARG_MAX_KEYS);
  2130. if (itr != options.end()) {
  2131. try {
  2132. #if defined(CYGWIN)
  2133. max_keys_ = strtol(itr->second.c_str(), 0, 10);
  2134. #else
  2135. max_keys_ = std::stoi(itr->second);
  2136. #endif
  2137. } catch (const std::invalid_argument&) {
  2138. exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
  2139. " has an invalid value");
  2140. } catch (const std::out_of_range&) {
  2141. exec_state_ = LDBCommandExecuteResult::Failed(
  2142. ARG_MAX_KEYS + " has a value out-of-range");
  2143. }
  2144. }
  2145. itr = options.find(ARG_COUNT_DELIM);
  2146. if (itr != options.end()) {
  2147. delim_ = itr->second;
  2148. count_delim_ = true;
  2149. } else {
  2150. count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
  2151. delim_ = ".";
  2152. }
  2153. print_stats_ = IsFlagPresent(flags, ARG_STATS);
  2154. count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);
  2155. decode_blob_index_ = IsFlagPresent(flags, ARG_DECODE_BLOB_INDEX);
  2156. dump_uncompressed_blobs_ = IsFlagPresent(flags, ARG_DUMP_UNCOMPRESSED_BLOBS);
  2157. if (is_key_hex_) {
  2158. if (!null_from_) {
  2159. from_ = HexToString(from_);
  2160. }
  2161. if (!null_to_) {
  2162. to_ = HexToString(to_);
  2163. }
  2164. }
  2165. itr = options.find(ARG_PATH);
  2166. if (itr != options.end()) {
  2167. path_ = itr->second;
  2168. if (db_path_.empty()) {
  2169. db_path_ = path_;
  2170. }
  2171. }
  2172. }
  2173. void DBDumperCommand::Help(std::string& ret) {
  2174. ret.append(" ");
  2175. ret.append(DBDumperCommand::Name());
  2176. ret.append(HelpRangeCmdArgs());
  2177. ret.append(" [--" + ARG_TTL + "]");
  2178. ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
  2179. ret.append(" [--" + ARG_TIMESTAMP + "]");
  2180. ret.append(" [--" + ARG_COUNT_ONLY + "]");
  2181. ret.append(" [--" + ARG_COUNT_DELIM + "=<char>]");
  2182. ret.append(" [--" + ARG_STATS + "]");
  2183. ret.append(" [--" + ARG_TTL_BUCKET + "=<N>]");
  2184. ret.append(" [--" + ARG_TTL_START + "=<N>:- is inclusive]");
  2185. ret.append(" [--" + ARG_TTL_END + "=<N>:- is exclusive]");
  2186. ret.append(" [--" + ARG_PATH + "=<path_to_a_file>]");
  2187. ret.append(" [--" + ARG_DECODE_BLOB_INDEX + "]");
  2188. ret.append(" [--" + ARG_DUMP_UNCOMPRESSED_BLOBS + "]");
  2189. ret.append("\n");
  2190. }
  2191. /**
  2192. * Handles two separate cases:
  2193. *
  2194. * 1) --db is specified - just dump the database.
  2195. *
  2196. * 2) --path is specified - determine based on file extension what dumping
  2197. * function to call. Please note that we intentionally use the extension
  2198. * and avoid probing the file contents under the assumption that renaming
  2199. * the files is not a supported scenario.
  2200. *
  2201. */
  2202. void DBDumperCommand::DoCommand() {
  2203. if (!db_) {
  2204. assert(!path_.empty());
  2205. std::string fileName = GetFileNameFromPath(path_);
  2206. uint64_t number;
  2207. FileType type;
  2208. exec_state_ = LDBCommandExecuteResult::Succeed("");
  2209. if (!ParseFileName(fileName, &number, &type)) {
  2210. exec_state_ =
  2211. LDBCommandExecuteResult::Failed("Can't parse file type: " + path_);
  2212. return;
  2213. }
  2214. switch (type) {
  2215. case kWalFile:
  2216. // TODO(myabandeh): allow configuring is_write_commited
  2217. DumpWalFiles(options_, path_, /* print_header_ */ true,
  2218. /* print_values_ */ true,
  2219. /* only_print_seqno_gaps */ false,
  2220. true /* is_write_commited */, ucmps_, &exec_state_);
  2221. break;
  2222. case kTableFile:
  2223. DumpSstFile(options_, path_, is_key_hex_, /* show_properties */ true,
  2224. decode_blob_index_, from_, to_);
  2225. break;
  2226. case kDescriptorFile:
  2227. DumpManifestFile(options_, path_, /* verbose_ */ false, is_key_hex_,
  2228. /* json_ */ false, column_families_);
  2229. break;
  2230. case kBlobFile:
  2231. DumpBlobFile(path_, is_key_hex_, is_value_hex_,
  2232. dump_uncompressed_blobs_);
  2233. break;
  2234. default:
  2235. exec_state_ = LDBCommandExecuteResult::Failed(
  2236. "File type not supported: " + path_);
  2237. break;
  2238. }
  2239. } else {
  2240. DoDumpCommand();
  2241. }
  2242. }
  2243. void DBDumperCommand::DoDumpCommand() {
  2244. assert(nullptr != db_);
  2245. assert(path_.empty());
  2246. // Parse command line args
  2247. uint64_t count = 0;
  2248. if (print_stats_) {
  2249. std::string stats;
  2250. if (db_->GetProperty("rocksdb.stats", &stats)) {
  2251. fprintf(stdout, "%s\n", stats.c_str());
  2252. }
  2253. }
  2254. // Setup key iterator
  2255. ReadOptions scan_read_opts;
  2256. Slice read_timestamp;
  2257. ColumnFamilyHandle* cfh = GetCfHandle();
  2258. const Comparator* ucmp = cfh->GetComparator();
  2259. size_t ts_sz = ucmp->timestamp_size();
  2260. if (ucmp->timestamp_size() > 0) {
  2261. read_timestamp = ucmp->GetMaxTimestamp();
  2262. scan_read_opts.timestamp = &read_timestamp;
  2263. }
  2264. scan_read_opts.total_order_seek = true;
  2265. Iterator* iter = db_->NewIterator(scan_read_opts, cfh);
  2266. Status st = iter->status();
  2267. if (!st.ok()) {
  2268. exec_state_ =
  2269. LDBCommandExecuteResult::Failed("Iterator error." + st.ToString());
  2270. }
  2271. if (!null_from_) {
  2272. iter->Seek(from_);
  2273. } else {
  2274. iter->SeekToFirst();
  2275. }
  2276. int max_keys = max_keys_;
  2277. int ttl_start;
  2278. if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
  2279. ttl_start = DBWithTTLImpl::kMinTimestamp; // TTL introduction time
  2280. }
  2281. int ttl_end;
  2282. if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
  2283. ttl_end = DBWithTTLImpl::kMaxTimestamp; // Max time allowed by TTL feature
  2284. }
  2285. if (ttl_end < ttl_start) {
  2286. fprintf(stderr, "Error: End time can't be less than start time\n");
  2287. delete iter;
  2288. return;
  2289. }
  2290. int time_range = ttl_end - ttl_start;
  2291. int bucket_size;
  2292. if (!ParseIntOption(option_map_, ARG_TTL_BUCKET, bucket_size, exec_state_) ||
  2293. bucket_size <= 0) {
  2294. bucket_size = time_range; // Will have just 1 bucket by default
  2295. }
  2296. // cretaing variables for row count of each type
  2297. std::string rtype1, rtype2, row, val;
  2298. rtype2 = "";
  2299. uint64_t c = 0;
  2300. uint64_t s1 = 0, s2 = 0;
  2301. // At this point, bucket_size=0 => time_range=0
  2302. int num_buckets = (bucket_size >= time_range)
  2303. ? 1
  2304. : ((time_range + bucket_size - 1) / bucket_size);
  2305. std::vector<uint64_t> bucket_counts(num_buckets, 0);
  2306. if (is_db_ttl_ && !count_only_ && timestamp_ && !count_delim_) {
  2307. fprintf(stdout, "Dumping key-values from %s to %s\n",
  2308. TimeToHumanString(ttl_start).c_str(),
  2309. TimeToHumanString(ttl_end).c_str());
  2310. }
  2311. HistogramImpl vsize_hist;
  2312. for (; iter->Valid(); iter->Next()) {
  2313. int rawtime = 0;
  2314. // If end marker was specified, we stop before it
  2315. if (!null_to_ && ucmp->Compare(iter->key(), to_) >= 0) {
  2316. break;
  2317. }
  2318. // Terminate if maximum number of keys have been dumped
  2319. if (max_keys == 0) {
  2320. break;
  2321. }
  2322. if (is_db_ttl_) {
  2323. TtlIterator* it_ttl = static_cast_with_check<TtlIterator>(iter);
  2324. rawtime = it_ttl->ttl_timestamp();
  2325. if (rawtime < ttl_start || rawtime >= ttl_end) {
  2326. continue;
  2327. }
  2328. }
  2329. if (max_keys > 0) {
  2330. --max_keys;
  2331. }
  2332. if (is_db_ttl_ && num_buckets > 1) {
  2333. IncBucketCounts(bucket_counts, ttl_start, time_range, bucket_size,
  2334. rawtime, num_buckets);
  2335. }
  2336. ++count;
  2337. if (count_delim_) {
  2338. rtype1 = "";
  2339. row = iter->key().ToString();
  2340. val = iter->value().ToString();
  2341. s1 = row.size() + val.size();
  2342. for (int j = 0; row[j] != delim_[0] && row[j] != '\0'; j++) {
  2343. rtype1 += row[j];
  2344. }
  2345. if (rtype2.compare("") && rtype2.compare(rtype1) != 0) {
  2346. fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
  2347. rtype2.c_str(), c, s2);
  2348. c = 1;
  2349. s2 = s1;
  2350. rtype2 = rtype1;
  2351. } else {
  2352. c++;
  2353. s2 += s1;
  2354. rtype2 = rtype1;
  2355. }
  2356. }
  2357. if (count_only_) {
  2358. vsize_hist.Add(iter->value().size());
  2359. }
  2360. if (!count_only_ && !count_delim_) {
  2361. if (is_db_ttl_ && timestamp_) {
  2362. fprintf(stdout, "%s ", TimeToHumanString(rawtime).c_str());
  2363. }
  2364. // (TODO) TTL Iterator does not support wide columns yet.
  2365. std::string str =
  2366. is_db_ttl_
  2367. ? PrintKeyValue(iter->key().ToString(),
  2368. ts_sz == 0 ? "" : iter->timestamp().ToString(),
  2369. iter->value().ToString(), is_key_hex_,
  2370. is_value_hex_, ucmp)
  2371. : PrintKeyValueOrWideColumns(
  2372. iter->key(), ts_sz == 0 ? "" : iter->timestamp().ToString(),
  2373. iter->value(), iter->columns(), is_key_hex_, is_value_hex_,
  2374. ucmp);
  2375. fprintf(stdout, "%s\n", str.c_str());
  2376. }
  2377. }
  2378. if (num_buckets > 1 && is_db_ttl_) {
  2379. PrintBucketCounts(bucket_counts, ttl_start, ttl_end, bucket_size,
  2380. num_buckets);
  2381. } else if (count_delim_) {
  2382. fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
  2383. rtype2.c_str(), c, s2);
  2384. } else {
  2385. fprintf(stdout, "Keys in range: %" PRIu64 "\n", count);
  2386. }
  2387. if (count_only_) {
  2388. fprintf(stdout, "Value size distribution: \n");
  2389. fprintf(stdout, "%s\n", vsize_hist.ToString().c_str());
  2390. }
  2391. // Clean up
  2392. delete iter;
  2393. }
  2394. const std::string ReduceDBLevelsCommand::ARG_NEW_LEVELS = "new_levels";
  2395. const std::string ReduceDBLevelsCommand::ARG_PRINT_OLD_LEVELS =
  2396. "print_old_levels";
  2397. ReduceDBLevelsCommand::ReduceDBLevelsCommand(
  2398. const std::vector<std::string>& /*params*/,
  2399. const std::map<std::string, std::string>& options,
  2400. const std::vector<std::string>& flags)
  2401. : LDBCommand(options, flags, false /* is_read_only */,
  2402. BuildCmdLineOptions({ARG_NEW_LEVELS, ARG_PRINT_OLD_LEVELS})),
  2403. old_levels_(1 << 7),
  2404. new_levels_(-1),
  2405. print_old_levels_(false) {
  2406. ParseIntOption(option_map_, ARG_NEW_LEVELS, new_levels_, exec_state_);
  2407. print_old_levels_ = IsFlagPresent(flags, ARG_PRINT_OLD_LEVELS);
  2408. if (new_levels_ <= 0) {
  2409. exec_state_ = LDBCommandExecuteResult::Failed(
  2410. " Use --" + ARG_NEW_LEVELS + " to specify a new level number\n");
  2411. }
  2412. }
  2413. std::vector<std::string> ReduceDBLevelsCommand::PrepareArgs(
  2414. const std::string& db_path, int new_levels, bool print_old_level) {
  2415. std::vector<std::string> ret;
  2416. ret.emplace_back("reduce_levels");
  2417. ret.push_back("--" + ARG_DB + "=" + db_path);
  2418. ret.push_back("--" + ARG_NEW_LEVELS + "=" + std::to_string(new_levels));
  2419. if (print_old_level) {
  2420. ret.push_back("--" + ARG_PRINT_OLD_LEVELS);
  2421. }
  2422. return ret;
  2423. }
  2424. void ReduceDBLevelsCommand::Help(std::string& ret) {
  2425. ret.append(" ");
  2426. ret.append(ReduceDBLevelsCommand::Name());
  2427. ret.append(" --" + ARG_NEW_LEVELS + "=<New number of levels>");
  2428. ret.append(" [--" + ARG_PRINT_OLD_LEVELS + "]");
  2429. ret.append("\n");
  2430. }
  2431. void ReduceDBLevelsCommand::OverrideBaseCFOptions(
  2432. ColumnFamilyOptions* cf_opts) {
  2433. LDBCommand::OverrideBaseCFOptions(cf_opts);
  2434. cf_opts->num_levels = old_levels_;
  2435. cf_opts->max_bytes_for_level_multiplier_additional.resize(cf_opts->num_levels,
  2436. 1);
  2437. // Disable size compaction
  2438. cf_opts->max_bytes_for_level_base = 1ULL << 50;
  2439. cf_opts->max_bytes_for_level_multiplier = 1;
  2440. }
  2441. Status ReduceDBLevelsCommand::GetOldNumOfLevels(Options& opt, int* levels) {
  2442. ImmutableDBOptions db_options(opt);
  2443. EnvOptions soptions;
  2444. std::shared_ptr<Cache> tc(
  2445. NewLRUCache(opt.max_open_files - 10, opt.table_cache_numshardbits));
  2446. const InternalKeyComparator cmp(opt.comparator);
  2447. WriteController wc(opt.delayed_write_rate);
  2448. WriteBufferManager wb(opt.db_write_buffer_size);
  2449. VersionSet versions(db_path_, &db_options, soptions, tc.get(), &wb, &wc,
  2450. /*block_cache_tracer=*/nullptr, /*io_tracer=*/nullptr,
  2451. /*db_id=*/"", /*db_session_id=*/"",
  2452. opt.daily_offpeak_time_utc,
  2453. /*error_handler=*/nullptr, /*unchanging=*/false);
  2454. std::vector<ColumnFamilyDescriptor> dummy;
  2455. ColumnFamilyDescriptor dummy_descriptor(kDefaultColumnFamilyName,
  2456. ColumnFamilyOptions(opt));
  2457. dummy.push_back(dummy_descriptor);
  2458. // We rely the VersionSet::Recover to tell us the internal data structures
  2459. // in the db. And the Recover() should never do any change
  2460. // (like LogAndApply) to the manifest file.
  2461. Status st = versions.Recover(dummy);
  2462. if (!st.ok()) {
  2463. return st;
  2464. }
  2465. int max = -1;
  2466. auto default_cfd = versions.GetColumnFamilySet()->GetDefault();
  2467. for (int i = 0; i < default_cfd->NumberLevels(); i++) {
  2468. if (default_cfd->current()->storage_info()->NumLevelFiles(i)) {
  2469. max = i;
  2470. }
  2471. }
  2472. *levels = max + 1;
  2473. return st;
  2474. }
  2475. void ReduceDBLevelsCommand::DoCommand() {
  2476. if (new_levels_ <= 1) {
  2477. exec_state_ =
  2478. LDBCommandExecuteResult::Failed("Invalid number of levels.\n");
  2479. return;
  2480. }
  2481. Status st;
  2482. PrepareOptions();
  2483. int old_level_num = -1;
  2484. st = GetOldNumOfLevels(options_, &old_level_num);
  2485. if (!st.ok()) {
  2486. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  2487. return;
  2488. }
  2489. if (print_old_levels_) {
  2490. fprintf(stdout, "The old number of levels in use is %d\n", old_level_num);
  2491. }
  2492. if (old_level_num <= new_levels_) {
  2493. return;
  2494. }
  2495. old_levels_ = old_level_num;
  2496. OpenDB();
  2497. if (exec_state_.IsFailed()) {
  2498. return;
  2499. }
  2500. assert(db_ != nullptr);
  2501. // Compact the whole DB to put all files to the highest level.
  2502. fprintf(stdout, "Compacting the db...\n");
  2503. st =
  2504. db_->CompactRange(CompactRangeOptions(), GetCfHandle(), nullptr, nullptr);
  2505. CloseDB();
  2506. if (st.ok()) {
  2507. EnvOptions soptions;
  2508. st = VersionSet::ReduceNumberOfLevels(db_path_, &options_, soptions,
  2509. new_levels_);
  2510. }
  2511. if (!st.ok()) {
  2512. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  2513. return;
  2514. }
  2515. }
  2516. const std::string ChangeCompactionStyleCommand::ARG_OLD_COMPACTION_STYLE =
  2517. "old_compaction_style";
  2518. const std::string ChangeCompactionStyleCommand::ARG_NEW_COMPACTION_STYLE =
  2519. "new_compaction_style";
  2520. ChangeCompactionStyleCommand::ChangeCompactionStyleCommand(
  2521. const std::vector<std::string>& /*params*/,
  2522. const std::map<std::string, std::string>& options,
  2523. const std::vector<std::string>& flags)
  2524. : LDBCommand(options, flags, false /* is_read_only */,
  2525. BuildCmdLineOptions(
  2526. {ARG_OLD_COMPACTION_STYLE, ARG_NEW_COMPACTION_STYLE})),
  2527. old_compaction_style_(-1),
  2528. new_compaction_style_(-1) {
  2529. ParseIntOption(option_map_, ARG_OLD_COMPACTION_STYLE, old_compaction_style_,
  2530. exec_state_);
  2531. if (old_compaction_style_ != kCompactionStyleLevel &&
  2532. old_compaction_style_ != kCompactionStyleUniversal) {
  2533. exec_state_ = LDBCommandExecuteResult::Failed(
  2534. "Use --" + ARG_OLD_COMPACTION_STYLE + " to specify old compaction " +
  2535. "style. Check ldb help for proper compaction style value.\n");
  2536. return;
  2537. }
  2538. ParseIntOption(option_map_, ARG_NEW_COMPACTION_STYLE, new_compaction_style_,
  2539. exec_state_);
  2540. if (new_compaction_style_ != kCompactionStyleLevel &&
  2541. new_compaction_style_ != kCompactionStyleUniversal) {
  2542. exec_state_ = LDBCommandExecuteResult::Failed(
  2543. "Use --" + ARG_NEW_COMPACTION_STYLE + " to specify new compaction " +
  2544. "style. Check ldb help for proper compaction style value.\n");
  2545. return;
  2546. }
  2547. if (new_compaction_style_ == old_compaction_style_) {
  2548. exec_state_ = LDBCommandExecuteResult::Failed(
  2549. "Old compaction style is the same as new compaction style. "
  2550. "Nothing to do.\n");
  2551. return;
  2552. }
  2553. if (old_compaction_style_ == kCompactionStyleUniversal &&
  2554. new_compaction_style_ == kCompactionStyleLevel) {
  2555. exec_state_ = LDBCommandExecuteResult::Failed(
  2556. "Convert from universal compaction to level compaction. "
  2557. "Nothing to do.\n");
  2558. return;
  2559. }
  2560. }
  2561. void ChangeCompactionStyleCommand::Help(std::string& ret) {
  2562. ret.append(" ");
  2563. ret.append(ChangeCompactionStyleCommand::Name());
  2564. ret.append(" --" + ARG_OLD_COMPACTION_STYLE + "=<Old compaction style: 0 " +
  2565. "for level compaction, 1 for universal compaction>");
  2566. ret.append(" --" + ARG_NEW_COMPACTION_STYLE + "=<New compaction style: 0 " +
  2567. "for level compaction, 1 for universal compaction>");
  2568. ret.append("\n");
  2569. }
  2570. void ChangeCompactionStyleCommand::OverrideBaseCFOptions(
  2571. ColumnFamilyOptions* cf_opts) {
  2572. LDBCommand::OverrideBaseCFOptions(cf_opts);
  2573. if (old_compaction_style_ == kCompactionStyleLevel &&
  2574. new_compaction_style_ == kCompactionStyleUniversal) {
  2575. // In order to convert from level compaction to universal compaction, we
  2576. // need to compact all data into a single file and move it to level 0.
  2577. cf_opts->disable_auto_compactions = true;
  2578. cf_opts->target_file_size_base = INT_MAX;
  2579. cf_opts->target_file_size_multiplier = 1;
  2580. cf_opts->max_bytes_for_level_base = INT_MAX;
  2581. cf_opts->max_bytes_for_level_multiplier = 1;
  2582. }
  2583. }
  2584. void ChangeCompactionStyleCommand::DoCommand() {
  2585. if (!db_) {
  2586. assert(GetExecuteState().IsFailed());
  2587. return;
  2588. }
  2589. // print db stats before we have made any change
  2590. std::string property;
  2591. std::string files_per_level;
  2592. for (int i = 0; i < db_->NumberLevels(GetCfHandle()); i++) {
  2593. db_->GetProperty(GetCfHandle(),
  2594. "rocksdb.num-files-at-level" + std::to_string(i),
  2595. &property);
  2596. // format print string
  2597. char buf[100];
  2598. snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
  2599. files_per_level += buf;
  2600. }
  2601. fprintf(stdout, "files per level before compaction: %s\n",
  2602. files_per_level.c_str());
  2603. // manual compact into a single file and move the file to level 0
  2604. CompactRangeOptions compact_options;
  2605. compact_options.change_level = true;
  2606. compact_options.target_level = 0;
  2607. Status s =
  2608. db_->CompactRange(compact_options, GetCfHandle(), nullptr, nullptr);
  2609. if (!s.ok()) {
  2610. std::stringstream oss;
  2611. oss << "Compaction failed: " << s.ToString();
  2612. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  2613. return;
  2614. }
  2615. // verify compaction result
  2616. files_per_level = "";
  2617. int num_files = 0;
  2618. for (int i = 0; i < db_->NumberLevels(GetCfHandle()); i++) {
  2619. db_->GetProperty(GetCfHandle(),
  2620. "rocksdb.num-files-at-level" + std::to_string(i),
  2621. &property);
  2622. // format print string
  2623. char buf[100];
  2624. snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
  2625. files_per_level += buf;
  2626. num_files = atoi(property.c_str());
  2627. // level 0 should have only 1 file
  2628. if (i == 0 && num_files != 1) {
  2629. exec_state_ = LDBCommandExecuteResult::Failed(
  2630. "Number of db files at "
  2631. "level 0 after compaction is " +
  2632. std::to_string(num_files) + ", not 1.\n");
  2633. return;
  2634. }
  2635. // other levels should have no file
  2636. if (i > 0 && num_files != 0) {
  2637. exec_state_ = LDBCommandExecuteResult::Failed(
  2638. "Number of db files at "
  2639. "level " +
  2640. std::to_string(i) + " after compaction is " +
  2641. std::to_string(num_files) + ", not 0.\n");
  2642. return;
  2643. }
  2644. }
  2645. fprintf(stdout, "files per level after compaction: %s\n",
  2646. files_per_level.c_str());
  2647. }
  2648. // ----------------------------------------------------------------------------
  2649. namespace {
  2650. struct StdErrReporter : public log::Reader::Reporter {
  2651. void Corruption(size_t /*bytes*/, const Status& s,
  2652. uint64_t /*log_number*/ = kMaxSequenceNumber) override {
  2653. std::cerr << "Corruption detected in log file " << s.ToString() << "\n";
  2654. }
  2655. };
  2656. class InMemoryHandler : public WriteBatch::Handler {
  2657. public:
  2658. InMemoryHandler(std::stringstream& row, bool print_values,
  2659. bool write_after_commit,
  2660. const std::map<uint32_t, const Comparator*>& ucmps)
  2661. : Handler(),
  2662. row_(row),
  2663. print_values_(print_values),
  2664. write_after_commit_(write_after_commit),
  2665. ucmps_(ucmps) {}
  2666. void commonPutMerge(uint32_t cf, const Slice& key, const Slice& value) {
  2667. std::string k = PrintKey(cf, key);
  2668. if (print_values_) {
  2669. std::string v = LDBCommand::StringToHex(value.ToString());
  2670. row_ << k << " : ";
  2671. row_ << v << " ";
  2672. } else {
  2673. row_ << k << " ";
  2674. }
  2675. }
  2676. Status PutCF(uint32_t cf, const Slice& key, const Slice& value) override {
  2677. row_ << "PUT(" << cf << ") : ";
  2678. commonPutMerge(cf, key, value);
  2679. return Status::OK();
  2680. }
  2681. Status PutEntityCF(uint32_t cf, const Slice& key,
  2682. const Slice& value) override {
  2683. row_ << "PUT_ENTITY(" << cf << ") : " << PrintKey(cf, key);
  2684. if (print_values_) {
  2685. row_ << " : ";
  2686. const Status s =
  2687. WideColumnsHelper::DumpSliceAsWideColumns(value, row_, true);
  2688. if (!s.ok()) {
  2689. return s;
  2690. }
  2691. }
  2692. row_ << ' ';
  2693. return Status::OK();
  2694. }
  2695. Status MergeCF(uint32_t cf, const Slice& key, const Slice& value) override {
  2696. row_ << "MERGE(" << cf << ") : ";
  2697. commonPutMerge(cf, key, value);
  2698. return Status::OK();
  2699. }
  2700. Status MarkNoop(bool) override {
  2701. row_ << "NOOP ";
  2702. return Status::OK();
  2703. }
  2704. Status DeleteCF(uint32_t cf, const Slice& key) override {
  2705. row_ << "DELETE(" << cf << ") : ";
  2706. row_ << PrintKey(cf, key) << " ";
  2707. return Status::OK();
  2708. }
  2709. Status SingleDeleteCF(uint32_t cf, const Slice& key) override {
  2710. row_ << "SINGLE_DELETE(" << cf << ") : ";
  2711. row_ << PrintKey(cf, key) << " ";
  2712. return Status::OK();
  2713. }
  2714. Status DeleteRangeCF(uint32_t cf, const Slice& begin_key,
  2715. const Slice& end_key) override {
  2716. row_ << "DELETE_RANGE(" << cf << ") : ";
  2717. row_ << PrintKey(cf, begin_key) << " ";
  2718. row_ << PrintKey(cf, end_key) << " ";
  2719. return Status::OK();
  2720. }
  2721. Status MarkBeginPrepare(bool unprepare) override {
  2722. row_ << "BEGIN_PREPARE(";
  2723. row_ << (unprepare ? "true" : "false") << ") ";
  2724. return Status::OK();
  2725. }
  2726. Status MarkEndPrepare(const Slice& xid) override {
  2727. row_ << "END_PREPARE(";
  2728. row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
  2729. return Status::OK();
  2730. }
  2731. Status MarkRollback(const Slice& xid) override {
  2732. row_ << "ROLLBACK(";
  2733. row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
  2734. return Status::OK();
  2735. }
  2736. Status MarkCommit(const Slice& xid) override {
  2737. row_ << "COMMIT(";
  2738. row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
  2739. return Status::OK();
  2740. }
  2741. Status MarkCommitWithTimestamp(const Slice& xid,
  2742. const Slice& commit_ts) override {
  2743. row_ << "COMMIT_WITH_TIMESTAMP(";
  2744. row_ << LDBCommand::StringToHex(xid.ToString()) << ", ";
  2745. row_ << LDBCommand::StringToHex(commit_ts.ToString()) << ") ";
  2746. return Status::OK();
  2747. }
  2748. ~InMemoryHandler() override = default;
  2749. protected:
  2750. Handler::OptionState WriteAfterCommit() const override {
  2751. return write_after_commit_ ? Handler::OptionState::kEnabled
  2752. : Handler::OptionState::kDisabled;
  2753. }
  2754. private:
  2755. std::string PrintKey(uint32_t cf, const Slice& key) {
  2756. auto ucmp_iter = ucmps_.find(cf);
  2757. if (ucmp_iter == ucmps_.end()) {
  2758. // Fallback to default print slice as hex
  2759. return LDBCommand::StringToHex(key.ToString());
  2760. }
  2761. size_t ts_sz = ucmp_iter->second->timestamp_size();
  2762. if (ts_sz == 0) {
  2763. return LDBCommand::StringToHex(key.ToString());
  2764. } else {
  2765. // This could happen if there is corruption or undetected comparator
  2766. // change.
  2767. if (key.size() < ts_sz) {
  2768. return "CORRUPT KEY";
  2769. }
  2770. Slice user_key_without_ts = key;
  2771. user_key_without_ts.remove_suffix(ts_sz);
  2772. Slice ts = Slice(key.data() + key.size() - ts_sz, ts_sz);
  2773. return LDBCommand::StringToHex(user_key_without_ts.ToString()) +
  2774. "|timestamp:" + ucmp_iter->second->TimestampToString(ts);
  2775. }
  2776. }
  2777. std::stringstream& row_;
  2778. bool print_values_;
  2779. bool write_after_commit_;
  2780. const std::map<uint32_t, const Comparator*> ucmps_;
  2781. };
  2782. void DumpWalFiles(Options options, const std::string& dir_or_file,
  2783. bool print_header, bool print_values,
  2784. bool only_print_seqno_gaps, bool is_write_committed,
  2785. const std::map<uint32_t, const Comparator*>& ucmps,
  2786. LDBCommandExecuteResult* exec_state) {
  2787. std::vector<std::string> filenames;
  2788. ROCKSDB_NAMESPACE::Env* env = options.env;
  2789. ROCKSDB_NAMESPACE::Status st = env->GetChildren(dir_or_file, &filenames);
  2790. std::optional<SequenceNumber> prev_batch_seqno;
  2791. std::optional<uint32_t> prev_batch_count;
  2792. if (!st.ok() || filenames.empty()) {
  2793. // dir_or_file does not exist or does not contain children
  2794. // Check its existence first
  2795. Status s = env->FileExists(dir_or_file);
  2796. // dir_or_file does not exist
  2797. if (!s.ok()) {
  2798. if (exec_state) {
  2799. *exec_state = LDBCommandExecuteResult::Failed(
  2800. dir_or_file + ": No such file or directory");
  2801. }
  2802. return;
  2803. }
  2804. // If it exists and doesn't have children, it should be a log file.
  2805. if (dir_or_file.length() <= 4 ||
  2806. dir_or_file.rfind(".log") != dir_or_file.length() - 4) {
  2807. if (exec_state) {
  2808. *exec_state = LDBCommandExecuteResult::Failed(
  2809. dir_or_file + ": Invalid log file name");
  2810. }
  2811. return;
  2812. }
  2813. DumpWalFile(options, dir_or_file, print_header, print_values,
  2814. only_print_seqno_gaps, is_write_committed, ucmps, exec_state,
  2815. &prev_batch_seqno, &prev_batch_count);
  2816. } else {
  2817. WALFileIterator wal_file_iter(dir_or_file, filenames);
  2818. if (!wal_file_iter.Valid()) {
  2819. if (exec_state) {
  2820. *exec_state = LDBCommandExecuteResult::Failed(
  2821. dir_or_file + ": No valid wal logs found");
  2822. }
  2823. return;
  2824. }
  2825. std::string wal_file = wal_file_iter.GetNextWAL();
  2826. while (!wal_file.empty()) {
  2827. std::cout << "Checking wal file: " << wal_file << std::endl;
  2828. DumpWalFile(options, wal_file, print_header, print_values,
  2829. only_print_seqno_gaps, is_write_committed, ucmps, exec_state,
  2830. &prev_batch_seqno, &prev_batch_count);
  2831. if (exec_state->IsFailed() || !wal_file_iter.Valid()) {
  2832. return;
  2833. }
  2834. wal_file = wal_file_iter.GetNextWAL();
  2835. }
  2836. }
  2837. }
  2838. void DumpWalFile(Options options, const std::string& wal_file,
  2839. bool print_header, bool print_values,
  2840. bool only_print_seqno_gaps, bool is_write_committed,
  2841. const std::map<uint32_t, const Comparator*>& ucmps,
  2842. LDBCommandExecuteResult* exec_state,
  2843. std::optional<SequenceNumber>* prev_batch_seqno,
  2844. std::optional<uint32_t>* prev_batch_count) {
  2845. const auto& fs = options.env->GetFileSystem();
  2846. FileOptions soptions(options);
  2847. std::unique_ptr<SequentialFileReader> wal_file_reader;
  2848. Status status = SequentialFileReader::Create(
  2849. fs, wal_file, soptions, &wal_file_reader, nullptr /* dbg */,
  2850. nullptr /* rate_limiter */);
  2851. if (!status.ok()) {
  2852. if (exec_state) {
  2853. *exec_state = LDBCommandExecuteResult::Failed("Failed to open WAL file " +
  2854. status.ToString());
  2855. } else {
  2856. std::cerr << "Error: Failed to open WAL file " << status.ToString()
  2857. << std::endl;
  2858. }
  2859. } else {
  2860. StdErrReporter reporter;
  2861. uint64_t log_number;
  2862. FileType type;
  2863. // Comparators are available and will be used for formatting user key if DB
  2864. // is opened for this dump wal operation.
  2865. UnorderedMap<uint32_t, size_t> running_ts_sz;
  2866. for (const auto& [cf_id, ucmp] : ucmps) {
  2867. running_ts_sz.emplace(cf_id, ucmp->timestamp_size());
  2868. }
  2869. // we need the log number, but ParseFilename expects dbname/NNN.log.
  2870. std::string sanitized = wal_file;
  2871. size_t lastslash = sanitized.rfind('/');
  2872. if (lastslash != std::string::npos) {
  2873. sanitized = sanitized.substr(lastslash + 1);
  2874. }
  2875. if (!ParseFileName(sanitized, &log_number, &type)) {
  2876. // bogus input, carry on as best we can
  2877. log_number = 0;
  2878. }
  2879. log::Reader reader(options.info_log, std::move(wal_file_reader), &reporter,
  2880. true /* checksum */, log_number);
  2881. std::unordered_set<uint32_t> encountered_cf_ids;
  2882. std::string scratch;
  2883. WriteBatch batch;
  2884. Slice record;
  2885. std::stringstream row;
  2886. if (print_header) {
  2887. std::cout << "Sequence,Count,ByteSize,Physical Offset,Key(s)";
  2888. if (print_values) {
  2889. std::cout << " : value ";
  2890. }
  2891. std::cout << "\n";
  2892. }
  2893. while (status.ok() && reader.ReadRecord(&record, &scratch)) {
  2894. row.str("");
  2895. if (record.size() < WriteBatchInternal::kHeader) {
  2896. reporter.Corruption(record.size(),
  2897. Status::Corruption("log record too small"));
  2898. } else {
  2899. status = WriteBatchInternal::SetContents(&batch, record);
  2900. if (!status.ok()) {
  2901. std::stringstream oss;
  2902. oss << "Parsing write batch failed: " << status.ToString();
  2903. if (exec_state) {
  2904. *exec_state = LDBCommandExecuteResult::Failed(oss.str());
  2905. } else {
  2906. std::cerr << oss.str() << std::endl;
  2907. }
  2908. break;
  2909. }
  2910. const UnorderedMap<uint32_t, size_t> recorded_ts_sz =
  2911. reader.GetRecordedTimestampSize();
  2912. if (!running_ts_sz.empty()) {
  2913. status = HandleWriteBatchTimestampSizeDifference(
  2914. &batch, running_ts_sz, recorded_ts_sz,
  2915. TimestampSizeConsistencyMode::kVerifyConsistency,
  2916. /* seq_per_batch */ false, /* batch_per_txn */ true,
  2917. /*new_batch=*/nullptr);
  2918. if (!status.ok()) {
  2919. std::stringstream oss;
  2920. oss << "Format for user keys in WAL file is inconsistent with the "
  2921. "comparator used to open the DB. Timestamp size recorded in "
  2922. "WAL vs specified by "
  2923. "comparator: {";
  2924. bool first_cf = true;
  2925. for (const auto& [cf_id, ts_sz] : running_ts_sz) {
  2926. if (first_cf) {
  2927. first_cf = false;
  2928. } else {
  2929. oss << ", ";
  2930. }
  2931. auto record_ts_iter = recorded_ts_sz.find(cf_id);
  2932. size_t ts_sz_in_wal = (record_ts_iter == recorded_ts_sz.end())
  2933. ? 0
  2934. : record_ts_iter->second;
  2935. oss << "(cf_id: " << cf_id << ", [recorded: " << ts_sz_in_wal
  2936. << ", comparator: " << ts_sz << "])";
  2937. }
  2938. oss << "}";
  2939. if (exec_state) {
  2940. *exec_state = LDBCommandExecuteResult::Failed(oss.str());
  2941. } else {
  2942. std::cerr << oss.str() << std::endl;
  2943. }
  2944. break;
  2945. }
  2946. }
  2947. SequenceNumber sequence_number = WriteBatchInternal::Sequence(&batch);
  2948. uint32_t batch_count = WriteBatchInternal::Count(&batch);
  2949. assert(prev_batch_seqno);
  2950. assert(prev_batch_count);
  2951. assert(prev_batch_seqno->has_value() == prev_batch_count->has_value());
  2952. // TODO(yuzhangyu): handle pessimistic transactions case.
  2953. if (only_print_seqno_gaps) {
  2954. if (!prev_batch_seqno->has_value() ||
  2955. !prev_batch_count->has_value() ||
  2956. prev_batch_seqno->value() + prev_batch_count->value() ==
  2957. sequence_number) {
  2958. *prev_batch_seqno = sequence_number;
  2959. *prev_batch_count = batch_count;
  2960. continue;
  2961. } else if (prev_batch_seqno->has_value() &&
  2962. prev_batch_count->has_value()) {
  2963. row << "Prev batch sequence number: " << prev_batch_seqno->value()
  2964. << ", prev batch count: " << prev_batch_count->value() << ", ";
  2965. *prev_batch_seqno = sequence_number;
  2966. *prev_batch_count = batch_count;
  2967. }
  2968. }
  2969. row << sequence_number << ",";
  2970. row << batch_count << ",";
  2971. *prev_batch_seqno = sequence_number;
  2972. *prev_batch_count = batch_count;
  2973. row << WriteBatchInternal::ByteSize(&batch) << ",";
  2974. row << reader.LastRecordOffset() << ",";
  2975. ColumnFamilyCollector cf_collector;
  2976. status = batch.Iterate(&cf_collector);
  2977. auto cf_ids = cf_collector.column_families();
  2978. encountered_cf_ids.insert(cf_ids.begin(), cf_ids.end());
  2979. InMemoryHandler handler(row, print_values, is_write_committed, ucmps);
  2980. status = batch.Iterate(&handler);
  2981. if (!status.ok()) {
  2982. if (exec_state) {
  2983. std::stringstream oss;
  2984. oss << "Print write batch error: " << status.ToString();
  2985. *exec_state = LDBCommandExecuteResult::Failed(oss.str());
  2986. }
  2987. row << "error: " << status.ToString();
  2988. break;
  2989. }
  2990. row << "\n";
  2991. }
  2992. std::cout << row.str();
  2993. }
  2994. std::stringstream cf_ids_oss;
  2995. bool empty_cfs = true;
  2996. for (uint32_t cf_id : encountered_cf_ids) {
  2997. if (ucmps.find(cf_id) == ucmps.end()) {
  2998. if (empty_cfs) {
  2999. cf_ids_oss << "[";
  3000. empty_cfs = false;
  3001. } else {
  3002. cf_ids_oss << ",";
  3003. }
  3004. cf_ids_oss << cf_id;
  3005. }
  3006. }
  3007. if (!empty_cfs) {
  3008. cf_ids_oss << "]";
  3009. std::cout
  3010. << "(Column family id: " << cf_ids_oss.str()
  3011. << " contained in WAL are not opened in DB. Applied default "
  3012. "hex formatting for user key. Specify --db=<db_path> to "
  3013. "open DB for better user key formatting if it contains timestamp.)"
  3014. << std::endl;
  3015. }
  3016. }
  3017. }
  3018. } // namespace
  3019. const std::string WALDumperCommand::ARG_WAL_FILE = "walfile";
  3020. const std::string WALDumperCommand::ARG_WRITE_COMMITTED = "write_committed";
  3021. const std::string WALDumperCommand::ARG_PRINT_VALUE = "print_value";
  3022. const std::string WALDumperCommand::ARG_PRINT_HEADER = "header";
  3023. const std::string WALDumperCommand::ARG_ONLY_PRINT_SEQNO_GAPS =
  3024. "only_print_seqno_gaps";
  3025. WALDumperCommand::WALDumperCommand(
  3026. const std::vector<std::string>& /*params*/,
  3027. const std::map<std::string, std::string>& options,
  3028. const std::vector<std::string>& flags)
  3029. : LDBCommand(options, flags, true /* is_read_only */,
  3030. BuildCmdLineOptions({ARG_WAL_FILE, ARG_DB, ARG_WRITE_COMMITTED,
  3031. ARG_PRINT_HEADER, ARG_PRINT_VALUE,
  3032. ARG_ONLY_PRINT_SEQNO_GAPS})),
  3033. print_header_(false),
  3034. print_values_(false),
  3035. only_print_seqno_gaps_(false),
  3036. is_write_committed_(false) {
  3037. wal_file_.clear();
  3038. auto itr = options.find(ARG_WAL_FILE);
  3039. if (itr != options.end()) {
  3040. wal_file_ = itr->second;
  3041. }
  3042. print_header_ = IsFlagPresent(flags, ARG_PRINT_HEADER);
  3043. print_values_ = IsFlagPresent(flags, ARG_PRINT_VALUE);
  3044. only_print_seqno_gaps_ = IsFlagPresent(flags, ARG_ONLY_PRINT_SEQNO_GAPS);
  3045. is_write_committed_ = ParseBooleanOption(options, ARG_WRITE_COMMITTED, true);
  3046. if (wal_file_.empty()) {
  3047. exec_state_ = LDBCommandExecuteResult::Failed("Argument " + ARG_WAL_FILE +
  3048. " must be specified.");
  3049. }
  3050. if (!db_path_.empty()) {
  3051. no_db_open_ = false;
  3052. }
  3053. }
  3054. void WALDumperCommand::Help(std::string& ret) {
  3055. ret.append(" ");
  3056. ret.append(WALDumperCommand::Name());
  3057. ret.append(" --" + ARG_WAL_FILE +
  3058. "=<write_ahead_log_file_path_or_directory>");
  3059. ret.append(" [--" + ARG_DB + "=<db_path>]");
  3060. ret.append(" [--" + ARG_PRINT_HEADER + "] ");
  3061. ret.append(" [--" + ARG_PRINT_VALUE + "] ");
  3062. ret.append(" [--" + ARG_ONLY_PRINT_SEQNO_GAPS +
  3063. "] (only correct if not using pessimistic transactions)");
  3064. ret.append(" [--" + ARG_WRITE_COMMITTED + "=true|false] ");
  3065. ret.append("\n");
  3066. }
  3067. void WALDumperCommand::DoCommand() {
  3068. PrepareOptions();
  3069. DumpWalFiles(options_, wal_file_, print_header_, print_values_,
  3070. only_print_seqno_gaps_, is_write_committed_, ucmps_,
  3071. &exec_state_);
  3072. }
  3073. // ----------------------------------------------------------------------------
  3074. GetCommand::GetCommand(const std::vector<std::string>& params,
  3075. const std::map<std::string, std::string>& options,
  3076. const std::vector<std::string>& flags)
  3077. : LDBCommand(options, flags, true /* is_read_only */,
  3078. BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
  3079. ARG_VALUE_HEX, ARG_READ_TIMESTAMP})) {
  3080. if (params.size() != 1) {
  3081. exec_state_ = LDBCommandExecuteResult::Failed(
  3082. "<key> must be specified for the get command");
  3083. } else {
  3084. key_ = params.at(0);
  3085. }
  3086. if (is_key_hex_) {
  3087. key_ = HexToString(key_);
  3088. }
  3089. }
  3090. void GetCommand::Help(std::string& ret) {
  3091. ret.append(" ");
  3092. ret.append(GetCommand::Name());
  3093. ret.append(" <key>");
  3094. ret.append(" [--" + ARG_READ_TIMESTAMP + "=<uint64_ts>] ");
  3095. ret.append(" [--" + ARG_TTL + "]");
  3096. ret.append("\n");
  3097. }
  3098. void GetCommand::DoCommand() {
  3099. if (!db_) {
  3100. assert(GetExecuteState().IsFailed());
  3101. return;
  3102. }
  3103. ReadOptions ropts;
  3104. Slice read_timestamp;
  3105. ColumnFamilyHandle* cfh = GetCfHandle();
  3106. Status st = MaybePopulateReadTimestamp(cfh, ropts, &read_timestamp);
  3107. if (!st.ok()) {
  3108. std::stringstream oss;
  3109. oss << "Get failed: " << st.ToString();
  3110. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  3111. return;
  3112. }
  3113. std::string value;
  3114. st = db_->Get(ropts, cfh, key_, &value);
  3115. if (st.ok()) {
  3116. fprintf(stdout, "%s\n",
  3117. (is_value_hex_ ? StringToHex(value) : value).c_str());
  3118. } else if (st.IsNotFound()) {
  3119. fprintf(stdout, "Key not found\n");
  3120. } else {
  3121. std::stringstream oss;
  3122. oss << "Get failed: " << st.ToString();
  3123. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  3124. }
  3125. }
  3126. // ----------------------------------------------------------------------------
  3127. MultiGetCommand::MultiGetCommand(
  3128. const std::vector<std::string>& params,
  3129. const std::map<std::string, std::string>& options,
  3130. const std::vector<std::string>& flags)
  3131. : LDBCommand(options, flags, true /* is_read_only */,
  3132. BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
  3133. ARG_READ_TIMESTAMP})) {
  3134. if (params.size() < 1) {
  3135. exec_state_ = LDBCommandExecuteResult::Failed(
  3136. "At least one <key> must be specified for multi_get.");
  3137. } else {
  3138. for (size_t i = 0; i < params.size(); ++i) {
  3139. std::string key = params.at(i);
  3140. keys_.emplace_back(is_key_hex_ ? HexToString(key) : key);
  3141. }
  3142. }
  3143. }
  3144. void MultiGetCommand::Help(std::string& ret) {
  3145. ret.append(" ");
  3146. ret.append(MultiGetCommand::Name());
  3147. ret.append(" <key_1> <key_2> <key_3> ...");
  3148. ret.append(" [--" + ARG_READ_TIMESTAMP + "=<uint64_ts>] ");
  3149. ret.append("\n");
  3150. }
  3151. void MultiGetCommand::DoCommand() {
  3152. if (!db_) {
  3153. assert(GetExecuteState().IsFailed());
  3154. return;
  3155. }
  3156. ReadOptions ropts;
  3157. Slice read_timestamp;
  3158. ColumnFamilyHandle* cfh = GetCfHandle();
  3159. Status st = MaybePopulateReadTimestamp(cfh, ropts, &read_timestamp);
  3160. if (!st.ok()) {
  3161. std::stringstream oss;
  3162. oss << "MultiGet failed: " << st.ToString();
  3163. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  3164. return;
  3165. }
  3166. size_t num_keys = keys_.size();
  3167. std::vector<Slice> key_slices;
  3168. std::vector<PinnableSlice> values(num_keys);
  3169. std::vector<Status> statuses(num_keys);
  3170. for (const std::string& key : keys_) {
  3171. key_slices.emplace_back(key);
  3172. }
  3173. db_->MultiGet(ropts, cfh, num_keys, key_slices.data(), values.data(),
  3174. statuses.data());
  3175. bool failed = false;
  3176. for (size_t i = 0; i < num_keys; ++i) {
  3177. if (statuses[i].ok()) {
  3178. fprintf(stdout, is_value_hex_ ? "%s%s0x%s\n" : "%s%s%s\n",
  3179. (is_key_hex_ ? StringToHex(keys_[i]) : keys_[i]).c_str(), DELIM,
  3180. values[i].ToString(is_value_hex_).c_str());
  3181. } else if (statuses[i].IsNotFound()) {
  3182. fprintf(stdout, "Key not found: %s\n",
  3183. (is_key_hex_ ? StringToHex(keys_[i]) : keys_[i]).c_str());
  3184. } else {
  3185. fprintf(stderr, "Status for key %s: %s\n",
  3186. (is_key_hex_ ? StringToHex(keys_[i]) : keys_[i]).c_str(),
  3187. statuses[i].ToString().c_str());
  3188. failed = true;
  3189. }
  3190. }
  3191. if (failed) {
  3192. exec_state_ =
  3193. LDBCommandExecuteResult::Failed("one or more keys had non-okay status");
  3194. }
  3195. }
  3196. // ----------------------------------------------------------------------------
  3197. GetEntityCommand::GetEntityCommand(
  3198. const std::vector<std::string>& params,
  3199. const std::map<std::string, std::string>& options,
  3200. const std::vector<std::string>& flags)
  3201. : LDBCommand(options, flags, true /* is_read_only */,
  3202. BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
  3203. ARG_VALUE_HEX, ARG_READ_TIMESTAMP})) {
  3204. if (params.size() != 1) {
  3205. exec_state_ = LDBCommandExecuteResult::Failed(
  3206. "<key> must be specified for the get_entity command");
  3207. } else {
  3208. key_ = params.at(0);
  3209. }
  3210. if (is_key_hex_) {
  3211. key_ = HexToString(key_);
  3212. }
  3213. }
  3214. void GetEntityCommand::Help(std::string& ret) {
  3215. ret.append(" ");
  3216. ret.append(GetEntityCommand::Name());
  3217. ret.append(" <key>");
  3218. ret.append(" [--" + ARG_READ_TIMESTAMP + "=<uint64_ts>] ");
  3219. ret.append(" [--" + ARG_TTL + "]");
  3220. ret.append("\n");
  3221. }
  3222. void GetEntityCommand::DoCommand() {
  3223. if (!db_) {
  3224. assert(GetExecuteState().IsFailed());
  3225. return;
  3226. }
  3227. ReadOptions ropt;
  3228. Slice read_timestamp;
  3229. ColumnFamilyHandle* cfh = GetCfHandle();
  3230. Status st = MaybePopulateReadTimestamp(cfh, ropt, &read_timestamp);
  3231. if (!st.ok()) {
  3232. std::stringstream oss;
  3233. oss << "GetEntity failed: " << st.ToString();
  3234. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  3235. return;
  3236. }
  3237. PinnableWideColumns pinnable_wide_columns;
  3238. st = db_->GetEntity(ropt, cfh, key_, &pinnable_wide_columns);
  3239. if (st.ok()) {
  3240. std::ostringstream oss;
  3241. WideColumnsHelper::DumpWideColumns(pinnable_wide_columns.columns(), oss,
  3242. is_value_hex_);
  3243. fprintf(stdout, "%s\n", oss.str().c_str());
  3244. } else {
  3245. std::stringstream oss;
  3246. oss << "GetEntity failed: " << st.ToString();
  3247. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  3248. }
  3249. }
  3250. // ----------------------------------------------------------------------------
  3251. MultiGetEntityCommand::MultiGetEntityCommand(
  3252. const std::vector<std::string>& params,
  3253. const std::map<std::string, std::string>& options,
  3254. const std::vector<std::string>& flags)
  3255. : LDBCommand(options, flags, true /* is_read_only */,
  3256. BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
  3257. ARG_READ_TIMESTAMP})) {
  3258. if (params.size() < 1) {
  3259. exec_state_ = LDBCommandExecuteResult::Failed(
  3260. "At least one <key> must be specified for the multi_get_entity "
  3261. "command");
  3262. } else {
  3263. for (size_t i = 0; i < params.size(); i++) {
  3264. std::string key = params.at(i);
  3265. keys_.emplace_back(is_key_hex_ ? HexToString(key) : key);
  3266. }
  3267. }
  3268. }
  3269. void MultiGetEntityCommand::Help(std::string& ret) {
  3270. ret.append(" ");
  3271. ret.append(MultiGetEntityCommand::Name());
  3272. ret.append(" <key_1> <key_2> <key_3> ...");
  3273. ret.append(" [--" + ARG_READ_TIMESTAMP + "=<uint64_ts>] ");
  3274. ret.append("\n");
  3275. }
  3276. void MultiGetEntityCommand::DoCommand() {
  3277. if (!db_) {
  3278. assert(GetExecuteState().IsFailed());
  3279. return;
  3280. }
  3281. ReadOptions ropt;
  3282. Slice read_timestamp;
  3283. ColumnFamilyHandle* cfh = GetCfHandle();
  3284. Status st = MaybePopulateReadTimestamp(cfh, ropt, &read_timestamp);
  3285. if (!st.ok()) {
  3286. std::stringstream oss;
  3287. oss << "MultiGetEntity failed: " << st.ToString();
  3288. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  3289. return;
  3290. }
  3291. size_t num_keys = keys_.size();
  3292. std::vector<Slice> key_slices;
  3293. std::vector<PinnableWideColumns> results(num_keys);
  3294. std::vector<Status> statuses(num_keys);
  3295. for (const std::string& key : keys_) {
  3296. key_slices.emplace_back(key);
  3297. }
  3298. db_->MultiGetEntity(ropt, cfh, num_keys, key_slices.data(), results.data(),
  3299. statuses.data());
  3300. bool failed = false;
  3301. for (size_t i = 0; i < num_keys; ++i) {
  3302. std::string key = is_key_hex_ ? StringToHex(keys_[i]) : keys_[i];
  3303. if (statuses[i].ok()) {
  3304. std::ostringstream oss;
  3305. oss << key << DELIM;
  3306. WideColumnsHelper::DumpWideColumns(results[i].columns(), oss,
  3307. is_value_hex_);
  3308. fprintf(stdout, "%s\n", oss.str().c_str());
  3309. } else if (statuses[i].IsNotFound()) {
  3310. fprintf(stdout, "Key not found: %s\n", key.c_str());
  3311. } else {
  3312. fprintf(stderr, "Status for key %s: %s\n", key.c_str(),
  3313. statuses[i].ToString().c_str());
  3314. failed = true;
  3315. }
  3316. }
  3317. if (failed) {
  3318. exec_state_ =
  3319. LDBCommandExecuteResult::Failed("one or more keys had non-okay status");
  3320. }
  3321. }
  3322. // ----------------------------------------------------------------------------
  3323. ApproxSizeCommand::ApproxSizeCommand(
  3324. const std::vector<std::string>& /*params*/,
  3325. const std::map<std::string, std::string>& options,
  3326. const std::vector<std::string>& flags)
  3327. : LDBCommand(options, flags, true /* is_read_only */,
  3328. BuildCmdLineOptions(
  3329. {ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM, ARG_TO})) {
  3330. if (options.find(ARG_FROM) != options.end()) {
  3331. start_key_ = options.find(ARG_FROM)->second;
  3332. } else {
  3333. exec_state_ = LDBCommandExecuteResult::Failed(
  3334. ARG_FROM + " must be specified for approxsize command");
  3335. return;
  3336. }
  3337. if (options.find(ARG_TO) != options.end()) {
  3338. end_key_ = options.find(ARG_TO)->second;
  3339. } else {
  3340. exec_state_ = LDBCommandExecuteResult::Failed(
  3341. ARG_TO + " must be specified for approxsize command");
  3342. return;
  3343. }
  3344. if (is_key_hex_) {
  3345. start_key_ = HexToString(start_key_);
  3346. end_key_ = HexToString(end_key_);
  3347. }
  3348. }
  3349. void ApproxSizeCommand::Help(std::string& ret) {
  3350. ret.append(" ");
  3351. ret.append(ApproxSizeCommand::Name());
  3352. ret.append(HelpRangeCmdArgs());
  3353. ret.append("\n");
  3354. }
  3355. void ApproxSizeCommand::DoCommand() {
  3356. if (!db_) {
  3357. assert(GetExecuteState().IsFailed());
  3358. return;
  3359. }
  3360. Range ranges[1];
  3361. ranges[0] = Range(start_key_, end_key_);
  3362. uint64_t sizes[1];
  3363. Status s = db_->GetApproximateSizes(GetCfHandle(), ranges, 1, sizes);
  3364. if (!s.ok()) {
  3365. std::stringstream oss;
  3366. oss << "ApproximateSize failed: " << s.ToString();
  3367. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  3368. } else {
  3369. fprintf(stdout, "%lu\n", (unsigned long)sizes[0]);
  3370. }
  3371. }
  3372. // ----------------------------------------------------------------------------
  3373. BatchPutCommand::BatchPutCommand(
  3374. const std::vector<std::string>& params,
  3375. const std::map<std::string, std::string>& options,
  3376. const std::vector<std::string>& flags)
  3377. : LDBCommand(options, flags, false /* is_read_only */,
  3378. BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
  3379. ARG_VALUE_HEX, ARG_CREATE_IF_MISSING})) {
  3380. if (params.size() < 2) {
  3381. exec_state_ = LDBCommandExecuteResult::Failed(
  3382. "At least one <key> <value> pair must be specified batchput.");
  3383. } else if (params.size() % 2 != 0) {
  3384. exec_state_ = LDBCommandExecuteResult::Failed(
  3385. "Equal number of <key>s and <value>s must be specified for batchput.");
  3386. } else {
  3387. for (size_t i = 0; i < params.size(); i += 2) {
  3388. std::string key = params.at(i);
  3389. std::string value = params.at(i + 1);
  3390. key_values_.emplace_back(is_key_hex_ ? HexToString(key) : key,
  3391. is_value_hex_ ? HexToString(value) : value);
  3392. }
  3393. }
  3394. create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
  3395. }
  3396. void BatchPutCommand::Help(std::string& ret) {
  3397. ret.append(" ");
  3398. ret.append(BatchPutCommand::Name());
  3399. ret.append(" <key> <value> [<key> <value>] [..]");
  3400. ret.append(" [--" + ARG_CREATE_IF_MISSING + "]");
  3401. ret.append(" [--" + ARG_TTL + "]");
  3402. ret.append("\n");
  3403. }
  3404. void BatchPutCommand::DoCommand() {
  3405. if (!db_) {
  3406. assert(GetExecuteState().IsFailed());
  3407. return;
  3408. }
  3409. WriteBatch batch;
  3410. Status st;
  3411. std::stringstream oss;
  3412. for (std::vector<std::pair<std::string, std::string>>::const_iterator itr =
  3413. key_values_.begin();
  3414. itr != key_values_.end(); ++itr) {
  3415. st = batch.Put(GetCfHandle(), itr->first, itr->second);
  3416. if (!st.ok()) {
  3417. oss << "Put to write batch failed: " << itr->first << "=>" << itr->second
  3418. << " error: " << st.ToString();
  3419. break;
  3420. }
  3421. }
  3422. if (st.ok()) {
  3423. st = db_->Write(WriteOptions(), &batch);
  3424. if (!st.ok()) {
  3425. oss << "Write failed: " << st.ToString();
  3426. }
  3427. }
  3428. if (st.ok()) {
  3429. fprintf(stdout, "OK\n");
  3430. } else {
  3431. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  3432. }
  3433. }
  3434. void BatchPutCommand::OverrideBaseOptions() {
  3435. LDBCommand::OverrideBaseOptions();
  3436. options_.create_if_missing = create_if_missing_;
  3437. }
  3438. // ----------------------------------------------------------------------------
  3439. ScanCommand::ScanCommand(const std::vector<std::string>& /*params*/,
  3440. const std::map<std::string, std::string>& options,
  3441. const std::vector<std::string>& flags)
  3442. : LDBCommand(
  3443. options, flags, true /* is_read_only */,
  3444. BuildCmdLineOptions({ARG_TTL, ARG_NO_VALUE, ARG_HEX, ARG_KEY_HEX,
  3445. ARG_TO, ARG_VALUE_HEX, ARG_FROM, ARG_TIMESTAMP,
  3446. ARG_MAX_KEYS, ARG_TTL_START, ARG_TTL_END,
  3447. ARG_READ_TIMESTAMP, ARG_GET_WRITE_UNIX_TIME})),
  3448. start_key_specified_(false),
  3449. end_key_specified_(false),
  3450. max_keys_scanned_(-1),
  3451. no_value_(false) {
  3452. auto itr = options.find(ARG_FROM);
  3453. if (itr != options.end()) {
  3454. start_key_ = itr->second;
  3455. if (is_key_hex_) {
  3456. start_key_ = HexToString(start_key_);
  3457. }
  3458. start_key_specified_ = true;
  3459. }
  3460. itr = options.find(ARG_TO);
  3461. if (itr != options.end()) {
  3462. end_key_ = itr->second;
  3463. if (is_key_hex_) {
  3464. end_key_ = HexToString(end_key_);
  3465. }
  3466. end_key_specified_ = true;
  3467. }
  3468. std::vector<std::string>::const_iterator vitr =
  3469. std::find(flags.begin(), flags.end(), ARG_NO_VALUE);
  3470. if (vitr != flags.end()) {
  3471. no_value_ = true;
  3472. }
  3473. itr = options.find(ARG_MAX_KEYS);
  3474. if (itr != options.end()) {
  3475. try {
  3476. #if defined(CYGWIN)
  3477. max_keys_scanned_ = strtol(itr->second.c_str(), 0, 10);
  3478. #else
  3479. max_keys_scanned_ = std::stoi(itr->second);
  3480. #endif
  3481. } catch (const std::invalid_argument&) {
  3482. exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
  3483. " has an invalid value");
  3484. } catch (const std::out_of_range&) {
  3485. exec_state_ = LDBCommandExecuteResult::Failed(
  3486. ARG_MAX_KEYS + " has a value out-of-range");
  3487. }
  3488. }
  3489. get_write_unix_time_ = IsFlagPresent(flags_, ARG_GET_WRITE_UNIX_TIME);
  3490. }
  3491. void ScanCommand::Help(std::string& ret) {
  3492. ret.append(" ");
  3493. ret.append(ScanCommand::Name());
  3494. ret.append(HelpRangeCmdArgs());
  3495. ret.append(" [--" + ARG_TTL + "]");
  3496. ret.append(" [--" + ARG_TIMESTAMP + "]");
  3497. ret.append(" [--" + ARG_MAX_KEYS + "=<N>q] ");
  3498. ret.append(" [--" + ARG_TTL_START + "=<N>:- is inclusive]");
  3499. ret.append(" [--" + ARG_TTL_END + "=<N>:- is exclusive]");
  3500. ret.append(" [--" + ARG_NO_VALUE + "]");
  3501. ret.append(" [--" + ARG_READ_TIMESTAMP + "=<uint64_ts>] ");
  3502. ret.append(" [--" + ARG_GET_WRITE_UNIX_TIME + "]");
  3503. ret.append("\n");
  3504. }
  3505. void ScanCommand::DoCommand() {
  3506. if (!db_) {
  3507. assert(GetExecuteState().IsFailed());
  3508. return;
  3509. }
  3510. int num_keys_scanned = 0;
  3511. ReadOptions scan_read_opts;
  3512. ColumnFamilyHandle* cfh = GetCfHandle();
  3513. const Comparator* ucmp = cfh->GetComparator();
  3514. size_t ts_sz = ucmp->timestamp_size();
  3515. Slice read_timestamp;
  3516. Status st = MaybePopulateReadTimestamp(cfh, scan_read_opts, &read_timestamp);
  3517. if (!st.ok()) {
  3518. std::stringstream oss;
  3519. oss << "Scan failed: " << st.ToString();
  3520. exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  3521. return;
  3522. }
  3523. scan_read_opts.total_order_seek = true;
  3524. Iterator* it = db_->NewIterator(scan_read_opts, cfh);
  3525. if (start_key_specified_) {
  3526. it->Seek(start_key_);
  3527. } else {
  3528. it->SeekToFirst();
  3529. }
  3530. int ttl_start;
  3531. if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
  3532. ttl_start = DBWithTTLImpl::kMinTimestamp; // TTL introduction time
  3533. }
  3534. int ttl_end;
  3535. if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
  3536. ttl_end = DBWithTTLImpl::kMaxTimestamp; // Max time allowed by TTL feature
  3537. }
  3538. if (ttl_end < ttl_start) {
  3539. fprintf(stderr, "Error: End time can't be less than start time\n");
  3540. delete it;
  3541. return;
  3542. }
  3543. if (is_db_ttl_ && timestamp_) {
  3544. fprintf(stdout, "Scanning key-values from %s to %s\n",
  3545. TimeToHumanString(ttl_start).c_str(),
  3546. TimeToHumanString(ttl_end).c_str());
  3547. }
  3548. for (;
  3549. it->Valid() && (!end_key_specified_ || it->key().ToString() < end_key_);
  3550. it->Next()) {
  3551. if (is_db_ttl_) {
  3552. TtlIterator* it_ttl = static_cast_with_check<TtlIterator>(it);
  3553. int rawtime = it_ttl->ttl_timestamp();
  3554. if (rawtime < ttl_start || rawtime >= ttl_end) {
  3555. continue;
  3556. }
  3557. if (timestamp_) {
  3558. fprintf(stdout, "%s ", TimeToHumanString(rawtime).c_str());
  3559. }
  3560. }
  3561. if (no_value_) {
  3562. std::string key_str = it->key().ToString();
  3563. if (is_key_hex_) {
  3564. key_str = StringToHex(key_str);
  3565. } else if (ldb_options_.key_formatter) {
  3566. key_str = ldb_options_.key_formatter->Format(key_str);
  3567. }
  3568. fprintf(stdout, "%s\n", key_str.c_str());
  3569. } else {
  3570. std::string str =
  3571. is_db_ttl_
  3572. ? PrintKeyValue(it->key().ToString(),
  3573. ts_sz == 0 ? "" : it->timestamp().ToString(),
  3574. it->value().ToString(), is_key_hex_,
  3575. is_value_hex_, ucmp)
  3576. : PrintKeyValueOrWideColumns(
  3577. it->key(), ts_sz == 0 ? "" : it->timestamp(), it->value(),
  3578. it->columns(), is_key_hex_, is_value_hex_, ucmp);
  3579. fprintf(stdout, "%s\n", str.c_str());
  3580. }
  3581. if (get_write_unix_time_) {
  3582. std::string write_unix_time;
  3583. uint64_t write_time_int = std::numeric_limits<uint64_t>::max();
  3584. Status s =
  3585. it->GetProperty("rocksdb.iterator.write-time", &write_unix_time);
  3586. if (s.ok()) {
  3587. s = DecodeU64Ts(write_unix_time, &write_time_int);
  3588. }
  3589. if (!s.ok()) {
  3590. fprintf(stdout, " Failed to get write unix time: %s\n",
  3591. s.ToString().c_str());
  3592. } else {
  3593. fprintf(stdout, " write unix time: %s\n",
  3594. std::to_string(write_time_int).c_str());
  3595. }
  3596. }
  3597. num_keys_scanned++;
  3598. if (max_keys_scanned_ >= 0 && num_keys_scanned >= max_keys_scanned_) {
  3599. break;
  3600. }
  3601. }
  3602. if (!it->status().ok()) { // Check for any errors found during the scan
  3603. exec_state_ = LDBCommandExecuteResult::Failed(it->status().ToString());
  3604. }
  3605. delete it;
  3606. }
  3607. // ----------------------------------------------------------------------------
  3608. DeleteCommand::DeleteCommand(const std::vector<std::string>& params,
  3609. const std::map<std::string, std::string>& options,
  3610. const std::vector<std::string>& flags)
  3611. : LDBCommand(options, flags, false /* is_read_only */,
  3612. BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {
  3613. if (params.size() != 1) {
  3614. exec_state_ = LDBCommandExecuteResult::Failed(
  3615. "KEY must be specified for the delete command");
  3616. } else {
  3617. key_ = params.at(0);
  3618. if (is_key_hex_) {
  3619. key_ = HexToString(key_);
  3620. }
  3621. }
  3622. }
  3623. void DeleteCommand::Help(std::string& ret) {
  3624. ret.append(" ");
  3625. ret.append(DeleteCommand::Name() + " <key>");
  3626. ret.append("\n");
  3627. }
  3628. void DeleteCommand::DoCommand() {
  3629. if (!db_) {
  3630. assert(GetExecuteState().IsFailed());
  3631. return;
  3632. }
  3633. Status st = db_->Delete(WriteOptions(), GetCfHandle(), key_);
  3634. if (st.ok()) {
  3635. fprintf(stdout, "OK\n");
  3636. } else {
  3637. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  3638. }
  3639. }
  3640. SingleDeleteCommand::SingleDeleteCommand(
  3641. const std::vector<std::string>& params,
  3642. const std::map<std::string, std::string>& options,
  3643. const std::vector<std::string>& flags)
  3644. : LDBCommand(options, flags, false /* is_read_only */,
  3645. BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {
  3646. if (params.size() != 1) {
  3647. exec_state_ = LDBCommandExecuteResult::Failed(
  3648. "KEY must be specified for the single delete command");
  3649. } else {
  3650. key_ = params.at(0);
  3651. if (is_key_hex_) {
  3652. key_ = HexToString(key_);
  3653. }
  3654. }
  3655. }
  3656. void SingleDeleteCommand::Help(std::string& ret) {
  3657. ret.append(" ");
  3658. ret.append(SingleDeleteCommand::Name() + " <key>");
  3659. ret.append("\n");
  3660. }
  3661. void SingleDeleteCommand::DoCommand() {
  3662. if (!db_) {
  3663. assert(GetExecuteState().IsFailed());
  3664. return;
  3665. }
  3666. Status st = db_->SingleDelete(WriteOptions(), GetCfHandle(), key_);
  3667. if (st.ok()) {
  3668. fprintf(stdout, "OK\n");
  3669. } else {
  3670. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  3671. }
  3672. }
  3673. DeleteRangeCommand::DeleteRangeCommand(
  3674. const std::vector<std::string>& params,
  3675. const std::map<std::string, std::string>& options,
  3676. const std::vector<std::string>& flags)
  3677. : LDBCommand(options, flags, false /* is_read_only */,
  3678. BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {
  3679. if (params.size() != 2) {
  3680. exec_state_ = LDBCommandExecuteResult::Failed(
  3681. "begin and end keys must be specified for the delete command");
  3682. } else {
  3683. begin_key_ = params.at(0);
  3684. end_key_ = params.at(1);
  3685. if (is_key_hex_) {
  3686. begin_key_ = HexToString(begin_key_);
  3687. end_key_ = HexToString(end_key_);
  3688. }
  3689. }
  3690. }
  3691. void DeleteRangeCommand::Help(std::string& ret) {
  3692. ret.append(" ");
  3693. ret.append(DeleteRangeCommand::Name() + " <begin key> <end key>");
  3694. ret.append("\n");
  3695. }
  3696. void DeleteRangeCommand::DoCommand() {
  3697. if (!db_) {
  3698. assert(GetExecuteState().IsFailed());
  3699. return;
  3700. }
  3701. Status st =
  3702. db_->DeleteRange(WriteOptions(), GetCfHandle(), begin_key_, end_key_);
  3703. if (st.ok()) {
  3704. fprintf(stdout, "OK\n");
  3705. } else {
  3706. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  3707. }
  3708. }
  3709. PutCommand::PutCommand(const std::vector<std::string>& params,
  3710. const std::map<std::string, std::string>& options,
  3711. const std::vector<std::string>& flags)
  3712. : LDBCommand(options, flags, false /* is_read_only */,
  3713. BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
  3714. ARG_VALUE_HEX, ARG_CREATE_IF_MISSING})) {
  3715. if (params.size() != 2) {
  3716. exec_state_ = LDBCommandExecuteResult::Failed(
  3717. "<key> and <value> must be specified for the put command");
  3718. } else {
  3719. key_ = params.at(0);
  3720. value_ = params.at(1);
  3721. }
  3722. if (is_key_hex_) {
  3723. key_ = HexToString(key_);
  3724. }
  3725. if (is_value_hex_) {
  3726. value_ = HexToString(value_);
  3727. }
  3728. create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
  3729. }
  3730. void PutCommand::Help(std::string& ret) {
  3731. ret.append(" ");
  3732. ret.append(PutCommand::Name());
  3733. ret.append(" <key> <value>");
  3734. ret.append(" [--" + ARG_CREATE_IF_MISSING + "]");
  3735. ret.append(" [--" + ARG_TTL + "]");
  3736. ret.append("\n");
  3737. }
  3738. void PutCommand::DoCommand() {
  3739. if (!db_) {
  3740. assert(GetExecuteState().IsFailed());
  3741. return;
  3742. }
  3743. Status st = db_->Put(WriteOptions(), GetCfHandle(), key_, value_);
  3744. if (st.ok()) {
  3745. fprintf(stdout, "OK\n");
  3746. } else {
  3747. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  3748. }
  3749. }
  3750. void PutCommand::OverrideBaseOptions() {
  3751. LDBCommand::OverrideBaseOptions();
  3752. options_.create_if_missing = create_if_missing_;
  3753. }
  3754. // ----------------------------------------------------------------------------
  3755. PutEntityCommand::PutEntityCommand(
  3756. const std::vector<std::string>& params,
  3757. const std::map<std::string, std::string>& options,
  3758. const std::vector<std::string>& flags)
  3759. : LDBCommand(options, flags, false /* is_read_only */,
  3760. BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
  3761. ARG_VALUE_HEX, ARG_CREATE_IF_MISSING})) {
  3762. if (params.size() < 2) {
  3763. exec_state_ = LDBCommandExecuteResult::Failed(
  3764. "<key> and at least one column <column_name>:<column_value> must be "
  3765. "specified for the put_entity command");
  3766. } else {
  3767. auto iter = params.begin();
  3768. key_ = *iter;
  3769. if (is_key_hex_) {
  3770. key_ = HexToString(key_);
  3771. }
  3772. for (++iter; iter != params.end(); ++iter) {
  3773. auto split = StringSplit(*iter, ':');
  3774. if (split.size() != 2) {
  3775. exec_state_ = LDBCommandExecuteResult::Failed(
  3776. "wide column format needs to be <column_name>:<column_value> (did "
  3777. "you mean put <key> <value>?)");
  3778. return;
  3779. }
  3780. std::string name(split[0]);
  3781. std::string value(split[1]);
  3782. if (is_value_hex_) {
  3783. name = HexToString(name);
  3784. value = HexToString(value);
  3785. }
  3786. column_names_.push_back(name);
  3787. column_values_.push_back(value);
  3788. }
  3789. }
  3790. create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
  3791. }
  3792. void PutEntityCommand::Help(std::string& ret) {
  3793. ret.append(" ");
  3794. ret.append(PutEntityCommand::Name());
  3795. ret.append(
  3796. " <key> <column1_name>:<column1_value> <column2_name>:<column2_value> "
  3797. "<...>");
  3798. ret.append(" [--" + ARG_CREATE_IF_MISSING + "]");
  3799. ret.append(" [--" + ARG_TTL + "]");
  3800. ret.append("\n");
  3801. }
  3802. void PutEntityCommand::DoCommand() {
  3803. if (!db_) {
  3804. assert(GetExecuteState().IsFailed());
  3805. return;
  3806. }
  3807. assert(column_names_.size() == column_values_.size());
  3808. WideColumns columns;
  3809. for (size_t i = 0; i < column_names_.size(); i++) {
  3810. WideColumn column(column_names_[i], column_values_[i]);
  3811. columns.emplace_back(column);
  3812. }
  3813. Status st = db_->PutEntity(WriteOptions(), GetCfHandle(), key_, columns);
  3814. if (st.ok()) {
  3815. fprintf(stdout, "OK\n");
  3816. } else {
  3817. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  3818. }
  3819. }
  3820. void PutEntityCommand::OverrideBaseOptions() {
  3821. LDBCommand::OverrideBaseOptions();
  3822. options_.create_if_missing = create_if_missing_;
  3823. }
  3824. // ----------------------------------------------------------------------------
  3825. const char* DBQuerierCommand::HELP_CMD = "help";
  3826. const char* DBQuerierCommand::GET_CMD = "get";
  3827. const char* DBQuerierCommand::PUT_CMD = "put";
  3828. const char* DBQuerierCommand::DELETE_CMD = "delete";
  3829. const char* DBQuerierCommand::COUNT_CMD = "count";
  3830. DBQuerierCommand::DBQuerierCommand(
  3831. const std::vector<std::string>& /*params*/,
  3832. const std::map<std::string, std::string>& options,
  3833. const std::vector<std::string>& flags)
  3834. : LDBCommand(
  3835. options, flags, false /* is_read_only */,
  3836. BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {
  3837. }
  3838. void DBQuerierCommand::Help(std::string& ret) {
  3839. ret.append(" ");
  3840. ret.append(DBQuerierCommand::Name());
  3841. ret.append(" [--" + ARG_TTL + "]");
  3842. ret.append("\n");
  3843. ret.append(
  3844. " Starts a REPL shell. Type help for list of available "
  3845. "commands.");
  3846. ret.append("\n");
  3847. }
  3848. void DBQuerierCommand::DoCommand() {
  3849. if (!db_) {
  3850. assert(GetExecuteState().IsFailed());
  3851. return;
  3852. }
  3853. std::string line;
  3854. Status s;
  3855. ColumnFamilyHandle* cfh = GetCfHandle();
  3856. const Comparator* ucmp = cfh->GetComparator();
  3857. while ((s.ok() || s.IsNotFound() || s.IsInvalidArgument()) &&
  3858. getline(std::cin, line, '\n')) {
  3859. std::string key;
  3860. std::string timestamp;
  3861. std::string value;
  3862. // Reset to OK status before parsing and executing next user command.
  3863. s = Status::OK();
  3864. std::stringstream oss;
  3865. // Parse line into std::vector<std::string>
  3866. std::vector<std::string> tokens;
  3867. ParsedParams parsed_params;
  3868. size_t pos = 0;
  3869. while (true) {
  3870. size_t pos2 = line.find(' ', pos);
  3871. std::string token =
  3872. line.substr(pos, (pos2 == std::string::npos) ? pos2 : (pos2 - pos));
  3873. ParseSingleParam(token, parsed_params, tokens);
  3874. if (pos2 == std::string::npos) {
  3875. break;
  3876. }
  3877. pos = pos2 + 1;
  3878. }
  3879. if (tokens.empty() || !parsed_params.flags.empty()) {
  3880. fprintf(stdout, "Bad command\n");
  3881. continue;
  3882. }
  3883. const std::string& cmd = tokens[0];
  3884. ReadOptions read_options;
  3885. WriteOptions write_options;
  3886. Slice read_timestamp;
  3887. if (cmd == HELP_CMD) {
  3888. fprintf(stdout,
  3889. "get <key> [--read_timestamp=<uint64_ts>]\n"
  3890. "put <key> [<write_timestamp>] <value>\n"
  3891. "delete <key> [<write_timestamp>]\n"
  3892. "count [--from=<start_key>] [--to=<end_key>] "
  3893. "[--read_timestamp=<uint64_ts>]\n");
  3894. } else if (cmd == DELETE_CMD && parsed_params.option_map.empty()) {
  3895. key = (is_key_hex_ ? HexToString(tokens[1]) : tokens[1]);
  3896. if (tokens.size() == 2) {
  3897. s = db_->Delete(write_options, cfh, Slice(key));
  3898. } else if (tokens.size() == 3) {
  3899. Status encode_s = EncodeUserProvidedTimestamp(tokens[2], &timestamp);
  3900. if (encode_s.ok()) {
  3901. s = db_->Delete(write_options, cfh, Slice(key), Slice(timestamp));
  3902. } else {
  3903. fprintf(stdout, "delete gets invalid argument: %s\n",
  3904. encode_s.ToString().c_str());
  3905. continue;
  3906. }
  3907. } else {
  3908. fprintf(stdout, "delete gets invalid arguments\n");
  3909. continue;
  3910. }
  3911. oss << "delete " << (is_key_hex_ ? StringToHex(key) : key);
  3912. if (!timestamp.empty()) {
  3913. oss << " write_ts: " << ucmp->TimestampToString(timestamp);
  3914. }
  3915. if (s.ok()) {
  3916. oss << " succeeded";
  3917. } else {
  3918. oss << " failed: " << s.ToString();
  3919. }
  3920. fprintf(stdout, "%s\n", oss.str().c_str());
  3921. } else if (cmd == PUT_CMD && parsed_params.option_map.empty()) {
  3922. key = (is_key_hex_ ? HexToString(tokens[1]) : tokens[1]);
  3923. if (tokens.size() == 3) {
  3924. value = (is_value_hex_ ? HexToString(tokens[2]) : tokens[2]);
  3925. s = db_->Put(write_options, cfh, Slice(key), Slice(value));
  3926. } else if (tokens.size() == 4) {
  3927. value = (is_value_hex_ ? HexToString(tokens[3]) : tokens[3]);
  3928. Status encode_s = EncodeUserProvidedTimestamp(tokens[2], &timestamp);
  3929. if (encode_s.ok()) {
  3930. s = db_->Put(write_options, cfh, Slice(key), Slice(timestamp),
  3931. Slice(value));
  3932. } else {
  3933. fprintf(stdout, "put gets invalid argument: %s\n",
  3934. encode_s.ToString().c_str());
  3935. continue;
  3936. }
  3937. } else {
  3938. fprintf(stdout, "put gets invalid arguments\n");
  3939. continue;
  3940. }
  3941. oss << "put " << (is_key_hex_ ? StringToHex(key) : key);
  3942. if (!timestamp.empty()) {
  3943. oss << " write_ts: " << ucmp->TimestampToString(timestamp);
  3944. }
  3945. oss << " => " << (is_value_hex_ ? StringToHex(value) : value);
  3946. if (s.ok()) {
  3947. oss << " succeeded";
  3948. } else {
  3949. oss << " failed: " << s.ToString();
  3950. }
  3951. fprintf(stdout, "%s\n", oss.str().c_str());
  3952. } else if (cmd == GET_CMD && tokens.size() == 2) {
  3953. key = (is_key_hex_ ? HexToString(tokens[1]) : tokens[1]);
  3954. bool bad_option = false;
  3955. for (auto& option : parsed_params.option_map) {
  3956. if (option.first == "read_timestamp") {
  3957. Status encode_s =
  3958. EncodeUserProvidedTimestamp(option.second, &timestamp);
  3959. if (!encode_s.ok()) {
  3960. fprintf(stdout, "get gets invalid argument: %s\n",
  3961. encode_s.ToString().c_str());
  3962. bad_option = true;
  3963. break;
  3964. }
  3965. read_timestamp = timestamp;
  3966. read_options.timestamp = &read_timestamp;
  3967. } else {
  3968. fprintf(stdout, "get gets invalid arguments\n");
  3969. bad_option = true;
  3970. break;
  3971. }
  3972. }
  3973. if (bad_option) {
  3974. continue;
  3975. }
  3976. s = db_->Get(read_options, cfh, Slice(key), &value);
  3977. if (s.ok()) {
  3978. fprintf(stdout, "%s\n",
  3979. PrintKeyValue(key, timestamp, value, is_key_hex_, is_value_hex_,
  3980. ucmp)
  3981. .c_str());
  3982. } else {
  3983. oss << "get " << (is_key_hex_ ? StringToHex(key) : key);
  3984. if (!timestamp.empty()) {
  3985. oss << " read_timestamp: " << ucmp->TimestampToString(timestamp);
  3986. }
  3987. oss << " status: " << s.ToString();
  3988. fprintf(stdout, "%s\n", oss.str().c_str());
  3989. }
  3990. } else if (cmd == COUNT_CMD) {
  3991. std::string start_key;
  3992. std::string end_key;
  3993. bool bad_option = false;
  3994. for (auto& option : parsed_params.option_map) {
  3995. if (option.first == "from") {
  3996. start_key =
  3997. (is_key_hex_ ? HexToString(option.second) : option.second);
  3998. } else if (option.first == "to") {
  3999. end_key = (is_key_hex_ ? HexToString(option.second) : option.second);
  4000. } else if (option.first == "read_timestamp") {
  4001. Status encode_s =
  4002. EncodeUserProvidedTimestamp(option.second, &timestamp);
  4003. if (!encode_s.ok()) {
  4004. bad_option = true;
  4005. fprintf(stdout, "count gets invalid argument: %s\n",
  4006. encode_s.ToString().c_str());
  4007. break;
  4008. }
  4009. read_timestamp = timestamp;
  4010. read_options.timestamp = &read_timestamp;
  4011. } else {
  4012. fprintf(stdout, "count gets invalid arguments\n");
  4013. bad_option = true;
  4014. break;
  4015. }
  4016. }
  4017. if (bad_option) {
  4018. continue;
  4019. }
  4020. Slice end_key_slice(end_key);
  4021. uint64_t count = 0;
  4022. if (!end_key.empty()) {
  4023. read_options.iterate_upper_bound = &end_key_slice;
  4024. }
  4025. std::unique_ptr<Iterator> iter(db_->NewIterator(read_options, cfh));
  4026. if (start_key.empty()) {
  4027. iter->SeekToFirst();
  4028. } else {
  4029. iter->Seek(start_key);
  4030. }
  4031. while (iter->status().ok() && iter->Valid()) {
  4032. count++;
  4033. iter->Next();
  4034. }
  4035. if (iter->status().ok()) {
  4036. fprintf(stdout, "%" PRIu64 "\n", count);
  4037. } else {
  4038. oss << "scan from "
  4039. << (is_key_hex_ ? StringToHex(start_key) : start_key);
  4040. if (!timestamp.empty()) {
  4041. oss << " read_timestamp: " << ucmp->TimestampToString(timestamp);
  4042. }
  4043. oss << " to " << (is_key_hex_ ? StringToHex(end_key) : end_key)
  4044. << " failed: " << iter->status().ToString();
  4045. fprintf(stdout, "%s\n", oss.str().c_str());
  4046. }
  4047. } else {
  4048. fprintf(stdout, "Unknown command %s\n", line.c_str());
  4049. }
  4050. }
  4051. if (!(s.ok() || s.IsNotFound() || s.IsInvalidArgument())) {
  4052. exec_state_ = LDBCommandExecuteResult::Failed(s.ToString());
  4053. }
  4054. }
  4055. // ----------------------------------------------------------------------------
  4056. CheckConsistencyCommand::CheckConsistencyCommand(
  4057. const std::vector<std::string>& /*params*/,
  4058. const std::map<std::string, std::string>& options,
  4059. const std::vector<std::string>& flags)
  4060. : LDBCommand(options, flags, true /* is_read_only */,
  4061. BuildCmdLineOptions({})) {}
  4062. void CheckConsistencyCommand::Help(std::string& ret) {
  4063. ret.append(" ");
  4064. ret.append(CheckConsistencyCommand::Name());
  4065. ret.append("\n");
  4066. }
  4067. void CheckConsistencyCommand::DoCommand() {
  4068. options_.paranoid_checks = true;
  4069. options_.num_levels = 64;
  4070. OpenDB();
  4071. if (exec_state_.IsSucceed() || exec_state_.IsNotStarted()) {
  4072. fprintf(stdout, "OK\n");
  4073. }
  4074. CloseDB();
  4075. }
  4076. // ----------------------------------------------------------------------------
  4077. const std::string CheckPointCommand::ARG_CHECKPOINT_DIR = "checkpoint_dir";
  4078. CheckPointCommand::CheckPointCommand(
  4079. const std::vector<std::string>& /*params*/,
  4080. const std::map<std::string, std::string>& options,
  4081. const std::vector<std::string>& flags)
  4082. : LDBCommand(options, flags, false /* is_read_only */,
  4083. BuildCmdLineOptions({ARG_CHECKPOINT_DIR})) {
  4084. auto itr = options.find(ARG_CHECKPOINT_DIR);
  4085. if (itr != options.end()) {
  4086. checkpoint_dir_ = itr->second;
  4087. }
  4088. }
  4089. void CheckPointCommand::Help(std::string& ret) {
  4090. ret.append(" ");
  4091. ret.append(CheckPointCommand::Name());
  4092. ret.append(" [--" + ARG_CHECKPOINT_DIR + "] ");
  4093. ret.append("\n");
  4094. }
  4095. void CheckPointCommand::DoCommand() {
  4096. if (!db_) {
  4097. assert(GetExecuteState().IsFailed());
  4098. return;
  4099. }
  4100. Checkpoint* checkpoint;
  4101. Status status = Checkpoint::Create(db_, &checkpoint);
  4102. status = checkpoint->CreateCheckpoint(checkpoint_dir_);
  4103. if (status.ok()) {
  4104. fprintf(stdout, "OK\n");
  4105. } else {
  4106. exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  4107. }
  4108. }
  4109. // ----------------------------------------------------------------------------
  4110. const std::string RepairCommand::ARG_VERBOSE = "verbose";
  4111. RepairCommand::RepairCommand(const std::vector<std::string>& /*params*/,
  4112. const std::map<std::string, std::string>& options,
  4113. const std::vector<std::string>& flags)
  4114. : LDBCommand(options, flags, false /* is_read_only */,
  4115. BuildCmdLineOptions({ARG_VERBOSE})) {
  4116. verbose_ = IsFlagPresent(flags, ARG_VERBOSE);
  4117. }
  4118. void RepairCommand::Help(std::string& ret) {
  4119. ret.append(" ");
  4120. ret.append(RepairCommand::Name());
  4121. ret.append(" [--" + ARG_VERBOSE + "]");
  4122. ret.append("\n");
  4123. }
  4124. void RepairCommand::OverrideBaseOptions() {
  4125. LDBCommand::OverrideBaseOptions();
  4126. auto level = verbose_ ? InfoLogLevel::INFO_LEVEL : InfoLogLevel::WARN_LEVEL;
  4127. options_.info_log.reset(new StderrLogger(level));
  4128. }
  4129. void RepairCommand::DoCommand() {
  4130. PrepareOptions();
  4131. Status status = RepairDB(db_path_, options_);
  4132. if (status.ok()) {
  4133. fprintf(stdout, "OK\n");
  4134. } else {
  4135. exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  4136. }
  4137. }
  4138. // ----------------------------------------------------------------------------
  4139. const std::string BackupEngineCommand::ARG_NUM_THREADS = "num_threads";
  4140. const std::string BackupEngineCommand::ARG_BACKUP_ENV_URI = "backup_env_uri";
  4141. const std::string BackupEngineCommand::ARG_BACKUP_FS_URI = "backup_fs_uri";
  4142. const std::string BackupEngineCommand::ARG_BACKUP_DIR = "backup_dir";
  4143. const std::string BackupEngineCommand::ARG_STDERR_LOG_LEVEL =
  4144. "stderr_log_level";
  4145. BackupEngineCommand::BackupEngineCommand(
  4146. const std::vector<std::string>& /*params*/,
  4147. const std::map<std::string, std::string>& options,
  4148. const std::vector<std::string>& flags)
  4149. : LDBCommand(options, flags, false /* is_read_only */,
  4150. BuildCmdLineOptions({ARG_BACKUP_ENV_URI, ARG_BACKUP_FS_URI,
  4151. ARG_BACKUP_DIR, ARG_NUM_THREADS,
  4152. ARG_STDERR_LOG_LEVEL})),
  4153. num_threads_(1) {
  4154. auto itr = options.find(ARG_NUM_THREADS);
  4155. if (itr != options.end()) {
  4156. num_threads_ = std::stoi(itr->second);
  4157. }
  4158. itr = options.find(ARG_BACKUP_ENV_URI);
  4159. if (itr != options.end()) {
  4160. backup_env_uri_ = itr->second;
  4161. }
  4162. itr = options.find(ARG_BACKUP_FS_URI);
  4163. if (itr != options.end()) {
  4164. backup_fs_uri_ = itr->second;
  4165. }
  4166. if (!backup_env_uri_.empty() && !backup_fs_uri_.empty()) {
  4167. exec_state_ = LDBCommandExecuteResult::Failed(
  4168. "you may not specity both --" + ARG_BACKUP_ENV_URI + " and --" +
  4169. ARG_BACKUP_FS_URI);
  4170. }
  4171. itr = options.find(ARG_BACKUP_DIR);
  4172. if (itr == options.end()) {
  4173. exec_state_ = LDBCommandExecuteResult::Failed("--" + ARG_BACKUP_DIR +
  4174. ": missing backup directory");
  4175. } else {
  4176. backup_dir_ = itr->second;
  4177. }
  4178. itr = options.find(ARG_STDERR_LOG_LEVEL);
  4179. if (itr != options.end()) {
  4180. int stderr_log_level = std::stoi(itr->second);
  4181. if (stderr_log_level < 0 ||
  4182. stderr_log_level >= InfoLogLevel::NUM_INFO_LOG_LEVELS) {
  4183. exec_state_ = LDBCommandExecuteResult::Failed(
  4184. ARG_STDERR_LOG_LEVEL + " must be >= 0 and < " +
  4185. std::to_string(InfoLogLevel::NUM_INFO_LOG_LEVELS) + ".");
  4186. } else {
  4187. logger_.reset(
  4188. new StderrLogger(static_cast<InfoLogLevel>(stderr_log_level)));
  4189. }
  4190. }
  4191. }
  4192. void BackupEngineCommand::Help(const std::string& name, std::string& ret) {
  4193. ret.append(" ");
  4194. ret.append(name);
  4195. ret.append(" [--" + ARG_BACKUP_ENV_URI + " | --" + ARG_BACKUP_FS_URI + "] ");
  4196. ret.append(" [--" + ARG_BACKUP_DIR + "] ");
  4197. ret.append(" [--" + ARG_NUM_THREADS + "] ");
  4198. ret.append(" [--" + ARG_STDERR_LOG_LEVEL + "=<int (InfoLogLevel)>] ");
  4199. ret.append("\n");
  4200. }
  4201. // ----------------------------------------------------------------------------
  4202. BackupCommand::BackupCommand(const std::vector<std::string>& params,
  4203. const std::map<std::string, std::string>& options,
  4204. const std::vector<std::string>& flags)
  4205. : BackupEngineCommand(params, options, flags) {}
  4206. void BackupCommand::Help(std::string& ret) {
  4207. BackupEngineCommand::Help(Name(), ret);
  4208. }
  4209. void BackupCommand::DoCommand() {
  4210. BackupEngine* backup_engine;
  4211. Status status;
  4212. if (!db_) {
  4213. assert(GetExecuteState().IsFailed());
  4214. return;
  4215. }
  4216. fprintf(stdout, "open db OK\n");
  4217. Env* custom_env = backup_env_guard_.get();
  4218. if (custom_env == nullptr) {
  4219. Status s =
  4220. Env::CreateFromUri(config_options_, backup_env_uri_, backup_fs_uri_,
  4221. &custom_env, &backup_env_guard_);
  4222. if (!s.ok()) {
  4223. exec_state_ = LDBCommandExecuteResult::Failed(s.ToString());
  4224. return;
  4225. }
  4226. }
  4227. assert(custom_env != nullptr);
  4228. BackupEngineOptions backup_options =
  4229. BackupEngineOptions(backup_dir_, custom_env);
  4230. backup_options.info_log = logger_.get();
  4231. backup_options.max_background_operations = num_threads_;
  4232. status = BackupEngine::Open(options_.env, backup_options, &backup_engine);
  4233. if (status.ok()) {
  4234. fprintf(stdout, "open backup engine OK\n");
  4235. } else {
  4236. exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  4237. return;
  4238. }
  4239. status = backup_engine->CreateNewBackup(db_);
  4240. if (status.ok()) {
  4241. fprintf(stdout, "create new backup OK\n");
  4242. } else {
  4243. exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  4244. return;
  4245. }
  4246. }
  4247. // ----------------------------------------------------------------------------
  4248. RestoreCommand::RestoreCommand(
  4249. const std::vector<std::string>& params,
  4250. const std::map<std::string, std::string>& options,
  4251. const std::vector<std::string>& flags)
  4252. : BackupEngineCommand(params, options, flags) {}
  4253. void RestoreCommand::Help(std::string& ret) {
  4254. BackupEngineCommand::Help(Name(), ret);
  4255. }
  4256. void RestoreCommand::DoCommand() {
  4257. Env* custom_env = backup_env_guard_.get();
  4258. if (custom_env == nullptr) {
  4259. Status s =
  4260. Env::CreateFromUri(config_options_, backup_env_uri_, backup_fs_uri_,
  4261. &custom_env, &backup_env_guard_);
  4262. if (!s.ok()) {
  4263. exec_state_ = LDBCommandExecuteResult::Failed(s.ToString());
  4264. return;
  4265. }
  4266. }
  4267. assert(custom_env != nullptr);
  4268. std::unique_ptr<BackupEngineReadOnly> restore_engine;
  4269. Status status;
  4270. {
  4271. BackupEngineOptions opts(backup_dir_, custom_env);
  4272. opts.info_log = logger_.get();
  4273. opts.max_background_operations = num_threads_;
  4274. BackupEngineReadOnly* raw_restore_engine_ptr;
  4275. status =
  4276. BackupEngineReadOnly::Open(options_.env, opts, &raw_restore_engine_ptr);
  4277. if (status.ok()) {
  4278. restore_engine.reset(raw_restore_engine_ptr);
  4279. }
  4280. }
  4281. if (status.ok()) {
  4282. fprintf(stdout, "open restore engine OK\n");
  4283. status = restore_engine->RestoreDBFromLatestBackup(db_path_, db_path_);
  4284. }
  4285. if (status.ok()) {
  4286. fprintf(stdout, "restore from backup OK\n");
  4287. } else {
  4288. exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  4289. }
  4290. }
  4291. // ----------------------------------------------------------------------------
  4292. namespace {
  4293. void DumpSstFile(Options options, std::string filename, bool output_hex,
  4294. bool show_properties, bool decode_blob_index,
  4295. std::string from_key, std::string to_key) {
  4296. if (filename.length() <= 4 ||
  4297. filename.rfind(".sst") != filename.length() - 4) {
  4298. std::cout << "Invalid sst file name." << std::endl;
  4299. return;
  4300. }
  4301. // no verification
  4302. ROCKSDB_NAMESPACE::SstFileDumper dumper(
  4303. options, filename, Temperature::kUnknown,
  4304. 2 * 1024 * 1024 /* readahead_size */,
  4305. /* verify_checksum */ false, output_hex, decode_blob_index);
  4306. Status st = dumper.ReadSequential(true, std::numeric_limits<uint64_t>::max(),
  4307. !from_key.empty(), from_key,
  4308. !to_key.empty(), to_key);
  4309. if (!st.ok()) {
  4310. std::cerr << "Error in reading SST file " << filename << st.ToString()
  4311. << std::endl;
  4312. return;
  4313. }
  4314. if (show_properties) {
  4315. const ROCKSDB_NAMESPACE::TableProperties* table_properties;
  4316. std::shared_ptr<const ROCKSDB_NAMESPACE::TableProperties>
  4317. table_properties_from_reader;
  4318. st = dumper.ReadTableProperties(&table_properties_from_reader);
  4319. if (!st.ok()) {
  4320. std::cerr << filename << ": " << st.ToString()
  4321. << ". Try to use initial table properties" << std::endl;
  4322. table_properties = dumper.GetInitTableProperties();
  4323. } else {
  4324. table_properties = table_properties_from_reader.get();
  4325. }
  4326. if (table_properties != nullptr) {
  4327. std::cout << std::endl << "Table Properties:" << std::endl;
  4328. std::cout << table_properties->ToString("\n") << std::endl;
  4329. }
  4330. }
  4331. }
  4332. void DumpBlobFile(const std::string& filename, bool is_key_hex,
  4333. bool is_value_hex, bool dump_uncompressed_blobs) {
  4334. using ROCKSDB_NAMESPACE::blob_db::BlobDumpTool;
  4335. BlobDumpTool tool;
  4336. BlobDumpTool::DisplayType blob_type = is_value_hex
  4337. ? BlobDumpTool::DisplayType::kHex
  4338. : BlobDumpTool::DisplayType::kRaw;
  4339. BlobDumpTool::DisplayType show_uncompressed_blob =
  4340. dump_uncompressed_blobs ? blob_type : BlobDumpTool::DisplayType::kNone;
  4341. BlobDumpTool::DisplayType show_blob =
  4342. dump_uncompressed_blobs ? BlobDumpTool::DisplayType::kNone : blob_type;
  4343. BlobDumpTool::DisplayType show_key = is_key_hex
  4344. ? BlobDumpTool::DisplayType::kHex
  4345. : BlobDumpTool::DisplayType::kRaw;
  4346. Status s = tool.Run(filename, show_key, show_blob, show_uncompressed_blob,
  4347. /* show_summary */ true);
  4348. if (!s.ok()) {
  4349. fprintf(stderr, "Failed: %s\n", s.ToString().c_str());
  4350. }
  4351. }
  4352. Status EncodeUserProvidedTimestamp(const std::string& user_timestamp,
  4353. std::string* ts_buf) {
  4354. uint64_t int_timestamp;
  4355. std::istringstream iss(user_timestamp);
  4356. if (!(iss >> int_timestamp)) {
  4357. return Status::InvalidArgument(
  4358. "user provided timestamp is not a valid uint64 value.");
  4359. }
  4360. EncodeU64Ts(int_timestamp, ts_buf);
  4361. return Status::OK();
  4362. }
  4363. } // namespace
  4364. DBFileDumperCommand::DBFileDumperCommand(
  4365. const std::vector<std::string>& /*params*/,
  4366. const std::map<std::string, std::string>& options,
  4367. const std::vector<std::string>& flags)
  4368. : LDBCommand(options, flags, true /* is_read_only */,
  4369. BuildCmdLineOptions(
  4370. {ARG_DECODE_BLOB_INDEX, ARG_DUMP_UNCOMPRESSED_BLOBS})),
  4371. decode_blob_index_(IsFlagPresent(flags, ARG_DECODE_BLOB_INDEX)),
  4372. dump_uncompressed_blobs_(
  4373. IsFlagPresent(flags, ARG_DUMP_UNCOMPRESSED_BLOBS)) {}
  4374. void DBFileDumperCommand::Help(std::string& ret) {
  4375. ret.append(" ");
  4376. ret.append(DBFileDumperCommand::Name());
  4377. ret.append(" [--" + ARG_DECODE_BLOB_INDEX + "] ");
  4378. ret.append(" [--" + ARG_DUMP_UNCOMPRESSED_BLOBS + "] ");
  4379. ret.append("\n");
  4380. }
  4381. void DBFileDumperCommand::DoCommand() {
  4382. if (!db_) {
  4383. assert(GetExecuteState().IsFailed());
  4384. return;
  4385. }
  4386. Status s;
  4387. // TODO: Use --hex, --key_hex, --value_hex flags consistently for
  4388. // dumping manifest file, sst files and blob files.
  4389. std::cout << "Manifest File" << std::endl;
  4390. std::cout << "==============================" << std::endl;
  4391. std::string manifest_filename;
  4392. s = ReadFileToString(db_->GetEnv(), CurrentFileName(db_->GetName()),
  4393. &manifest_filename);
  4394. if (!s.ok() || manifest_filename.empty() ||
  4395. manifest_filename.back() != '\n') {
  4396. std::cerr << "Error when reading CURRENT file "
  4397. << CurrentFileName(db_->GetName()) << std::endl;
  4398. }
  4399. // remove the trailing '\n'
  4400. manifest_filename.resize(manifest_filename.size() - 1);
  4401. std::string manifest_filepath = db_->GetName() + "/" + manifest_filename;
  4402. // Correct concatenation of filepath and filename:
  4403. // Check that there is no double slashes (or more!) when concatenation
  4404. // happens.
  4405. manifest_filepath = NormalizePath(manifest_filepath);
  4406. std::cout << manifest_filepath << std::endl;
  4407. DumpManifestFile(options_, manifest_filepath, false, false, false,
  4408. column_families_);
  4409. std::cout << std::endl;
  4410. std::vector<ColumnFamilyMetaData> column_families;
  4411. db_->GetAllColumnFamilyMetaData(&column_families);
  4412. for (const auto& column_family : column_families) {
  4413. std::cout << "Column family name: " << column_family.name << std::endl;
  4414. std::cout << "==============================" << std::endl;
  4415. std::cout << std::endl;
  4416. std::cout << "SST Files" << std::endl;
  4417. std::cout << "==============================" << std::endl;
  4418. for (const LevelMetaData& level : column_family.levels) {
  4419. for (const SstFileMetaData& sst_file : level.files) {
  4420. std::string filename = sst_file.db_path + "/" + sst_file.name;
  4421. // Correct concatenation of filepath and filename:
  4422. // Check that there is no double slashes (or more!) when concatenation
  4423. // happens.
  4424. filename = NormalizePath(filename);
  4425. std::cout << filename << " level:" << level.level << std::endl;
  4426. std::cout << "------------------------------" << std::endl;
  4427. DumpSstFile(options_, filename, false, true, decode_blob_index_);
  4428. std::cout << std::endl;
  4429. }
  4430. }
  4431. std::cout << "Blob Files" << std::endl;
  4432. std::cout << "==============================" << std::endl;
  4433. for (const BlobMetaData& blob_file : column_family.blob_files) {
  4434. std::string filename =
  4435. blob_file.blob_file_path + "/" + blob_file.blob_file_name;
  4436. // Correct concatenation of filepath and filename:
  4437. // Check that there is no double slashes (or more!) when concatenation
  4438. // happens.
  4439. filename = NormalizePath(filename);
  4440. std::cout << filename << std::endl;
  4441. std::cout << "------------------------------" << std::endl;
  4442. DumpBlobFile(filename, /* is_key_hex */ false, /* is_value_hex */ false,
  4443. dump_uncompressed_blobs_);
  4444. std::cout << std::endl;
  4445. }
  4446. }
  4447. std::cout << std::endl;
  4448. std::cout << "Write Ahead Log Files" << std::endl;
  4449. std::cout << "==============================" << std::endl;
  4450. ROCKSDB_NAMESPACE::VectorWalPtr wal_files;
  4451. s = db_->GetSortedWalFiles(wal_files);
  4452. if (!s.ok()) {
  4453. std::cerr << "Error when getting WAL files" << std::endl;
  4454. } else {
  4455. std::string wal_dir;
  4456. if (options_.wal_dir.empty()) {
  4457. wal_dir = db_->GetName();
  4458. } else {
  4459. wal_dir = NormalizePath(options_.wal_dir + "/");
  4460. }
  4461. std::optional<SequenceNumber> prev_batch_seqno;
  4462. std::optional<uint32_t> prev_batch_count;
  4463. for (auto& wal : wal_files) {
  4464. // TODO(qyang): option.wal_dir should be passed into ldb command
  4465. std::string filename = wal_dir + wal->PathName();
  4466. std::cout << filename << std::endl;
  4467. // TODO(myabandeh): allow configuring is_write_commited
  4468. DumpWalFile(
  4469. options_, filename, true /* print_header */, true /* print_values */,
  4470. false /* only_print_seqno_gapstrue */, true /* is_write_commited */,
  4471. ucmps_, &exec_state_, &prev_batch_seqno, &prev_batch_count);
  4472. }
  4473. }
  4474. }
  4475. const std::string DBLiveFilesMetadataDumperCommand::ARG_SORT_BY_FILENAME =
  4476. "sort_by_filename";
  4477. DBLiveFilesMetadataDumperCommand::DBLiveFilesMetadataDumperCommand(
  4478. const std::vector<std::string>& /*params*/,
  4479. const std::map<std::string, std::string>& options,
  4480. const std::vector<std::string>& flags)
  4481. : LDBCommand(options, flags, true /* is_read_only */,
  4482. BuildCmdLineOptions({ARG_SORT_BY_FILENAME})) {
  4483. sort_by_filename_ = IsFlagPresent(flags, ARG_SORT_BY_FILENAME);
  4484. }
  4485. void DBLiveFilesMetadataDumperCommand::Help(std::string& ret) {
  4486. ret.append(" ");
  4487. ret.append(DBLiveFilesMetadataDumperCommand::Name());
  4488. ret.append(" [--" + ARG_SORT_BY_FILENAME + "] ");
  4489. ret.append("\n");
  4490. }
  4491. void DBLiveFilesMetadataDumperCommand::DoCommand() {
  4492. if (!db_) {
  4493. assert(GetExecuteState().IsFailed());
  4494. return;
  4495. }
  4496. Status s;
  4497. std::vector<ColumnFamilyMetaData> metadata;
  4498. db_->GetAllColumnFamilyMetaData(&metadata);
  4499. if (sort_by_filename_) {
  4500. std::cout << "Live SST and Blob Files:" << std::endl;
  4501. // tuple of <file path, level, column family name>
  4502. std::vector<std::tuple<std::string, int, std::string>> all_files;
  4503. for (const auto& column_metadata : metadata) {
  4504. // Iterate Levels
  4505. const auto& levels = column_metadata.levels;
  4506. const std::string& cf = column_metadata.name;
  4507. for (const auto& level_metadata : levels) {
  4508. // Iterate SST files
  4509. const auto& sst_files = level_metadata.files;
  4510. int level = level_metadata.level;
  4511. for (const auto& sst_metadata : sst_files) {
  4512. // The SstFileMetaData.name always starts with "/",
  4513. // however SstFileMetaData.db_path is the string provided by
  4514. // the user as an input. Therefore we check if we can
  4515. // concantenate the two strings directly or if we need to
  4516. // drop a possible extra "/" at the end of SstFileMetaData.db_path.
  4517. std::string filename =
  4518. NormalizePath(sst_metadata.db_path + "/" + sst_metadata.name);
  4519. all_files.emplace_back(filename, level, cf);
  4520. } // End of for-loop over sst files
  4521. } // End of for-loop over levels
  4522. const auto& blob_files = column_metadata.blob_files;
  4523. for (const auto& blob_metadata : blob_files) {
  4524. // The BlobMetaData.blob_file_name always starts with "/",
  4525. // however BlobMetaData.blob_file_path is the string provided by
  4526. // the user as an input. Therefore we check if we can
  4527. // concantenate the two strings directly or if we need to
  4528. // drop a possible extra "/" at the end of BlobMetaData.blob_file_path.
  4529. std::string filename = NormalizePath(
  4530. blob_metadata.blob_file_path + "/" + blob_metadata.blob_file_name);
  4531. // Level for blob files is encoded as -1
  4532. all_files.emplace_back(filename, -1, cf);
  4533. } // End of for-loop over blob files
  4534. } // End of for-loop over column metadata
  4535. // Sort by filename (i.e. first entry in tuple)
  4536. std::sort(all_files.begin(), all_files.end());
  4537. for (const auto& item : all_files) {
  4538. const std::string& filename = std::get<0>(item);
  4539. int level = std::get<1>(item);
  4540. const std::string& cf = std::get<2>(item);
  4541. if (level == -1) { // Blob File
  4542. std::cout << filename << ", column family '" << cf << "'" << std::endl;
  4543. } else { // SST file
  4544. std::cout << filename << " : level " << level << ", column family '"
  4545. << cf << "'" << std::endl;
  4546. }
  4547. }
  4548. } else {
  4549. for (const auto& column_metadata : metadata) {
  4550. std::cout << "===== Column Family: " << column_metadata.name
  4551. << " =====" << std::endl;
  4552. std::cout << "Live SST Files:" << std::endl;
  4553. // Iterate levels
  4554. const auto& levels = column_metadata.levels;
  4555. for (const auto& level_metadata : levels) {
  4556. std::cout << "---------- level " << level_metadata.level
  4557. << " ----------" << std::endl;
  4558. // Iterate SST files
  4559. const auto& sst_files = level_metadata.files;
  4560. for (const auto& sst_metadata : sst_files) {
  4561. // The SstFileMetaData.name always starts with "/",
  4562. // however SstFileMetaData.db_path is the string provided by
  4563. // the user as an input. Therefore we check if we can
  4564. // concantenate the two strings directly or if we need to
  4565. // drop a possible extra "/" at the end of SstFileMetaData.db_path.
  4566. std::string filename =
  4567. NormalizePath(sst_metadata.db_path + "/" + sst_metadata.name);
  4568. std::cout << filename << std::endl;
  4569. } // End of for-loop over sst files
  4570. } // End of for-loop over levels
  4571. std::cout << "Live Blob Files:" << std::endl;
  4572. const auto& blob_files = column_metadata.blob_files;
  4573. for (const auto& blob_metadata : blob_files) {
  4574. // The BlobMetaData.blob_file_name always starts with "/",
  4575. // however BlobMetaData.blob_file_path is the string provided by
  4576. // the user as an input. Therefore we check if we can
  4577. // concantenate the two strings directly or if we need to
  4578. // drop a possible extra "/" at the end of BlobMetaData.blob_file_path.
  4579. std::string filename = NormalizePath(
  4580. blob_metadata.blob_file_path + "/" + blob_metadata.blob_file_name);
  4581. std::cout << filename << std::endl;
  4582. } // End of for-loop over blob files
  4583. } // End of for-loop over column metadata
  4584. } // End of else ("not sort_by_filename")
  4585. std::cout << "------------------------------" << std::endl;
  4586. }
  4587. void WriteExternalSstFilesCommand::Help(std::string& ret) {
  4588. ret.append(" ");
  4589. ret.append(WriteExternalSstFilesCommand::Name());
  4590. ret.append(" <output_sst_path>");
  4591. ret.append("\n");
  4592. }
  4593. WriteExternalSstFilesCommand::WriteExternalSstFilesCommand(
  4594. const std::vector<std::string>& params,
  4595. const std::map<std::string, std::string>& options,
  4596. const std::vector<std::string>& flags)
  4597. : LDBCommand(
  4598. options, flags, false /* is_read_only */,
  4599. BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM,
  4600. ARG_TO, ARG_CREATE_IF_MISSING})) {
  4601. create_if_missing_ =
  4602. IsFlagPresent(flags, ARG_CREATE_IF_MISSING) ||
  4603. ParseBooleanOption(options, ARG_CREATE_IF_MISSING, false);
  4604. if (params.size() != 1) {
  4605. exec_state_ = LDBCommandExecuteResult::Failed(
  4606. "output SST file path must be specified");
  4607. } else {
  4608. output_sst_path_ = params.at(0);
  4609. }
  4610. }
  4611. void WriteExternalSstFilesCommand::DoCommand() {
  4612. if (!db_) {
  4613. assert(GetExecuteState().IsFailed());
  4614. return;
  4615. }
  4616. ColumnFamilyHandle* cfh = GetCfHandle();
  4617. SstFileWriter sst_file_writer(EnvOptions(), db_->GetOptions(), cfh);
  4618. Status status = sst_file_writer.Open(output_sst_path_);
  4619. if (!status.ok()) {
  4620. exec_state_ = LDBCommandExecuteResult::Failed("failed to open SST file: " +
  4621. status.ToString());
  4622. return;
  4623. }
  4624. int bad_lines = 0;
  4625. std::string line;
  4626. std::ifstream ifs_stdin("/dev/stdin");
  4627. std::istream* istream_p = ifs_stdin.is_open() ? &ifs_stdin : &std::cin;
  4628. while (getline(*istream_p, line, '\n')) {
  4629. std::string key;
  4630. std::string value;
  4631. if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
  4632. status = sst_file_writer.Put(key, value);
  4633. if (!status.ok()) {
  4634. exec_state_ = LDBCommandExecuteResult::Failed(
  4635. "failed to write record to file: " + status.ToString());
  4636. return;
  4637. }
  4638. } else if (0 == line.find("Keys in range:")) {
  4639. // ignore this line
  4640. } else if (0 == line.find("Created bg thread 0x")) {
  4641. // ignore this line
  4642. } else {
  4643. bad_lines++;
  4644. }
  4645. }
  4646. status = sst_file_writer.Finish();
  4647. if (!status.ok()) {
  4648. exec_state_ = LDBCommandExecuteResult::Failed(
  4649. "Failed to finish writing to file: " + status.ToString());
  4650. return;
  4651. }
  4652. if (bad_lines > 0) {
  4653. fprintf(stderr, "Warning: %d bad lines ignored.\n", bad_lines);
  4654. }
  4655. exec_state_ = LDBCommandExecuteResult::Succeed(
  4656. "external SST file written to " + output_sst_path_);
  4657. }
  4658. void WriteExternalSstFilesCommand::OverrideBaseOptions() {
  4659. LDBCommand::OverrideBaseOptions();
  4660. options_.create_if_missing = create_if_missing_;
  4661. }
  4662. const std::string IngestExternalSstFilesCommand::ARG_MOVE_FILES = "move_files";
  4663. const std::string IngestExternalSstFilesCommand::ARG_SNAPSHOT_CONSISTENCY =
  4664. "snapshot_consistency";
  4665. const std::string IngestExternalSstFilesCommand::ARG_ALLOW_GLOBAL_SEQNO =
  4666. "allow_global_seqno";
  4667. const std::string IngestExternalSstFilesCommand::ARG_ALLOW_BLOCKING_FLUSH =
  4668. "allow_blocking_flush";
  4669. const std::string IngestExternalSstFilesCommand::ARG_INGEST_BEHIND =
  4670. "ingest_behind";
  4671. const std::string IngestExternalSstFilesCommand::ARG_WRITE_GLOBAL_SEQNO =
  4672. "write_global_seqno";
  4673. void IngestExternalSstFilesCommand::Help(std::string& ret) {
  4674. ret.append(" ");
  4675. ret.append(IngestExternalSstFilesCommand::Name());
  4676. ret.append(" <input_sst_path>");
  4677. ret.append(" [--" + ARG_MOVE_FILES + "] ");
  4678. ret.append(" [--" + ARG_SNAPSHOT_CONSISTENCY + "] ");
  4679. ret.append(" [--" + ARG_ALLOW_GLOBAL_SEQNO + "] ");
  4680. ret.append(" [--" + ARG_ALLOW_BLOCKING_FLUSH + "] ");
  4681. ret.append(" [--" + ARG_INGEST_BEHIND + "] ");
  4682. ret.append(" [--" + ARG_WRITE_GLOBAL_SEQNO + "] ");
  4683. ret.append("\n");
  4684. }
  4685. IngestExternalSstFilesCommand::IngestExternalSstFilesCommand(
  4686. const std::vector<std::string>& params,
  4687. const std::map<std::string, std::string>& options,
  4688. const std::vector<std::string>& flags)
  4689. : LDBCommand(
  4690. options, flags, false /* is_read_only */,
  4691. BuildCmdLineOptions({ARG_MOVE_FILES, ARG_SNAPSHOT_CONSISTENCY,
  4692. ARG_ALLOW_GLOBAL_SEQNO, ARG_CREATE_IF_MISSING,
  4693. ARG_ALLOW_BLOCKING_FLUSH, ARG_INGEST_BEHIND,
  4694. ARG_WRITE_GLOBAL_SEQNO})),
  4695. move_files_(false),
  4696. snapshot_consistency_(true),
  4697. allow_global_seqno_(true),
  4698. allow_blocking_flush_(true),
  4699. ingest_behind_(false),
  4700. write_global_seqno_(true) {
  4701. create_if_missing_ =
  4702. IsFlagPresent(flags, ARG_CREATE_IF_MISSING) ||
  4703. ParseBooleanOption(options, ARG_CREATE_IF_MISSING, false);
  4704. move_files_ = IsFlagPresent(flags, ARG_MOVE_FILES) ||
  4705. ParseBooleanOption(options, ARG_MOVE_FILES, false);
  4706. snapshot_consistency_ =
  4707. IsFlagPresent(flags, ARG_SNAPSHOT_CONSISTENCY) ||
  4708. ParseBooleanOption(options, ARG_SNAPSHOT_CONSISTENCY, true);
  4709. allow_global_seqno_ =
  4710. IsFlagPresent(flags, ARG_ALLOW_GLOBAL_SEQNO) ||
  4711. ParseBooleanOption(options, ARG_ALLOW_GLOBAL_SEQNO, true);
  4712. allow_blocking_flush_ =
  4713. IsFlagPresent(flags, ARG_ALLOW_BLOCKING_FLUSH) ||
  4714. ParseBooleanOption(options, ARG_ALLOW_BLOCKING_FLUSH, true);
  4715. ingest_behind_ = IsFlagPresent(flags, ARG_INGEST_BEHIND) ||
  4716. ParseBooleanOption(options, ARG_INGEST_BEHIND, false);
  4717. write_global_seqno_ =
  4718. IsFlagPresent(flags, ARG_WRITE_GLOBAL_SEQNO) ||
  4719. ParseBooleanOption(options, ARG_WRITE_GLOBAL_SEQNO, true);
  4720. if (allow_global_seqno_) {
  4721. if (!write_global_seqno_) {
  4722. fprintf(stderr,
  4723. "Warning: not writing global_seqno to the ingested SST can\n"
  4724. "prevent older versions of RocksDB from being able to open it\n");
  4725. }
  4726. } else {
  4727. if (write_global_seqno_) {
  4728. exec_state_ = LDBCommandExecuteResult::Failed(
  4729. "ldb cannot write global_seqno to the ingested SST when global_seqno "
  4730. "is not allowed");
  4731. }
  4732. }
  4733. if (params.size() != 1) {
  4734. exec_state_ =
  4735. LDBCommandExecuteResult::Failed("input SST path must be specified");
  4736. } else {
  4737. input_sst_path_ = params.at(0);
  4738. }
  4739. }
  4740. void IngestExternalSstFilesCommand::DoCommand() {
  4741. if (!db_) {
  4742. assert(GetExecuteState().IsFailed());
  4743. return;
  4744. }
  4745. if (GetExecuteState().IsFailed()) {
  4746. return;
  4747. }
  4748. ColumnFamilyHandle* cfh = GetCfHandle();
  4749. IngestExternalFileOptions ifo;
  4750. ifo.move_files = move_files_;
  4751. ifo.snapshot_consistency = snapshot_consistency_;
  4752. ifo.allow_global_seqno = allow_global_seqno_;
  4753. ifo.allow_blocking_flush = allow_blocking_flush_;
  4754. ifo.ingest_behind = ingest_behind_;
  4755. ifo.write_global_seqno = write_global_seqno_;
  4756. Status status = db_->IngestExternalFile(cfh, {input_sst_path_}, ifo);
  4757. if (!status.ok()) {
  4758. exec_state_ = LDBCommandExecuteResult::Failed(
  4759. "failed to ingest external SST: " + status.ToString());
  4760. } else {
  4761. exec_state_ =
  4762. LDBCommandExecuteResult::Succeed("external SST files ingested");
  4763. }
  4764. }
  4765. void IngestExternalSstFilesCommand::OverrideBaseOptions() {
  4766. LDBCommand::OverrideBaseOptions();
  4767. options_.create_if_missing = create_if_missing_;
  4768. }
  4769. ListFileRangeDeletesCommand::ListFileRangeDeletesCommand(
  4770. const std::map<std::string, std::string>& options,
  4771. const std::vector<std::string>& flags)
  4772. : LDBCommand(options, flags, true /* is_read_only */,
  4773. BuildCmdLineOptions({ARG_MAX_KEYS})) {
  4774. auto itr = options.find(ARG_MAX_KEYS);
  4775. if (itr != options.end()) {
  4776. try {
  4777. #if defined(CYGWIN)
  4778. max_keys_ = strtol(itr->second.c_str(), 0, 10);
  4779. #else
  4780. max_keys_ = std::stoi(itr->second);
  4781. #endif
  4782. } catch (const std::invalid_argument&) {
  4783. exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
  4784. " has an invalid value");
  4785. } catch (const std::out_of_range&) {
  4786. exec_state_ = LDBCommandExecuteResult::Failed(
  4787. ARG_MAX_KEYS + " has a value out-of-range");
  4788. }
  4789. }
  4790. }
  4791. void ListFileRangeDeletesCommand::Help(std::string& ret) {
  4792. ret.append(" ");
  4793. ret.append(ListFileRangeDeletesCommand::Name());
  4794. ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
  4795. ret.append(" : print tombstones in SST files.\n");
  4796. }
  4797. void ListFileRangeDeletesCommand::DoCommand() {
  4798. if (!db_) {
  4799. assert(GetExecuteState().IsFailed());
  4800. return;
  4801. }
  4802. DBImpl* db_impl = static_cast_with_check<DBImpl>(db_->GetRootDB());
  4803. std::string out_str;
  4804. Status st =
  4805. db_impl->TablesRangeTombstoneSummary(GetCfHandle(), max_keys_, &out_str);
  4806. if (st.ok()) {
  4807. TEST_SYNC_POINT_CALLBACK(
  4808. "ListFileRangeDeletesCommand::DoCommand:BeforePrint", &out_str);
  4809. fprintf(stdout, "%s\n", out_str.c_str());
  4810. }
  4811. }
  4812. void UnsafeRemoveSstFileCommand::Help(std::string& ret) {
  4813. ret.append(" ");
  4814. ret.append(UnsafeRemoveSstFileCommand::Name());
  4815. ret.append(" <SST file number>");
  4816. ret.append(" ");
  4817. ret.append(" MUST NOT be used on a live DB.");
  4818. ret.append("\n");
  4819. }
  4820. UnsafeRemoveSstFileCommand::UnsafeRemoveSstFileCommand(
  4821. const std::vector<std::string>& params,
  4822. const std::map<std::string, std::string>& options,
  4823. const std::vector<std::string>& flags)
  4824. : LDBCommand(options, flags, false /* is_read_only */,
  4825. BuildCmdLineOptions({})) {
  4826. if (params.size() != 1) {
  4827. exec_state_ =
  4828. LDBCommandExecuteResult::Failed("SST file number must be specified");
  4829. } else {
  4830. char* endptr = nullptr;
  4831. sst_file_number_ = strtoull(params.at(0).c_str(), &endptr, 10 /* base */);
  4832. if (endptr == nullptr || *endptr != '\0') {
  4833. exec_state_ = LDBCommandExecuteResult::Failed(
  4834. "Failed to parse SST file number " + params.at(0));
  4835. }
  4836. }
  4837. }
  4838. void UnsafeRemoveSstFileCommand::DoCommand() {
  4839. // TODO: plumb Env::IOActivity, Env::IOPriority
  4840. const ReadOptions read_options;
  4841. const WriteOptions write_options;
  4842. PrepareOptions();
  4843. OfflineManifestWriter w(options_, db_path_);
  4844. if (column_families_.empty()) {
  4845. column_families_.emplace_back(kDefaultColumnFamilyName, options_);
  4846. }
  4847. Status s = w.Recover(column_families_);
  4848. ColumnFamilyData* cfd = nullptr;
  4849. int level = -1;
  4850. if (s.ok()) {
  4851. FileMetaData* metadata = nullptr;
  4852. s = w.Versions().GetMetadataForFile(sst_file_number_, &level, &metadata,
  4853. &cfd);
  4854. }
  4855. if (s.ok()) {
  4856. VersionEdit edit;
  4857. edit.SetColumnFamily(cfd->GetID());
  4858. edit.DeleteFile(level, sst_file_number_);
  4859. std::unique_ptr<FSDirectory> db_dir;
  4860. s = options_.env->GetFileSystem()->NewDirectory(db_path_, IOOptions(),
  4861. &db_dir, nullptr);
  4862. if (s.ok()) {
  4863. s = w.LogAndApply(read_options, write_options, cfd, &edit, db_dir.get());
  4864. }
  4865. }
  4866. if (!s.ok()) {
  4867. exec_state_ = LDBCommandExecuteResult::Failed(
  4868. "failed to unsafely remove SST file: " + s.ToString());
  4869. } else {
  4870. exec_state_ = LDBCommandExecuteResult::Succeed("unsafely removed SST file");
  4871. }
  4872. }
  4873. const std::string UpdateManifestCommand::ARG_VERBOSE = "verbose";
  4874. const std::string UpdateManifestCommand::ARG_UPDATE_TEMPERATURES =
  4875. "update_temperatures";
  4876. void UpdateManifestCommand::Help(std::string& ret) {
  4877. ret.append(" ");
  4878. ret.append(UpdateManifestCommand::Name());
  4879. ret.append(" [--update_temperatures]");
  4880. ret.append(" ");
  4881. ret.append(" MUST NOT be used on a live DB.");
  4882. ret.append("\n");
  4883. }
  4884. UpdateManifestCommand::UpdateManifestCommand(
  4885. const std::vector<std::string>& /*params*/,
  4886. const std::map<std::string, std::string>& options,
  4887. const std::vector<std::string>& flags)
  4888. : LDBCommand(options, flags, false /* is_read_only */,
  4889. BuildCmdLineOptions({ARG_VERBOSE, ARG_UPDATE_TEMPERATURES})) {
  4890. verbose_ = IsFlagPresent(flags, ARG_VERBOSE) ||
  4891. ParseBooleanOption(options, ARG_VERBOSE, false);
  4892. update_temperatures_ =
  4893. IsFlagPresent(flags, ARG_UPDATE_TEMPERATURES) ||
  4894. ParseBooleanOption(options, ARG_UPDATE_TEMPERATURES, false);
  4895. if (!update_temperatures_) {
  4896. exec_state_ = LDBCommandExecuteResult::Failed(
  4897. "No action like --update_temperatures specified for update_manifest");
  4898. }
  4899. }
  4900. void UpdateManifestCommand::DoCommand() {
  4901. PrepareOptions();
  4902. auto level = verbose_ ? InfoLogLevel::INFO_LEVEL : InfoLogLevel::WARN_LEVEL;
  4903. options_.info_log.reset(new StderrLogger(level));
  4904. experimental::UpdateManifestForFilesStateOptions opts;
  4905. opts.update_temperatures = update_temperatures_;
  4906. if (column_families_.empty()) {
  4907. column_families_.emplace_back(kDefaultColumnFamilyName, options_);
  4908. }
  4909. Status s = experimental::UpdateManifestForFilesState(options_, db_path_,
  4910. column_families_);
  4911. if (!s.ok()) {
  4912. exec_state_ = LDBCommandExecuteResult::Failed(
  4913. "failed to update manifest: " + s.ToString());
  4914. } else {
  4915. exec_state_ =
  4916. LDBCommandExecuteResult::Succeed("Manifest updates successful");
  4917. }
  4918. }
  4919. const std::string CompactionProgressDumpCommand::ARG_PATH = "path";
  4920. CompactionProgressDumpCommand::CompactionProgressDumpCommand(
  4921. const std::vector<std::string>& /*params*/,
  4922. const std::map<std::string, std::string>& options,
  4923. const std::vector<std::string>& flags)
  4924. : LDBCommand(options, flags, false, BuildCmdLineOptions({ARG_PATH})) {
  4925. auto itr = options.find(ARG_PATH);
  4926. if (itr != options.end()) {
  4927. path_ = itr->second;
  4928. } else {
  4929. path_ = "";
  4930. }
  4931. if (path_.empty()) {
  4932. exec_state_ = LDBCommandExecuteResult::Failed(
  4933. "The --path option is required for compaction_progress_dump command");
  4934. }
  4935. }
  4936. void CompactionProgressDumpCommand::Help(std::string& ret) {
  4937. ret.append(" ");
  4938. ret.append(CompactionProgressDumpCommand::Name());
  4939. ret.append(" [--" + ARG_PATH + "=<path_to_compaction_progress_file>]");
  4940. ret.append("\n");
  4941. }
  4942. void CompactionProgressDumpCommand::DoCommand() {
  4943. DumpCompactionProgressFile(path_);
  4944. }
  4945. } // namespace ROCKSDB_NAMESPACE