ldb_cmd.cc 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437
  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. #ifndef ROCKSDB_LITE
  7. #include "rocksdb/utilities/ldb_cmd.h"
  8. #include <cinttypes>
  9. #include "db/db_impl/db_impl.h"
  10. #include "db/dbformat.h"
  11. #include "db/log_reader.h"
  12. #include "db/write_batch_internal.h"
  13. #include "env/composite_env_wrapper.h"
  14. #include "file/filename.h"
  15. #include "port/port_dirent.h"
  16. #include "rocksdb/cache.h"
  17. #include "rocksdb/file_checksum.h"
  18. #include "rocksdb/table_properties.h"
  19. #include "rocksdb/utilities/backupable_db.h"
  20. #include "rocksdb/utilities/checkpoint.h"
  21. #include "rocksdb/utilities/debug.h"
  22. #include "rocksdb/utilities/options_util.h"
  23. #include "rocksdb/write_batch.h"
  24. #include "rocksdb/write_buffer_manager.h"
  25. #include "table/scoped_arena_iterator.h"
  26. #include "tools/ldb_cmd_impl.h"
  27. #include "tools/sst_dump_tool_imp.h"
  28. #include "util/cast_util.h"
  29. #include "util/coding.h"
  30. #include "util/file_checksum_helper.h"
  31. #include "util/stderr_logger.h"
  32. #include "util/string_util.h"
  33. #include "utilities/merge_operators.h"
  34. #include "utilities/ttl/db_ttl_impl.h"
  35. #include <cstdlib>
  36. #include <ctime>
  37. #include <fstream>
  38. #include <functional>
  39. #include <iostream>
  40. #include <limits>
  41. #include <sstream>
  42. #include <stdexcept>
  43. #include <string>
  44. namespace ROCKSDB_NAMESPACE {
  45. class FileChecksumFuncCrc32c;
  46. const std::string LDBCommand::ARG_ENV_URI = "env_uri";
  47. const std::string LDBCommand::ARG_DB = "db";
  48. const std::string LDBCommand::ARG_PATH = "path";
  49. const std::string LDBCommand::ARG_SECONDARY_PATH = "secondary_path";
  50. const std::string LDBCommand::ARG_HEX = "hex";
  51. const std::string LDBCommand::ARG_KEY_HEX = "key_hex";
  52. const std::string LDBCommand::ARG_VALUE_HEX = "value_hex";
  53. const std::string LDBCommand::ARG_CF_NAME = "column_family";
  54. const std::string LDBCommand::ARG_TTL = "ttl";
  55. const std::string LDBCommand::ARG_TTL_START = "start_time";
  56. const std::string LDBCommand::ARG_TTL_END = "end_time";
  57. const std::string LDBCommand::ARG_TIMESTAMP = "timestamp";
  58. const std::string LDBCommand::ARG_TRY_LOAD_OPTIONS = "try_load_options";
  59. const std::string LDBCommand::ARG_IGNORE_UNKNOWN_OPTIONS =
  60. "ignore_unknown_options";
  61. const std::string LDBCommand::ARG_FROM = "from";
  62. const std::string LDBCommand::ARG_TO = "to";
  63. const std::string LDBCommand::ARG_MAX_KEYS = "max_keys";
  64. const std::string LDBCommand::ARG_BLOOM_BITS = "bloom_bits";
  65. const std::string LDBCommand::ARG_FIX_PREFIX_LEN = "fix_prefix_len";
  66. const std::string LDBCommand::ARG_COMPRESSION_TYPE = "compression_type";
  67. const std::string LDBCommand::ARG_COMPRESSION_MAX_DICT_BYTES =
  68. "compression_max_dict_bytes";
  69. const std::string LDBCommand::ARG_BLOCK_SIZE = "block_size";
  70. const std::string LDBCommand::ARG_AUTO_COMPACTION = "auto_compaction";
  71. const std::string LDBCommand::ARG_DB_WRITE_BUFFER_SIZE = "db_write_buffer_size";
  72. const std::string LDBCommand::ARG_WRITE_BUFFER_SIZE = "write_buffer_size";
  73. const std::string LDBCommand::ARG_FILE_SIZE = "file_size";
  74. const std::string LDBCommand::ARG_CREATE_IF_MISSING = "create_if_missing";
  75. const std::string LDBCommand::ARG_NO_VALUE = "no_value";
  76. const char* LDBCommand::DELIM = " ==> ";
  77. namespace {
  78. void DumpWalFile(Options options, std::string wal_file, bool print_header,
  79. bool print_values, bool is_write_committed,
  80. LDBCommandExecuteResult* exec_state);
  81. void DumpSstFile(Options options, std::string filename, bool output_hex,
  82. bool show_properties);
  83. };
  84. LDBCommand* LDBCommand::InitFromCmdLineArgs(
  85. int argc, char** argv, const Options& options,
  86. const LDBOptions& ldb_options,
  87. const std::vector<ColumnFamilyDescriptor>* column_families) {
  88. std::vector<std::string> args;
  89. for (int i = 1; i < argc; i++) {
  90. args.push_back(argv[i]);
  91. }
  92. return InitFromCmdLineArgs(args, options, ldb_options, column_families,
  93. SelectCommand);
  94. }
  95. /**
  96. * Parse the command-line arguments and create the appropriate LDBCommand2
  97. * instance.
  98. * The command line arguments must be in the following format:
  99. * ./ldb --db=PATH_TO_DB [--commonOpt1=commonOpt1Val] ..
  100. * COMMAND <PARAM1> <PARAM2> ... [-cmdSpecificOpt1=cmdSpecificOpt1Val] ..
  101. * This is similar to the command line format used by HBaseClientTool.
  102. * Command name is not included in args.
  103. * Returns nullptr if the command-line cannot be parsed.
  104. */
  105. LDBCommand* LDBCommand::InitFromCmdLineArgs(
  106. const std::vector<std::string>& args, const Options& options,
  107. const LDBOptions& ldb_options,
  108. const std::vector<ColumnFamilyDescriptor>* /*column_families*/,
  109. const std::function<LDBCommand*(const ParsedParams&)>& selector) {
  110. // --x=y command line arguments are added as x->y map entries in
  111. // parsed_params.option_map.
  112. //
  113. // Command-line arguments of the form --hex end up in this array as hex to
  114. // parsed_params.flags
  115. ParsedParams parsed_params;
  116. // Everything other than option_map and flags. Represents commands
  117. // and their parameters. For eg: put key1 value1 go into this vector.
  118. std::vector<std::string> cmdTokens;
  119. const std::string OPTION_PREFIX = "--";
  120. for (const auto& arg : args) {
  121. if (arg[0] == '-' && arg[1] == '-'){
  122. std::vector<std::string> splits = StringSplit(arg, '=');
  123. // --option_name=option_value
  124. if (splits.size() == 2) {
  125. std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
  126. parsed_params.option_map[optionKey] = splits[1];
  127. } else if (splits.size() == 1) {
  128. // --flag_name
  129. std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
  130. parsed_params.flags.push_back(optionKey);
  131. } else {
  132. // --option_name=option_value, option_value contains '='
  133. std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
  134. parsed_params.option_map[optionKey] =
  135. arg.substr(splits[0].length() + 1);
  136. }
  137. } else {
  138. cmdTokens.push_back(arg);
  139. }
  140. }
  141. if (cmdTokens.size() < 1) {
  142. fprintf(stderr, "Command not specified!");
  143. return nullptr;
  144. }
  145. parsed_params.cmd = cmdTokens[0];
  146. parsed_params.cmd_params.assign(cmdTokens.begin() + 1, cmdTokens.end());
  147. LDBCommand* command = selector(parsed_params);
  148. if (command) {
  149. command->SetDBOptions(options);
  150. command->SetLDBOptions(ldb_options);
  151. }
  152. return command;
  153. }
  154. LDBCommand* LDBCommand::SelectCommand(const ParsedParams& parsed_params) {
  155. if (parsed_params.cmd == GetCommand::Name()) {
  156. return new GetCommand(parsed_params.cmd_params, parsed_params.option_map,
  157. parsed_params.flags);
  158. } else if (parsed_params.cmd == PutCommand::Name()) {
  159. return new PutCommand(parsed_params.cmd_params, parsed_params.option_map,
  160. parsed_params.flags);
  161. } else if (parsed_params.cmd == BatchPutCommand::Name()) {
  162. return new BatchPutCommand(parsed_params.cmd_params,
  163. parsed_params.option_map, parsed_params.flags);
  164. } else if (parsed_params.cmd == ScanCommand::Name()) {
  165. return new ScanCommand(parsed_params.cmd_params, parsed_params.option_map,
  166. parsed_params.flags);
  167. } else if (parsed_params.cmd == DeleteCommand::Name()) {
  168. return new DeleteCommand(parsed_params.cmd_params, parsed_params.option_map,
  169. parsed_params.flags);
  170. } else if (parsed_params.cmd == DeleteRangeCommand::Name()) {
  171. return new DeleteRangeCommand(parsed_params.cmd_params,
  172. parsed_params.option_map,
  173. parsed_params.flags);
  174. } else if (parsed_params.cmd == ApproxSizeCommand::Name()) {
  175. return new ApproxSizeCommand(parsed_params.cmd_params,
  176. parsed_params.option_map, parsed_params.flags);
  177. } else if (parsed_params.cmd == DBQuerierCommand::Name()) {
  178. return new DBQuerierCommand(parsed_params.cmd_params,
  179. parsed_params.option_map, parsed_params.flags);
  180. } else if (parsed_params.cmd == CompactorCommand::Name()) {
  181. return new CompactorCommand(parsed_params.cmd_params,
  182. parsed_params.option_map, parsed_params.flags);
  183. } else if (parsed_params.cmd == WALDumperCommand::Name()) {
  184. return new WALDumperCommand(parsed_params.cmd_params,
  185. parsed_params.option_map, parsed_params.flags);
  186. } else if (parsed_params.cmd == ReduceDBLevelsCommand::Name()) {
  187. return new ReduceDBLevelsCommand(parsed_params.cmd_params,
  188. parsed_params.option_map,
  189. parsed_params.flags);
  190. } else if (parsed_params.cmd == ChangeCompactionStyleCommand::Name()) {
  191. return new ChangeCompactionStyleCommand(parsed_params.cmd_params,
  192. parsed_params.option_map,
  193. parsed_params.flags);
  194. } else if (parsed_params.cmd == DBDumperCommand::Name()) {
  195. return new DBDumperCommand(parsed_params.cmd_params,
  196. parsed_params.option_map, parsed_params.flags);
  197. } else if (parsed_params.cmd == DBLoaderCommand::Name()) {
  198. return new DBLoaderCommand(parsed_params.cmd_params,
  199. parsed_params.option_map, parsed_params.flags);
  200. } else if (parsed_params.cmd == ManifestDumpCommand::Name()) {
  201. return new ManifestDumpCommand(parsed_params.cmd_params,
  202. parsed_params.option_map,
  203. parsed_params.flags);
  204. } else if (parsed_params.cmd == FileChecksumDumpCommand::Name()) {
  205. return new FileChecksumDumpCommand(parsed_params.cmd_params,
  206. parsed_params.option_map,
  207. parsed_params.flags);
  208. } else if (parsed_params.cmd == ListColumnFamiliesCommand::Name()) {
  209. return new ListColumnFamiliesCommand(parsed_params.cmd_params,
  210. parsed_params.option_map,
  211. parsed_params.flags);
  212. } else if (parsed_params.cmd == CreateColumnFamilyCommand::Name()) {
  213. return new CreateColumnFamilyCommand(parsed_params.cmd_params,
  214. parsed_params.option_map,
  215. parsed_params.flags);
  216. } else if (parsed_params.cmd == DropColumnFamilyCommand::Name()) {
  217. return new DropColumnFamilyCommand(parsed_params.cmd_params,
  218. parsed_params.option_map,
  219. parsed_params.flags);
  220. } else if (parsed_params.cmd == DBFileDumperCommand::Name()) {
  221. return new DBFileDumperCommand(parsed_params.cmd_params,
  222. parsed_params.option_map,
  223. parsed_params.flags);
  224. } else if (parsed_params.cmd == InternalDumpCommand::Name()) {
  225. return new InternalDumpCommand(parsed_params.cmd_params,
  226. parsed_params.option_map,
  227. parsed_params.flags);
  228. } else if (parsed_params.cmd == CheckConsistencyCommand::Name()) {
  229. return new CheckConsistencyCommand(parsed_params.cmd_params,
  230. parsed_params.option_map,
  231. parsed_params.flags);
  232. } else if (parsed_params.cmd == CheckPointCommand::Name()) {
  233. return new CheckPointCommand(parsed_params.cmd_params,
  234. parsed_params.option_map,
  235. parsed_params.flags);
  236. } else if (parsed_params.cmd == RepairCommand::Name()) {
  237. return new RepairCommand(parsed_params.cmd_params, parsed_params.option_map,
  238. parsed_params.flags);
  239. } else if (parsed_params.cmd == BackupCommand::Name()) {
  240. return new BackupCommand(parsed_params.cmd_params, parsed_params.option_map,
  241. parsed_params.flags);
  242. } else if (parsed_params.cmd == RestoreCommand::Name()) {
  243. return new RestoreCommand(parsed_params.cmd_params,
  244. parsed_params.option_map, parsed_params.flags);
  245. } else if (parsed_params.cmd == WriteExternalSstFilesCommand::Name()) {
  246. return new WriteExternalSstFilesCommand(parsed_params.cmd_params,
  247. parsed_params.option_map,
  248. parsed_params.flags);
  249. } else if (parsed_params.cmd == IngestExternalSstFilesCommand::Name()) {
  250. return new IngestExternalSstFilesCommand(parsed_params.cmd_params,
  251. parsed_params.option_map,
  252. parsed_params.flags);
  253. } else if (parsed_params.cmd == ListFileRangeDeletesCommand::Name()) {
  254. return new ListFileRangeDeletesCommand(parsed_params.option_map,
  255. parsed_params.flags);
  256. }
  257. return nullptr;
  258. }
  259. /* Run the command, and return the execute result. */
  260. void LDBCommand::Run() {
  261. if (!exec_state_.IsNotStarted()) {
  262. return;
  263. }
  264. if (!options_.env || options_.env == Env::Default()) {
  265. Env* env = Env::Default();
  266. Status s = Env::LoadEnv(env_uri_, &env, &env_guard_);
  267. if (!s.ok() && !s.IsNotFound()) {
  268. fprintf(stderr, "LoadEnv: %s\n", s.ToString().c_str());
  269. exec_state_ = LDBCommandExecuteResult::Failed(s.ToString());
  270. return;
  271. }
  272. options_.env = env;
  273. }
  274. options_.file_system.reset(new LegacyFileSystemWrapper(options_.env));
  275. if (db_ == nullptr && !NoDBOpen()) {
  276. OpenDB();
  277. if (exec_state_.IsFailed() && try_load_options_) {
  278. // We don't always return if there is a failure because a WAL file or
  279. // manifest file can be given to "dump" command so we should continue.
  280. // --try_load_options is not valid in those cases.
  281. return;
  282. }
  283. }
  284. // We'll intentionally proceed even if the DB can't be opened because users
  285. // can also specify a filename, not just a directory.
  286. DoCommand();
  287. if (exec_state_.IsNotStarted()) {
  288. exec_state_ = LDBCommandExecuteResult::Succeed("");
  289. }
  290. if (db_ != nullptr) {
  291. CloseDB();
  292. }
  293. }
  294. LDBCommand::LDBCommand(const std::map<std::string, std::string>& options,
  295. const std::vector<std::string>& flags, bool is_read_only,
  296. const std::vector<std::string>& valid_cmd_line_options)
  297. : db_(nullptr),
  298. db_ttl_(nullptr),
  299. is_read_only_(is_read_only),
  300. is_key_hex_(false),
  301. is_value_hex_(false),
  302. is_db_ttl_(false),
  303. timestamp_(false),
  304. try_load_options_(false),
  305. ignore_unknown_options_(false),
  306. create_if_missing_(false),
  307. option_map_(options),
  308. flags_(flags),
  309. valid_cmd_line_options_(valid_cmd_line_options) {
  310. std::map<std::string, std::string>::const_iterator itr = options.find(ARG_DB);
  311. if (itr != options.end()) {
  312. db_path_ = itr->second;
  313. }
  314. itr = options.find(ARG_ENV_URI);
  315. if (itr != options.end()) {
  316. env_uri_ = itr->second;
  317. }
  318. itr = options.find(ARG_CF_NAME);
  319. if (itr != options.end()) {
  320. column_family_name_ = itr->second;
  321. } else {
  322. column_family_name_ = kDefaultColumnFamilyName;
  323. }
  324. itr = options.find(ARG_SECONDARY_PATH);
  325. secondary_path_ = "";
  326. if (itr != options.end()) {
  327. secondary_path_ = itr->second;
  328. }
  329. is_key_hex_ = IsKeyHex(options, flags);
  330. is_value_hex_ = IsValueHex(options, flags);
  331. is_db_ttl_ = IsFlagPresent(flags, ARG_TTL);
  332. timestamp_ = IsFlagPresent(flags, ARG_TIMESTAMP);
  333. try_load_options_ = IsFlagPresent(flags, ARG_TRY_LOAD_OPTIONS);
  334. ignore_unknown_options_ = IsFlagPresent(flags, ARG_IGNORE_UNKNOWN_OPTIONS);
  335. }
  336. void LDBCommand::OpenDB() {
  337. if (!create_if_missing_ && try_load_options_) {
  338. Status s = LoadLatestOptions(db_path_, options_.env, &options_,
  339. &column_families_, ignore_unknown_options_);
  340. if (!s.ok() && !s.IsNotFound()) {
  341. // Option file exists but load option file error.
  342. std::string msg = s.ToString();
  343. exec_state_ = LDBCommandExecuteResult::Failed(msg);
  344. db_ = nullptr;
  345. return;
  346. }
  347. if (options_.env->FileExists(options_.wal_dir).IsNotFound()) {
  348. options_.wal_dir = db_path_;
  349. fprintf(
  350. stderr,
  351. "wal_dir loaded from the option file doesn't exist. Ignore it.\n");
  352. }
  353. // If merge operator is not set, set a string append operator. There is
  354. // no harm doing it.
  355. for (auto& cf_entry : column_families_) {
  356. if (!cf_entry.options.merge_operator) {
  357. cf_entry.options.merge_operator =
  358. MergeOperators::CreateStringAppendOperator(':');
  359. }
  360. }
  361. }
  362. options_ = PrepareOptionsForOpenDB();
  363. if (!exec_state_.IsNotStarted()) {
  364. return;
  365. }
  366. if (column_families_.empty() && !options_.merge_operator) {
  367. // No harm to add a general merge operator if it is not specified.
  368. options_.merge_operator = MergeOperators::CreateStringAppendOperator(':');
  369. }
  370. // Open the DB.
  371. Status st;
  372. std::vector<ColumnFamilyHandle*> handles_opened;
  373. if (is_db_ttl_) {
  374. // ldb doesn't yet support TTL DB with multiple column families
  375. if (!column_family_name_.empty() || !column_families_.empty()) {
  376. exec_state_ = LDBCommandExecuteResult::Failed(
  377. "ldb doesn't support TTL DB with multiple column families");
  378. }
  379. if (!secondary_path_.empty()) {
  380. exec_state_ = LDBCommandExecuteResult::Failed(
  381. "Open as secondary is not supported for TTL DB yet.");
  382. }
  383. if (is_read_only_) {
  384. st = DBWithTTL::Open(options_, db_path_, &db_ttl_, 0, true);
  385. } else {
  386. st = DBWithTTL::Open(options_, db_path_, &db_ttl_);
  387. }
  388. db_ = db_ttl_;
  389. } else {
  390. if (column_families_.empty()) {
  391. // Try to figure out column family lists
  392. std::vector<std::string> cf_list;
  393. st = DB::ListColumnFamilies(options_, db_path_, &cf_list);
  394. // There is possible the DB doesn't exist yet, for "create if not
  395. // "existing case". The failure is ignored here. We rely on DB::Open()
  396. // to give us the correct error message for problem with opening
  397. // existing DB.
  398. if (st.ok() && cf_list.size() > 1) {
  399. // Ignore single column family DB.
  400. for (auto cf_name : cf_list) {
  401. column_families_.emplace_back(cf_name, options_);
  402. }
  403. }
  404. }
  405. if (is_read_only_ && secondary_path_.empty()) {
  406. if (column_families_.empty()) {
  407. st = DB::OpenForReadOnly(options_, db_path_, &db_);
  408. } else {
  409. st = DB::OpenForReadOnly(options_, db_path_, column_families_,
  410. &handles_opened, &db_);
  411. }
  412. } else {
  413. if (column_families_.empty()) {
  414. if (secondary_path_.empty()) {
  415. st = DB::Open(options_, db_path_, &db_);
  416. } else {
  417. st = DB::OpenAsSecondary(options_, db_path_, secondary_path_, &db_);
  418. }
  419. } else {
  420. if (secondary_path_.empty()) {
  421. st = DB::Open(options_, db_path_, column_families_, &handles_opened,
  422. &db_);
  423. } else {
  424. st = DB::OpenAsSecondary(options_, db_path_, secondary_path_,
  425. column_families_, &handles_opened, &db_);
  426. }
  427. }
  428. }
  429. }
  430. if (!st.ok()) {
  431. std::string msg = st.ToString();
  432. exec_state_ = LDBCommandExecuteResult::Failed(msg);
  433. } else if (!handles_opened.empty()) {
  434. assert(handles_opened.size() == column_families_.size());
  435. bool found_cf_name = false;
  436. for (size_t i = 0; i < handles_opened.size(); i++) {
  437. cf_handles_[column_families_[i].name] = handles_opened[i];
  438. if (column_family_name_ == column_families_[i].name) {
  439. found_cf_name = true;
  440. }
  441. }
  442. if (!found_cf_name) {
  443. exec_state_ = LDBCommandExecuteResult::Failed(
  444. "Non-existing column family " + column_family_name_);
  445. CloseDB();
  446. }
  447. } else {
  448. // We successfully opened DB in single column family mode.
  449. assert(column_families_.empty());
  450. if (column_family_name_ != kDefaultColumnFamilyName) {
  451. exec_state_ = LDBCommandExecuteResult::Failed(
  452. "Non-existing column family " + column_family_name_);
  453. CloseDB();
  454. }
  455. }
  456. }
  457. void LDBCommand::CloseDB() {
  458. if (db_ != nullptr) {
  459. for (auto& pair : cf_handles_) {
  460. delete pair.second;
  461. }
  462. delete db_;
  463. db_ = nullptr;
  464. }
  465. }
  466. ColumnFamilyHandle* LDBCommand::GetCfHandle() {
  467. if (!cf_handles_.empty()) {
  468. auto it = cf_handles_.find(column_family_name_);
  469. if (it == cf_handles_.end()) {
  470. exec_state_ = LDBCommandExecuteResult::Failed(
  471. "Cannot find column family " + column_family_name_);
  472. } else {
  473. return it->second;
  474. }
  475. }
  476. return db_->DefaultColumnFamily();
  477. }
  478. std::vector<std::string> LDBCommand::BuildCmdLineOptions(
  479. std::vector<std::string> options) {
  480. std::vector<std::string> ret = {ARG_ENV_URI,
  481. ARG_DB,
  482. ARG_SECONDARY_PATH,
  483. ARG_BLOOM_BITS,
  484. ARG_BLOCK_SIZE,
  485. ARG_AUTO_COMPACTION,
  486. ARG_COMPRESSION_TYPE,
  487. ARG_COMPRESSION_MAX_DICT_BYTES,
  488. ARG_WRITE_BUFFER_SIZE,
  489. ARG_FILE_SIZE,
  490. ARG_FIX_PREFIX_LEN,
  491. ARG_TRY_LOAD_OPTIONS,
  492. ARG_IGNORE_UNKNOWN_OPTIONS,
  493. ARG_CF_NAME};
  494. ret.insert(ret.end(), options.begin(), options.end());
  495. return ret;
  496. }
  497. /**
  498. * Parses the specific integer option and fills in the value.
  499. * Returns true if the option is found.
  500. * Returns false if the option is not found or if there is an error parsing the
  501. * value. If there is an error, the specified exec_state is also
  502. * updated.
  503. */
  504. bool LDBCommand::ParseIntOption(
  505. const std::map<std::string, std::string>& /*options*/,
  506. const std::string& option, int& value,
  507. LDBCommandExecuteResult& exec_state) {
  508. std::map<std::string, std::string>::const_iterator itr =
  509. option_map_.find(option);
  510. if (itr != option_map_.end()) {
  511. try {
  512. #if defined(CYGWIN)
  513. value = strtol(itr->second.c_str(), 0, 10);
  514. #else
  515. value = std::stoi(itr->second);
  516. #endif
  517. return true;
  518. } catch (const std::invalid_argument&) {
  519. exec_state =
  520. LDBCommandExecuteResult::Failed(option + " has an invalid value.");
  521. } catch (const std::out_of_range&) {
  522. exec_state = LDBCommandExecuteResult::Failed(
  523. option + " has a value out-of-range.");
  524. }
  525. }
  526. return false;
  527. }
  528. /**
  529. * Parses the specified option and fills in the value.
  530. * Returns true if the option is found.
  531. * Returns false otherwise.
  532. */
  533. bool LDBCommand::ParseStringOption(
  534. const std::map<std::string, std::string>& /*options*/,
  535. const std::string& option, std::string* value) {
  536. auto itr = option_map_.find(option);
  537. if (itr != option_map_.end()) {
  538. *value = itr->second;
  539. return true;
  540. }
  541. return false;
  542. }
  543. Options LDBCommand::PrepareOptionsForOpenDB() {
  544. ColumnFamilyOptions* cf_opts;
  545. auto column_families_iter =
  546. std::find_if(column_families_.begin(), column_families_.end(),
  547. [this](const ColumnFamilyDescriptor& cf_desc) {
  548. return cf_desc.name == column_family_name_;
  549. });
  550. if (column_families_iter != column_families_.end()) {
  551. cf_opts = &column_families_iter->options;
  552. } else {
  553. cf_opts = static_cast<ColumnFamilyOptions*>(&options_);
  554. }
  555. DBOptions* db_opts = static_cast<DBOptions*>(&options_);
  556. db_opts->create_if_missing = false;
  557. std::map<std::string, std::string>::const_iterator itr;
  558. BlockBasedTableOptions table_options;
  559. bool use_table_options = false;
  560. int bits;
  561. if (ParseIntOption(option_map_, ARG_BLOOM_BITS, bits, exec_state_)) {
  562. if (bits > 0) {
  563. use_table_options = true;
  564. table_options.filter_policy.reset(NewBloomFilterPolicy(bits));
  565. } else {
  566. exec_state_ =
  567. LDBCommandExecuteResult::Failed(ARG_BLOOM_BITS + " must be > 0.");
  568. }
  569. }
  570. int block_size;
  571. if (ParseIntOption(option_map_, ARG_BLOCK_SIZE, block_size, exec_state_)) {
  572. if (block_size > 0) {
  573. use_table_options = true;
  574. table_options.block_size = block_size;
  575. } else {
  576. exec_state_ =
  577. LDBCommandExecuteResult::Failed(ARG_BLOCK_SIZE + " must be > 0.");
  578. }
  579. }
  580. if (use_table_options) {
  581. cf_opts->table_factory.reset(NewBlockBasedTableFactory(table_options));
  582. }
  583. itr = option_map_.find(ARG_AUTO_COMPACTION);
  584. if (itr != option_map_.end()) {
  585. cf_opts->disable_auto_compactions = !StringToBool(itr->second);
  586. }
  587. itr = option_map_.find(ARG_COMPRESSION_TYPE);
  588. if (itr != option_map_.end()) {
  589. std::string comp = itr->second;
  590. if (comp == "no") {
  591. cf_opts->compression = kNoCompression;
  592. } else if (comp == "snappy") {
  593. cf_opts->compression = kSnappyCompression;
  594. } else if (comp == "zlib") {
  595. cf_opts->compression = kZlibCompression;
  596. } else if (comp == "bzip2") {
  597. cf_opts->compression = kBZip2Compression;
  598. } else if (comp == "lz4") {
  599. cf_opts->compression = kLZ4Compression;
  600. } else if (comp == "lz4hc") {
  601. cf_opts->compression = kLZ4HCCompression;
  602. } else if (comp == "xpress") {
  603. cf_opts->compression = kXpressCompression;
  604. } else if (comp == "zstd") {
  605. cf_opts->compression = kZSTD;
  606. } else {
  607. // Unknown compression.
  608. exec_state_ =
  609. LDBCommandExecuteResult::Failed("Unknown compression level: " + comp);
  610. }
  611. }
  612. int compression_max_dict_bytes;
  613. if (ParseIntOption(option_map_, ARG_COMPRESSION_MAX_DICT_BYTES,
  614. compression_max_dict_bytes, exec_state_)) {
  615. if (compression_max_dict_bytes >= 0) {
  616. cf_opts->compression_opts.max_dict_bytes = compression_max_dict_bytes;
  617. } else {
  618. exec_state_ = LDBCommandExecuteResult::Failed(
  619. ARG_COMPRESSION_MAX_DICT_BYTES + " must be >= 0.");
  620. }
  621. }
  622. int db_write_buffer_size;
  623. if (ParseIntOption(option_map_, ARG_DB_WRITE_BUFFER_SIZE,
  624. db_write_buffer_size, exec_state_)) {
  625. if (db_write_buffer_size >= 0) {
  626. db_opts->db_write_buffer_size = db_write_buffer_size;
  627. } else {
  628. exec_state_ = LDBCommandExecuteResult::Failed(ARG_DB_WRITE_BUFFER_SIZE +
  629. " must be >= 0.");
  630. }
  631. }
  632. int write_buffer_size;
  633. if (ParseIntOption(option_map_, ARG_WRITE_BUFFER_SIZE, write_buffer_size,
  634. exec_state_)) {
  635. if (write_buffer_size > 0) {
  636. cf_opts->write_buffer_size = write_buffer_size;
  637. } else {
  638. exec_state_ = LDBCommandExecuteResult::Failed(ARG_WRITE_BUFFER_SIZE +
  639. " must be > 0.");
  640. }
  641. }
  642. int file_size;
  643. if (ParseIntOption(option_map_, ARG_FILE_SIZE, file_size, exec_state_)) {
  644. if (file_size > 0) {
  645. cf_opts->target_file_size_base = file_size;
  646. } else {
  647. exec_state_ =
  648. LDBCommandExecuteResult::Failed(ARG_FILE_SIZE + " must be > 0.");
  649. }
  650. }
  651. if (db_opts->db_paths.size() == 0) {
  652. db_opts->db_paths.emplace_back(db_path_,
  653. std::numeric_limits<uint64_t>::max());
  654. }
  655. int fix_prefix_len;
  656. if (ParseIntOption(option_map_, ARG_FIX_PREFIX_LEN, fix_prefix_len,
  657. exec_state_)) {
  658. if (fix_prefix_len > 0) {
  659. cf_opts->prefix_extractor.reset(
  660. NewFixedPrefixTransform(static_cast<size_t>(fix_prefix_len)));
  661. } else {
  662. exec_state_ =
  663. LDBCommandExecuteResult::Failed(ARG_FIX_PREFIX_LEN + " must be > 0.");
  664. }
  665. }
  666. // TODO(ajkr): this return value doesn't reflect the CF options changed, so
  667. // subcommands that rely on this won't see the effect of CF-related CLI args.
  668. // Such subcommands need to be changed to properly support CFs.
  669. return options_;
  670. }
  671. bool LDBCommand::ParseKeyValue(const std::string& line, std::string* key,
  672. std::string* value, bool is_key_hex,
  673. bool is_value_hex) {
  674. size_t pos = line.find(DELIM);
  675. if (pos != std::string::npos) {
  676. *key = line.substr(0, pos);
  677. *value = line.substr(pos + strlen(DELIM));
  678. if (is_key_hex) {
  679. *key = HexToString(*key);
  680. }
  681. if (is_value_hex) {
  682. *value = HexToString(*value);
  683. }
  684. return true;
  685. } else {
  686. return false;
  687. }
  688. }
  689. /**
  690. * Make sure that ONLY the command-line options and flags expected by this
  691. * command are specified on the command-line. Extraneous options are usually
  692. * the result of user error.
  693. * Returns true if all checks pass. Else returns false, and prints an
  694. * appropriate error msg to stderr.
  695. */
  696. bool LDBCommand::ValidateCmdLineOptions() {
  697. for (std::map<std::string, std::string>::const_iterator itr =
  698. option_map_.begin();
  699. itr != option_map_.end(); ++itr) {
  700. if (std::find(valid_cmd_line_options_.begin(),
  701. valid_cmd_line_options_.end(),
  702. itr->first) == valid_cmd_line_options_.end()) {
  703. fprintf(stderr, "Invalid command-line option %s\n", itr->first.c_str());
  704. return false;
  705. }
  706. }
  707. for (std::vector<std::string>::const_iterator itr = flags_.begin();
  708. itr != flags_.end(); ++itr) {
  709. if (std::find(valid_cmd_line_options_.begin(),
  710. valid_cmd_line_options_.end(),
  711. *itr) == valid_cmd_line_options_.end()) {
  712. fprintf(stderr, "Invalid command-line flag %s\n", itr->c_str());
  713. return false;
  714. }
  715. }
  716. if (!NoDBOpen() && option_map_.find(ARG_DB) == option_map_.end() &&
  717. option_map_.find(ARG_PATH) == option_map_.end()) {
  718. fprintf(stderr, "Either %s or %s must be specified.\n", ARG_DB.c_str(),
  719. ARG_PATH.c_str());
  720. return false;
  721. }
  722. return true;
  723. }
  724. std::string LDBCommand::HexToString(const std::string& str) {
  725. std::string result;
  726. std::string::size_type len = str.length();
  727. if (len < 2 || str[0] != '0' || str[1] != 'x') {
  728. fprintf(stderr, "Invalid hex input %s. Must start with 0x\n", str.c_str());
  729. throw "Invalid hex input";
  730. }
  731. if (!Slice(str.data() + 2, len - 2).DecodeHex(&result)) {
  732. throw "Invalid hex input";
  733. }
  734. return result;
  735. }
  736. std::string LDBCommand::StringToHex(const std::string& str) {
  737. std::string result("0x");
  738. result.append(Slice(str).ToString(true));
  739. return result;
  740. }
  741. std::string LDBCommand::PrintKeyValue(const std::string& key,
  742. const std::string& value, bool is_key_hex,
  743. bool is_value_hex) {
  744. std::string result;
  745. result.append(is_key_hex ? StringToHex(key) : key);
  746. result.append(DELIM);
  747. result.append(is_value_hex ? StringToHex(value) : value);
  748. return result;
  749. }
  750. std::string LDBCommand::PrintKeyValue(const std::string& key,
  751. const std::string& value, bool is_hex) {
  752. return PrintKeyValue(key, value, is_hex, is_hex);
  753. }
  754. std::string LDBCommand::HelpRangeCmdArgs() {
  755. std::ostringstream str_stream;
  756. str_stream << " ";
  757. str_stream << "[--" << ARG_FROM << "] ";
  758. str_stream << "[--" << ARG_TO << "] ";
  759. return str_stream.str();
  760. }
  761. bool LDBCommand::IsKeyHex(const std::map<std::string, std::string>& options,
  762. const std::vector<std::string>& flags) {
  763. return (IsFlagPresent(flags, ARG_HEX) || IsFlagPresent(flags, ARG_KEY_HEX) ||
  764. ParseBooleanOption(options, ARG_HEX, false) ||
  765. ParseBooleanOption(options, ARG_KEY_HEX, false));
  766. }
  767. bool LDBCommand::IsValueHex(const std::map<std::string, std::string>& options,
  768. const std::vector<std::string>& flags) {
  769. return (IsFlagPresent(flags, ARG_HEX) ||
  770. IsFlagPresent(flags, ARG_VALUE_HEX) ||
  771. ParseBooleanOption(options, ARG_HEX, false) ||
  772. ParseBooleanOption(options, ARG_VALUE_HEX, false));
  773. }
  774. bool LDBCommand::ParseBooleanOption(
  775. const std::map<std::string, std::string>& options,
  776. const std::string& option, bool default_val) {
  777. std::map<std::string, std::string>::const_iterator itr = options.find(option);
  778. if (itr != options.end()) {
  779. std::string option_val = itr->second;
  780. return StringToBool(itr->second);
  781. }
  782. return default_val;
  783. }
  784. bool LDBCommand::StringToBool(std::string val) {
  785. std::transform(val.begin(), val.end(), val.begin(),
  786. [](char ch) -> char { return (char)::tolower(ch); });
  787. if (val == "true") {
  788. return true;
  789. } else if (val == "false") {
  790. return false;
  791. } else {
  792. throw "Invalid value for boolean argument";
  793. }
  794. }
  795. CompactorCommand::CompactorCommand(
  796. const std::vector<std::string>& /*params*/,
  797. const std::map<std::string, std::string>& options,
  798. const std::vector<std::string>& flags)
  799. : LDBCommand(options, flags, false,
  800. BuildCmdLineOptions({ARG_FROM, ARG_TO, ARG_HEX, ARG_KEY_HEX,
  801. ARG_VALUE_HEX, ARG_TTL})),
  802. null_from_(true),
  803. null_to_(true) {
  804. std::map<std::string, std::string>::const_iterator itr =
  805. options.find(ARG_FROM);
  806. if (itr != options.end()) {
  807. null_from_ = false;
  808. from_ = itr->second;
  809. }
  810. itr = options.find(ARG_TO);
  811. if (itr != options.end()) {
  812. null_to_ = false;
  813. to_ = itr->second;
  814. }
  815. if (is_key_hex_) {
  816. if (!null_from_) {
  817. from_ = HexToString(from_);
  818. }
  819. if (!null_to_) {
  820. to_ = HexToString(to_);
  821. }
  822. }
  823. }
  824. void CompactorCommand::Help(std::string& ret) {
  825. ret.append(" ");
  826. ret.append(CompactorCommand::Name());
  827. ret.append(HelpRangeCmdArgs());
  828. ret.append("\n");
  829. }
  830. void CompactorCommand::DoCommand() {
  831. if (!db_) {
  832. assert(GetExecuteState().IsFailed());
  833. return;
  834. }
  835. Slice* begin = nullptr;
  836. Slice* end = nullptr;
  837. if (!null_from_) {
  838. begin = new Slice(from_);
  839. }
  840. if (!null_to_) {
  841. end = new Slice(to_);
  842. }
  843. CompactRangeOptions cro;
  844. cro.bottommost_level_compaction = BottommostLevelCompaction::kForceOptimized;
  845. db_->CompactRange(cro, GetCfHandle(), begin, end);
  846. exec_state_ = LDBCommandExecuteResult::Succeed("");
  847. delete begin;
  848. delete end;
  849. }
  850. // ---------------------------------------------------------------------------
  851. const std::string DBLoaderCommand::ARG_DISABLE_WAL = "disable_wal";
  852. const std::string DBLoaderCommand::ARG_BULK_LOAD = "bulk_load";
  853. const std::string DBLoaderCommand::ARG_COMPACT = "compact";
  854. DBLoaderCommand::DBLoaderCommand(
  855. const std::vector<std::string>& /*params*/,
  856. const std::map<std::string, std::string>& options,
  857. const std::vector<std::string>& flags)
  858. : LDBCommand(
  859. options, flags, false,
  860. BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM,
  861. ARG_TO, ARG_CREATE_IF_MISSING, ARG_DISABLE_WAL,
  862. ARG_BULK_LOAD, ARG_COMPACT})),
  863. disable_wal_(false),
  864. bulk_load_(false),
  865. compact_(false) {
  866. create_if_missing_ = IsFlagPresent(flags, ARG_CREATE_IF_MISSING);
  867. disable_wal_ = IsFlagPresent(flags, ARG_DISABLE_WAL);
  868. bulk_load_ = IsFlagPresent(flags, ARG_BULK_LOAD);
  869. compact_ = IsFlagPresent(flags, ARG_COMPACT);
  870. }
  871. void DBLoaderCommand::Help(std::string& ret) {
  872. ret.append(" ");
  873. ret.append(DBLoaderCommand::Name());
  874. ret.append(" [--" + ARG_CREATE_IF_MISSING + "]");
  875. ret.append(" [--" + ARG_DISABLE_WAL + "]");
  876. ret.append(" [--" + ARG_BULK_LOAD + "]");
  877. ret.append(" [--" + ARG_COMPACT + "]");
  878. ret.append("\n");
  879. }
  880. Options DBLoaderCommand::PrepareOptionsForOpenDB() {
  881. Options opt = LDBCommand::PrepareOptionsForOpenDB();
  882. opt.create_if_missing = create_if_missing_;
  883. if (bulk_load_) {
  884. opt.PrepareForBulkLoad();
  885. }
  886. return opt;
  887. }
  888. void DBLoaderCommand::DoCommand() {
  889. if (!db_) {
  890. assert(GetExecuteState().IsFailed());
  891. return;
  892. }
  893. WriteOptions write_options;
  894. if (disable_wal_) {
  895. write_options.disableWAL = true;
  896. }
  897. int bad_lines = 0;
  898. std::string line;
  899. // prefer ifstream getline performance vs that from std::cin istream
  900. std::ifstream ifs_stdin("/dev/stdin");
  901. std::istream* istream_p = ifs_stdin.is_open() ? &ifs_stdin : &std::cin;
  902. while (getline(*istream_p, line, '\n')) {
  903. std::string key;
  904. std::string value;
  905. if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
  906. db_->Put(write_options, GetCfHandle(), Slice(key), Slice(value));
  907. } else if (0 == line.find("Keys in range:")) {
  908. // ignore this line
  909. } else if (0 == line.find("Created bg thread 0x")) {
  910. // ignore this line
  911. } else {
  912. bad_lines ++;
  913. }
  914. }
  915. if (bad_lines > 0) {
  916. std::cout << "Warning: " << bad_lines << " bad lines ignored." << std::endl;
  917. }
  918. if (compact_) {
  919. db_->CompactRange(CompactRangeOptions(), GetCfHandle(), nullptr, nullptr);
  920. }
  921. }
  922. // ----------------------------------------------------------------------------
  923. namespace {
  924. void DumpManifestFile(Options options, std::string file, bool verbose, bool hex,
  925. bool json) {
  926. EnvOptions sopt;
  927. std::string dbname("dummy");
  928. std::shared_ptr<Cache> tc(NewLRUCache(options.max_open_files - 10,
  929. options.table_cache_numshardbits));
  930. // Notice we are using the default options not through SanitizeOptions(),
  931. // if VersionSet::DumpManifest() depends on any option done by
  932. // SanitizeOptions(), we need to initialize it manually.
  933. options.db_paths.emplace_back("dummy", 0);
  934. options.num_levels = 64;
  935. WriteController wc(options.delayed_write_rate);
  936. WriteBufferManager wb(options.db_write_buffer_size);
  937. ImmutableDBOptions immutable_db_options(options);
  938. VersionSet versions(dbname, &immutable_db_options, sopt, tc.get(), &wb, &wc,
  939. /*block_cache_tracer=*/nullptr);
  940. Status s = versions.DumpManifest(options, file, verbose, hex, json);
  941. if (!s.ok()) {
  942. fprintf(stderr, "Error in processing file %s %s\n", file.c_str(),
  943. s.ToString().c_str());
  944. }
  945. }
  946. } // namespace
  947. const std::string ManifestDumpCommand::ARG_VERBOSE = "verbose";
  948. const std::string ManifestDumpCommand::ARG_JSON = "json";
  949. const std::string ManifestDumpCommand::ARG_PATH = "path";
  950. void ManifestDumpCommand::Help(std::string& ret) {
  951. ret.append(" ");
  952. ret.append(ManifestDumpCommand::Name());
  953. ret.append(" [--" + ARG_VERBOSE + "]");
  954. ret.append(" [--" + ARG_JSON + "]");
  955. ret.append(" [--" + ARG_PATH + "=<path_to_manifest_file>]");
  956. ret.append("\n");
  957. }
  958. ManifestDumpCommand::ManifestDumpCommand(
  959. const std::vector<std::string>& /*params*/,
  960. const std::map<std::string, std::string>& options,
  961. const std::vector<std::string>& flags)
  962. : LDBCommand(
  963. options, flags, false,
  964. BuildCmdLineOptions({ARG_VERBOSE, ARG_PATH, ARG_HEX, ARG_JSON})),
  965. verbose_(false),
  966. json_(false),
  967. path_("") {
  968. verbose_ = IsFlagPresent(flags, ARG_VERBOSE);
  969. json_ = IsFlagPresent(flags, ARG_JSON);
  970. std::map<std::string, std::string>::const_iterator itr =
  971. options.find(ARG_PATH);
  972. if (itr != options.end()) {
  973. path_ = itr->second;
  974. if (path_.empty()) {
  975. exec_state_ = LDBCommandExecuteResult::Failed("--path: missing pathname");
  976. }
  977. }
  978. }
  979. void ManifestDumpCommand::DoCommand() {
  980. std::string manifestfile;
  981. if (!path_.empty()) {
  982. manifestfile = path_;
  983. } else {
  984. // We need to find the manifest file by searching the directory
  985. // containing the db for files of the form MANIFEST_[0-9]+
  986. std::vector<std::string> files;
  987. Status s = options_.env->GetChildren(db_path_, &files);
  988. if (!s.ok()) {
  989. std::string err_msg = s.ToString();
  990. err_msg.append(": Failed to list the content of ");
  991. err_msg.append(db_path_);
  992. exec_state_ = LDBCommandExecuteResult::Failed(err_msg);
  993. return;
  994. }
  995. const std::string kManifestNamePrefix = "MANIFEST-";
  996. std::string matched_file;
  997. #ifdef OS_WIN
  998. const char kPathDelim = '\\';
  999. #else
  1000. const char kPathDelim = '/';
  1001. #endif
  1002. for (const auto& file_path : files) {
  1003. // Some Env::GetChildren() return absolute paths. Some directories' path
  1004. // end with path delim, e.g. '/' or '\\'.
  1005. size_t pos = file_path.find_last_of(kPathDelim);
  1006. if (pos == file_path.size() - 1) {
  1007. continue;
  1008. }
  1009. std::string fname;
  1010. if (pos != std::string::npos) {
  1011. // Absolute path.
  1012. fname.assign(file_path, pos + 1, file_path.size() - pos - 1);
  1013. } else {
  1014. fname = file_path;
  1015. }
  1016. uint64_t file_num = 0;
  1017. FileType file_type = kLogFile; // Just for initialization
  1018. if (ParseFileName(fname, &file_num, &file_type) &&
  1019. file_type == kDescriptorFile) {
  1020. if (!matched_file.empty()) {
  1021. exec_state_ = LDBCommandExecuteResult::Failed(
  1022. "Multiple MANIFEST files found; use --path to select one");
  1023. return;
  1024. } else {
  1025. matched_file.swap(fname);
  1026. }
  1027. }
  1028. }
  1029. if (matched_file.empty()) {
  1030. std::string err_msg("No MANIFEST found in ");
  1031. err_msg.append(db_path_);
  1032. exec_state_ = LDBCommandExecuteResult::Failed(err_msg);
  1033. return;
  1034. }
  1035. if (db_path_[db_path_.length() - 1] != '/') {
  1036. db_path_.append("/");
  1037. }
  1038. manifestfile = db_path_ + matched_file;
  1039. }
  1040. if (verbose_) {
  1041. fprintf(stdout, "Processing Manifest file %s\n", manifestfile.c_str());
  1042. }
  1043. DumpManifestFile(options_, manifestfile, verbose_, is_key_hex_, json_);
  1044. if (verbose_) {
  1045. fprintf(stdout, "Processing Manifest file %s done\n", manifestfile.c_str());
  1046. }
  1047. }
  1048. // ----------------------------------------------------------------------------
  1049. namespace {
  1050. void GetLiveFilesChecksumInfoFromVersionSet(Options options,
  1051. const std::string& db_path,
  1052. FileChecksumList* checksum_list) {
  1053. EnvOptions sopt;
  1054. Status s;
  1055. std::string dbname(db_path);
  1056. std::shared_ptr<Cache> tc(NewLRUCache(options.max_open_files - 10,
  1057. options.table_cache_numshardbits));
  1058. // Notice we are using the default options not through SanitizeOptions(),
  1059. // if VersionSet::GetLiveFilesChecksumInfo depends on any option done by
  1060. // SanitizeOptions(), we need to initialize it manually.
  1061. options.db_paths.emplace_back(db_path, 0);
  1062. options.num_levels = 64;
  1063. WriteController wc(options.delayed_write_rate);
  1064. WriteBufferManager wb(options.db_write_buffer_size);
  1065. ImmutableDBOptions immutable_db_options(options);
  1066. VersionSet versions(dbname, &immutable_db_options, sopt, tc.get(), &wb, &wc,
  1067. /*block_cache_tracer=*/nullptr);
  1068. std::vector<std::string> cf_name_list;
  1069. s = versions.ListColumnFamilies(&cf_name_list, db_path,
  1070. options.file_system.get());
  1071. if (s.ok()) {
  1072. std::vector<ColumnFamilyDescriptor> cf_list;
  1073. for (const auto& name : cf_name_list) {
  1074. cf_list.emplace_back(name, ColumnFamilyOptions(options));
  1075. }
  1076. s = versions.Recover(cf_list, true);
  1077. }
  1078. if (s.ok()) {
  1079. s = versions.GetLiveFilesChecksumInfo(checksum_list);
  1080. }
  1081. if (!s.ok()) {
  1082. fprintf(stderr, "Error Status: %s", s.ToString().c_str());
  1083. }
  1084. }
  1085. } // namespace
  1086. const std::string FileChecksumDumpCommand::ARG_PATH = "path";
  1087. void FileChecksumDumpCommand::Help(std::string& ret) {
  1088. ret.append(" ");
  1089. ret.append(FileChecksumDumpCommand::Name());
  1090. ret.append(" [--" + ARG_PATH + "=<path_to_manifest_file>]");
  1091. ret.append("\n");
  1092. }
  1093. FileChecksumDumpCommand::FileChecksumDumpCommand(
  1094. const std::vector<std::string>& /*params*/,
  1095. const std::map<std::string, std::string>& options,
  1096. const std::vector<std::string>& flags)
  1097. : LDBCommand(options, flags, false, BuildCmdLineOptions({ARG_PATH})),
  1098. path_("") {
  1099. std::map<std::string, std::string>::const_iterator itr =
  1100. options.find(ARG_PATH);
  1101. if (itr != options.end()) {
  1102. path_ = itr->second;
  1103. if (path_.empty()) {
  1104. exec_state_ = LDBCommandExecuteResult::Failed("--path: missing pathname");
  1105. }
  1106. }
  1107. }
  1108. void FileChecksumDumpCommand::DoCommand() {
  1109. // print out the checksum information in the following format:
  1110. // sst file number, checksum function name, checksum value
  1111. // sst file number, checksum function name, checksum value
  1112. // ......
  1113. std::unique_ptr<FileChecksumList> checksum_list(NewFileChecksumList());
  1114. GetLiveFilesChecksumInfoFromVersionSet(options_, db_path_,
  1115. checksum_list.get());
  1116. if (checksum_list != nullptr) {
  1117. std::vector<uint64_t> file_numbers;
  1118. std::vector<std::string> checksums;
  1119. std::vector<std::string> checksum_func_names;
  1120. Status s = checksum_list->GetAllFileChecksums(&file_numbers, &checksums,
  1121. &checksum_func_names);
  1122. if (s.ok()) {
  1123. for (size_t i = 0; i < file_numbers.size(); i++) {
  1124. assert(i < file_numbers.size());
  1125. assert(i < checksums.size());
  1126. assert(i < checksum_func_names.size());
  1127. fprintf(stdout, "%" PRId64 ", %s, %s\n", file_numbers[i],
  1128. checksum_func_names[i].c_str(), checksums[i].c_str());
  1129. }
  1130. }
  1131. fprintf(stdout, "Print SST file checksum information finished \n");
  1132. }
  1133. }
  1134. // ----------------------------------------------------------------------------
  1135. void ListColumnFamiliesCommand::Help(std::string& ret) {
  1136. ret.append(" ");
  1137. ret.append(ListColumnFamiliesCommand::Name());
  1138. ret.append("\n");
  1139. }
  1140. ListColumnFamiliesCommand::ListColumnFamiliesCommand(
  1141. const std::vector<std::string>& /*params*/,
  1142. const std::map<std::string, std::string>& options,
  1143. const std::vector<std::string>& flags)
  1144. : LDBCommand(options, flags, false, BuildCmdLineOptions({})) {}
  1145. void ListColumnFamiliesCommand::DoCommand() {
  1146. std::vector<std::string> column_families;
  1147. Status s = DB::ListColumnFamilies(options_, db_path_, &column_families);
  1148. if (!s.ok()) {
  1149. fprintf(stderr, "Error in processing db %s %s\n", db_path_.c_str(),
  1150. s.ToString().c_str());
  1151. } else {
  1152. fprintf(stdout, "Column families in %s: \n{", db_path_.c_str());
  1153. bool first = true;
  1154. for (auto cf : column_families) {
  1155. if (!first) {
  1156. fprintf(stdout, ", ");
  1157. }
  1158. first = false;
  1159. fprintf(stdout, "%s", cf.c_str());
  1160. }
  1161. fprintf(stdout, "}\n");
  1162. }
  1163. }
  1164. void CreateColumnFamilyCommand::Help(std::string& ret) {
  1165. ret.append(" ");
  1166. ret.append(CreateColumnFamilyCommand::Name());
  1167. ret.append(" --db=<db_path> <new_column_family_name>");
  1168. ret.append("\n");
  1169. }
  1170. CreateColumnFamilyCommand::CreateColumnFamilyCommand(
  1171. const std::vector<std::string>& params,
  1172. const std::map<std::string, std::string>& options,
  1173. const std::vector<std::string>& flags)
  1174. : LDBCommand(options, flags, true, {ARG_DB}) {
  1175. if (params.size() != 1) {
  1176. exec_state_ = LDBCommandExecuteResult::Failed(
  1177. "new column family name must be specified");
  1178. } else {
  1179. new_cf_name_ = params[0];
  1180. }
  1181. }
  1182. void CreateColumnFamilyCommand::DoCommand() {
  1183. ColumnFamilyHandle* new_cf_handle = nullptr;
  1184. Status st = db_->CreateColumnFamily(options_, new_cf_name_, &new_cf_handle);
  1185. if (st.ok()) {
  1186. fprintf(stdout, "OK\n");
  1187. } else {
  1188. exec_state_ = LDBCommandExecuteResult::Failed(
  1189. "Fail to create new column family: " + st.ToString());
  1190. }
  1191. delete new_cf_handle;
  1192. CloseDB();
  1193. }
  1194. void DropColumnFamilyCommand::Help(std::string& ret) {
  1195. ret.append(" ");
  1196. ret.append(DropColumnFamilyCommand::Name());
  1197. ret.append(" --db=<db_path> <column_family_name_to_drop>");
  1198. ret.append("\n");
  1199. }
  1200. DropColumnFamilyCommand::DropColumnFamilyCommand(
  1201. const std::vector<std::string>& params,
  1202. const std::map<std::string, std::string>& options,
  1203. const std::vector<std::string>& flags)
  1204. : LDBCommand(options, flags, true, {ARG_DB}) {
  1205. if (params.size() != 1) {
  1206. exec_state_ = LDBCommandExecuteResult::Failed(
  1207. "The name of column family to drop must be specified");
  1208. } else {
  1209. cf_name_to_drop_ = params[0];
  1210. }
  1211. }
  1212. void DropColumnFamilyCommand::DoCommand() {
  1213. auto iter = cf_handles_.find(cf_name_to_drop_);
  1214. if (iter == cf_handles_.end()) {
  1215. exec_state_ = LDBCommandExecuteResult::Failed(
  1216. "Column family: " + cf_name_to_drop_ + " doesn't exist in db.");
  1217. return;
  1218. }
  1219. ColumnFamilyHandle* cf_handle_to_drop = iter->second;
  1220. Status st = db_->DropColumnFamily(cf_handle_to_drop);
  1221. if (st.ok()) {
  1222. fprintf(stdout, "OK\n");
  1223. } else {
  1224. exec_state_ = LDBCommandExecuteResult::Failed(
  1225. "Fail to drop column family: " + st.ToString());
  1226. }
  1227. CloseDB();
  1228. }
  1229. // ----------------------------------------------------------------------------
  1230. namespace {
  1231. // This function only called when it's the sane case of >1 buckets in time-range
  1232. // Also called only when timekv falls between ttl_start and ttl_end provided
  1233. void IncBucketCounts(std::vector<uint64_t>& bucket_counts, int ttl_start,
  1234. int time_range, int bucket_size, int timekv,
  1235. int num_buckets) {
  1236. #ifdef NDEBUG
  1237. (void)time_range;
  1238. (void)num_buckets;
  1239. #endif
  1240. assert(time_range > 0 && timekv >= ttl_start && bucket_size > 0 &&
  1241. timekv < (ttl_start + time_range) && num_buckets > 1);
  1242. int bucket = (timekv - ttl_start) / bucket_size;
  1243. bucket_counts[bucket]++;
  1244. }
  1245. void PrintBucketCounts(const std::vector<uint64_t>& bucket_counts,
  1246. int ttl_start, int ttl_end, int bucket_size,
  1247. int num_buckets) {
  1248. int time_point = ttl_start;
  1249. for(int i = 0; i < num_buckets - 1; i++, time_point += bucket_size) {
  1250. fprintf(stdout, "Keys in range %s to %s : %lu\n",
  1251. TimeToHumanString(time_point).c_str(),
  1252. TimeToHumanString(time_point + bucket_size).c_str(),
  1253. (unsigned long)bucket_counts[i]);
  1254. }
  1255. fprintf(stdout, "Keys in range %s to %s : %lu\n",
  1256. TimeToHumanString(time_point).c_str(),
  1257. TimeToHumanString(ttl_end).c_str(),
  1258. (unsigned long)bucket_counts[num_buckets - 1]);
  1259. }
  1260. } // namespace
  1261. const std::string InternalDumpCommand::ARG_COUNT_ONLY = "count_only";
  1262. const std::string InternalDumpCommand::ARG_COUNT_DELIM = "count_delim";
  1263. const std::string InternalDumpCommand::ARG_STATS = "stats";
  1264. const std::string InternalDumpCommand::ARG_INPUT_KEY_HEX = "input_key_hex";
  1265. InternalDumpCommand::InternalDumpCommand(
  1266. const std::vector<std::string>& /*params*/,
  1267. const std::map<std::string, std::string>& options,
  1268. const std::vector<std::string>& flags)
  1269. : LDBCommand(
  1270. options, flags, true,
  1271. BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM,
  1272. ARG_TO, ARG_MAX_KEYS, ARG_COUNT_ONLY,
  1273. ARG_COUNT_DELIM, ARG_STATS, ARG_INPUT_KEY_HEX})),
  1274. has_from_(false),
  1275. has_to_(false),
  1276. max_keys_(-1),
  1277. delim_("."),
  1278. count_only_(false),
  1279. count_delim_(false),
  1280. print_stats_(false),
  1281. is_input_key_hex_(false) {
  1282. has_from_ = ParseStringOption(options, ARG_FROM, &from_);
  1283. has_to_ = ParseStringOption(options, ARG_TO, &to_);
  1284. ParseIntOption(options, ARG_MAX_KEYS, max_keys_, exec_state_);
  1285. std::map<std::string, std::string>::const_iterator itr =
  1286. options.find(ARG_COUNT_DELIM);
  1287. if (itr != options.end()) {
  1288. delim_ = itr->second;
  1289. count_delim_ = true;
  1290. // fprintf(stdout,"delim = %c\n",delim_[0]);
  1291. } else {
  1292. count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
  1293. delim_=".";
  1294. }
  1295. print_stats_ = IsFlagPresent(flags, ARG_STATS);
  1296. count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);
  1297. is_input_key_hex_ = IsFlagPresent(flags, ARG_INPUT_KEY_HEX);
  1298. if (is_input_key_hex_) {
  1299. if (has_from_) {
  1300. from_ = HexToString(from_);
  1301. }
  1302. if (has_to_) {
  1303. to_ = HexToString(to_);
  1304. }
  1305. }
  1306. }
  1307. void InternalDumpCommand::Help(std::string& ret) {
  1308. ret.append(" ");
  1309. ret.append(InternalDumpCommand::Name());
  1310. ret.append(HelpRangeCmdArgs());
  1311. ret.append(" [--" + ARG_INPUT_KEY_HEX + "]");
  1312. ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
  1313. ret.append(" [--" + ARG_COUNT_ONLY + "]");
  1314. ret.append(" [--" + ARG_COUNT_DELIM + "=<char>]");
  1315. ret.append(" [--" + ARG_STATS + "]");
  1316. ret.append("\n");
  1317. }
  1318. void InternalDumpCommand::DoCommand() {
  1319. if (!db_) {
  1320. assert(GetExecuteState().IsFailed());
  1321. return;
  1322. }
  1323. if (print_stats_) {
  1324. std::string stats;
  1325. if (db_->GetProperty(GetCfHandle(), "rocksdb.stats", &stats)) {
  1326. fprintf(stdout, "%s\n", stats.c_str());
  1327. }
  1328. }
  1329. // Cast as DBImpl to get internal iterator
  1330. std::vector<KeyVersion> key_versions;
  1331. Status st = GetAllKeyVersions(db_, GetCfHandle(), from_, to_, max_keys_,
  1332. &key_versions);
  1333. if (!st.ok()) {
  1334. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  1335. return;
  1336. }
  1337. std::string rtype1, rtype2, row, val;
  1338. rtype2 = "";
  1339. uint64_t c=0;
  1340. uint64_t s1=0,s2=0;
  1341. long long count = 0;
  1342. for (auto& key_version : key_versions) {
  1343. InternalKey ikey(key_version.user_key, key_version.sequence,
  1344. static_cast<ValueType>(key_version.type));
  1345. if (has_to_ && ikey.user_key() == to_) {
  1346. // GetAllKeyVersions() includes keys with user key `to_`, but idump has
  1347. // traditionally excluded such keys.
  1348. break;
  1349. }
  1350. ++count;
  1351. int k;
  1352. if (count_delim_) {
  1353. rtype1 = "";
  1354. s1=0;
  1355. row = ikey.Encode().ToString();
  1356. val = key_version.value;
  1357. for(k=0;row[k]!='\x01' && row[k]!='\0';k++)
  1358. s1++;
  1359. for(k=0;val[k]!='\x01' && val[k]!='\0';k++)
  1360. s1++;
  1361. for(int j=0;row[j]!=delim_[0] && row[j]!='\0' && row[j]!='\x01';j++)
  1362. rtype1+=row[j];
  1363. if(rtype2.compare("") && rtype2.compare(rtype1)!=0) {
  1364. fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
  1365. rtype2.c_str(), c, s2);
  1366. c=1;
  1367. s2=s1;
  1368. rtype2 = rtype1;
  1369. } else {
  1370. c++;
  1371. s2+=s1;
  1372. rtype2=rtype1;
  1373. }
  1374. }
  1375. if (!count_only_ && !count_delim_) {
  1376. std::string key = ikey.DebugString(is_key_hex_);
  1377. std::string value = Slice(key_version.value).ToString(is_value_hex_);
  1378. std::cout << key << " => " << value << "\n";
  1379. }
  1380. // Terminate if maximum number of keys have been dumped
  1381. if (max_keys_ > 0 && count >= max_keys_) break;
  1382. }
  1383. if(count_delim_) {
  1384. fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
  1385. rtype2.c_str(), c, s2);
  1386. } else {
  1387. fprintf(stdout, "Internal keys in range: %lld\n", count);
  1388. }
  1389. }
  1390. const std::string DBDumperCommand::ARG_COUNT_ONLY = "count_only";
  1391. const std::string DBDumperCommand::ARG_COUNT_DELIM = "count_delim";
  1392. const std::string DBDumperCommand::ARG_STATS = "stats";
  1393. const std::string DBDumperCommand::ARG_TTL_BUCKET = "bucket";
  1394. DBDumperCommand::DBDumperCommand(
  1395. const std::vector<std::string>& /*params*/,
  1396. const std::map<std::string, std::string>& options,
  1397. const std::vector<std::string>& flags)
  1398. : LDBCommand(options, flags, true,
  1399. BuildCmdLineOptions(
  1400. {ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM,
  1401. ARG_TO, ARG_MAX_KEYS, ARG_COUNT_ONLY, ARG_COUNT_DELIM,
  1402. ARG_STATS, ARG_TTL_START, ARG_TTL_END, ARG_TTL_BUCKET,
  1403. ARG_TIMESTAMP, ARG_PATH})),
  1404. null_from_(true),
  1405. null_to_(true),
  1406. max_keys_(-1),
  1407. count_only_(false),
  1408. count_delim_(false),
  1409. print_stats_(false) {
  1410. std::map<std::string, std::string>::const_iterator itr =
  1411. options.find(ARG_FROM);
  1412. if (itr != options.end()) {
  1413. null_from_ = false;
  1414. from_ = itr->second;
  1415. }
  1416. itr = options.find(ARG_TO);
  1417. if (itr != options.end()) {
  1418. null_to_ = false;
  1419. to_ = itr->second;
  1420. }
  1421. itr = options.find(ARG_MAX_KEYS);
  1422. if (itr != options.end()) {
  1423. try {
  1424. #if defined(CYGWIN)
  1425. max_keys_ = strtol(itr->second.c_str(), 0, 10);
  1426. #else
  1427. max_keys_ = std::stoi(itr->second);
  1428. #endif
  1429. } catch (const std::invalid_argument&) {
  1430. exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
  1431. " has an invalid value");
  1432. } catch (const std::out_of_range&) {
  1433. exec_state_ = LDBCommandExecuteResult::Failed(
  1434. ARG_MAX_KEYS + " has a value out-of-range");
  1435. }
  1436. }
  1437. itr = options.find(ARG_COUNT_DELIM);
  1438. if (itr != options.end()) {
  1439. delim_ = itr->second;
  1440. count_delim_ = true;
  1441. } else {
  1442. count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
  1443. delim_=".";
  1444. }
  1445. print_stats_ = IsFlagPresent(flags, ARG_STATS);
  1446. count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);
  1447. if (is_key_hex_) {
  1448. if (!null_from_) {
  1449. from_ = HexToString(from_);
  1450. }
  1451. if (!null_to_) {
  1452. to_ = HexToString(to_);
  1453. }
  1454. }
  1455. itr = options.find(ARG_PATH);
  1456. if (itr != options.end()) {
  1457. path_ = itr->second;
  1458. if (db_path_.empty()) {
  1459. db_path_ = path_;
  1460. }
  1461. }
  1462. }
  1463. void DBDumperCommand::Help(std::string& ret) {
  1464. ret.append(" ");
  1465. ret.append(DBDumperCommand::Name());
  1466. ret.append(HelpRangeCmdArgs());
  1467. ret.append(" [--" + ARG_TTL + "]");
  1468. ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
  1469. ret.append(" [--" + ARG_TIMESTAMP + "]");
  1470. ret.append(" [--" + ARG_COUNT_ONLY + "]");
  1471. ret.append(" [--" + ARG_COUNT_DELIM + "=<char>]");
  1472. ret.append(" [--" + ARG_STATS + "]");
  1473. ret.append(" [--" + ARG_TTL_BUCKET + "=<N>]");
  1474. ret.append(" [--" + ARG_TTL_START + "=<N>:- is inclusive]");
  1475. ret.append(" [--" + ARG_TTL_END + "=<N>:- is exclusive]");
  1476. ret.append(" [--" + ARG_PATH + "=<path_to_a_file>]");
  1477. ret.append("\n");
  1478. }
  1479. /**
  1480. * Handles two separate cases:
  1481. *
  1482. * 1) --db is specified - just dump the database.
  1483. *
  1484. * 2) --path is specified - determine based on file extension what dumping
  1485. * function to call. Please note that we intentionally use the extension
  1486. * and avoid probing the file contents under the assumption that renaming
  1487. * the files is not a supported scenario.
  1488. *
  1489. */
  1490. void DBDumperCommand::DoCommand() {
  1491. if (!db_) {
  1492. assert(!path_.empty());
  1493. std::string fileName = GetFileNameFromPath(path_);
  1494. uint64_t number;
  1495. FileType type;
  1496. exec_state_ = LDBCommandExecuteResult::Succeed("");
  1497. if (!ParseFileName(fileName, &number, &type)) {
  1498. exec_state_ =
  1499. LDBCommandExecuteResult::Failed("Can't parse file type: " + path_);
  1500. return;
  1501. }
  1502. switch (type) {
  1503. case kLogFile:
  1504. // TODO(myabandeh): allow configuring is_write_commited
  1505. DumpWalFile(options_, path_, /* print_header_ */ true,
  1506. /* print_values_ */ true, true /* is_write_commited */,
  1507. &exec_state_);
  1508. break;
  1509. case kTableFile:
  1510. DumpSstFile(options_, path_, is_key_hex_, /* show_properties */ true);
  1511. break;
  1512. case kDescriptorFile:
  1513. DumpManifestFile(options_, path_, /* verbose_ */ false, is_key_hex_,
  1514. /* json_ */ false);
  1515. break;
  1516. default:
  1517. exec_state_ = LDBCommandExecuteResult::Failed(
  1518. "File type not supported: " + path_);
  1519. break;
  1520. }
  1521. } else {
  1522. DoDumpCommand();
  1523. }
  1524. }
  1525. void DBDumperCommand::DoDumpCommand() {
  1526. assert(nullptr != db_);
  1527. assert(path_.empty());
  1528. // Parse command line args
  1529. uint64_t count = 0;
  1530. if (print_stats_) {
  1531. std::string stats;
  1532. if (db_->GetProperty("rocksdb.stats", &stats)) {
  1533. fprintf(stdout, "%s\n", stats.c_str());
  1534. }
  1535. }
  1536. // Setup key iterator
  1537. ReadOptions scan_read_opts;
  1538. scan_read_opts.total_order_seek = true;
  1539. Iterator* iter = db_->NewIterator(scan_read_opts, GetCfHandle());
  1540. Status st = iter->status();
  1541. if (!st.ok()) {
  1542. exec_state_ =
  1543. LDBCommandExecuteResult::Failed("Iterator error." + st.ToString());
  1544. }
  1545. if (!null_from_) {
  1546. iter->Seek(from_);
  1547. } else {
  1548. iter->SeekToFirst();
  1549. }
  1550. int max_keys = max_keys_;
  1551. int ttl_start;
  1552. if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
  1553. ttl_start = DBWithTTLImpl::kMinTimestamp; // TTL introduction time
  1554. }
  1555. int ttl_end;
  1556. if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
  1557. ttl_end = DBWithTTLImpl::kMaxTimestamp; // Max time allowed by TTL feature
  1558. }
  1559. if (ttl_end < ttl_start) {
  1560. fprintf(stderr, "Error: End time can't be less than start time\n");
  1561. delete iter;
  1562. return;
  1563. }
  1564. int time_range = ttl_end - ttl_start;
  1565. int bucket_size;
  1566. if (!ParseIntOption(option_map_, ARG_TTL_BUCKET, bucket_size, exec_state_) ||
  1567. bucket_size <= 0) {
  1568. bucket_size = time_range; // Will have just 1 bucket by default
  1569. }
  1570. //cretaing variables for row count of each type
  1571. std::string rtype1, rtype2, row, val;
  1572. rtype2 = "";
  1573. uint64_t c=0;
  1574. uint64_t s1=0,s2=0;
  1575. // At this point, bucket_size=0 => time_range=0
  1576. int num_buckets = (bucket_size >= time_range)
  1577. ? 1
  1578. : ((time_range + bucket_size - 1) / bucket_size);
  1579. std::vector<uint64_t> bucket_counts(num_buckets, 0);
  1580. if (is_db_ttl_ && !count_only_ && timestamp_ && !count_delim_) {
  1581. fprintf(stdout, "Dumping key-values from %s to %s\n",
  1582. TimeToHumanString(ttl_start).c_str(),
  1583. TimeToHumanString(ttl_end).c_str());
  1584. }
  1585. HistogramImpl vsize_hist;
  1586. for (; iter->Valid(); iter->Next()) {
  1587. int rawtime = 0;
  1588. // If end marker was specified, we stop before it
  1589. if (!null_to_ && (iter->key().ToString() >= to_))
  1590. break;
  1591. // Terminate if maximum number of keys have been dumped
  1592. if (max_keys == 0)
  1593. break;
  1594. if (is_db_ttl_) {
  1595. TtlIterator* it_ttl = static_cast_with_check<TtlIterator, Iterator>(iter);
  1596. rawtime = it_ttl->timestamp();
  1597. if (rawtime < ttl_start || rawtime >= ttl_end) {
  1598. continue;
  1599. }
  1600. }
  1601. if (max_keys > 0) {
  1602. --max_keys;
  1603. }
  1604. if (is_db_ttl_ && num_buckets > 1) {
  1605. IncBucketCounts(bucket_counts, ttl_start, time_range, bucket_size,
  1606. rawtime, num_buckets);
  1607. }
  1608. ++count;
  1609. if (count_delim_) {
  1610. rtype1 = "";
  1611. row = iter->key().ToString();
  1612. val = iter->value().ToString();
  1613. s1 = row.size()+val.size();
  1614. for(int j=0;row[j]!=delim_[0] && row[j]!='\0';j++)
  1615. rtype1+=row[j];
  1616. if(rtype2.compare("") && rtype2.compare(rtype1)!=0) {
  1617. fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
  1618. rtype2.c_str(), c, s2);
  1619. c=1;
  1620. s2=s1;
  1621. rtype2 = rtype1;
  1622. } else {
  1623. c++;
  1624. s2+=s1;
  1625. rtype2=rtype1;
  1626. }
  1627. }
  1628. if (count_only_) {
  1629. vsize_hist.Add(iter->value().size());
  1630. }
  1631. if (!count_only_ && !count_delim_) {
  1632. if (is_db_ttl_ && timestamp_) {
  1633. fprintf(stdout, "%s ", TimeToHumanString(rawtime).c_str());
  1634. }
  1635. std::string str =
  1636. PrintKeyValue(iter->key().ToString(), iter->value().ToString(),
  1637. is_key_hex_, is_value_hex_);
  1638. fprintf(stdout, "%s\n", str.c_str());
  1639. }
  1640. }
  1641. if (num_buckets > 1 && is_db_ttl_) {
  1642. PrintBucketCounts(bucket_counts, ttl_start, ttl_end, bucket_size,
  1643. num_buckets);
  1644. } else if(count_delim_) {
  1645. fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
  1646. rtype2.c_str(), c, s2);
  1647. } else {
  1648. fprintf(stdout, "Keys in range: %" PRIu64 "\n", count);
  1649. }
  1650. if (count_only_) {
  1651. fprintf(stdout, "Value size distribution: \n");
  1652. fprintf(stdout, "%s\n", vsize_hist.ToString().c_str());
  1653. }
  1654. // Clean up
  1655. delete iter;
  1656. }
  1657. const std::string ReduceDBLevelsCommand::ARG_NEW_LEVELS = "new_levels";
  1658. const std::string ReduceDBLevelsCommand::ARG_PRINT_OLD_LEVELS =
  1659. "print_old_levels";
  1660. ReduceDBLevelsCommand::ReduceDBLevelsCommand(
  1661. const std::vector<std::string>& /*params*/,
  1662. const std::map<std::string, std::string>& options,
  1663. const std::vector<std::string>& flags)
  1664. : LDBCommand(options, flags, false,
  1665. BuildCmdLineOptions({ARG_NEW_LEVELS, ARG_PRINT_OLD_LEVELS})),
  1666. old_levels_(1 << 7),
  1667. new_levels_(-1),
  1668. print_old_levels_(false) {
  1669. ParseIntOption(option_map_, ARG_NEW_LEVELS, new_levels_, exec_state_);
  1670. print_old_levels_ = IsFlagPresent(flags, ARG_PRINT_OLD_LEVELS);
  1671. if(new_levels_ <= 0) {
  1672. exec_state_ = LDBCommandExecuteResult::Failed(
  1673. " Use --" + ARG_NEW_LEVELS + " to specify a new level number\n");
  1674. }
  1675. }
  1676. std::vector<std::string> ReduceDBLevelsCommand::PrepareArgs(
  1677. const std::string& db_path, int new_levels, bool print_old_level) {
  1678. std::vector<std::string> ret;
  1679. ret.push_back("reduce_levels");
  1680. ret.push_back("--" + ARG_DB + "=" + db_path);
  1681. ret.push_back("--" + ARG_NEW_LEVELS + "=" +
  1682. ROCKSDB_NAMESPACE::ToString(new_levels));
  1683. if(print_old_level) {
  1684. ret.push_back("--" + ARG_PRINT_OLD_LEVELS);
  1685. }
  1686. return ret;
  1687. }
  1688. void ReduceDBLevelsCommand::Help(std::string& ret) {
  1689. ret.append(" ");
  1690. ret.append(ReduceDBLevelsCommand::Name());
  1691. ret.append(" --" + ARG_NEW_LEVELS + "=<New number of levels>");
  1692. ret.append(" [--" + ARG_PRINT_OLD_LEVELS + "]");
  1693. ret.append("\n");
  1694. }
  1695. Options ReduceDBLevelsCommand::PrepareOptionsForOpenDB() {
  1696. Options opt = LDBCommand::PrepareOptionsForOpenDB();
  1697. opt.num_levels = old_levels_;
  1698. opt.max_bytes_for_level_multiplier_additional.resize(opt.num_levels, 1);
  1699. // Disable size compaction
  1700. opt.max_bytes_for_level_base = 1ULL << 50;
  1701. opt.max_bytes_for_level_multiplier = 1;
  1702. return opt;
  1703. }
  1704. Status ReduceDBLevelsCommand::GetOldNumOfLevels(Options& opt,
  1705. int* levels) {
  1706. ImmutableDBOptions db_options(opt);
  1707. EnvOptions soptions;
  1708. std::shared_ptr<Cache> tc(
  1709. NewLRUCache(opt.max_open_files - 10, opt.table_cache_numshardbits));
  1710. const InternalKeyComparator cmp(opt.comparator);
  1711. WriteController wc(opt.delayed_write_rate);
  1712. WriteBufferManager wb(opt.db_write_buffer_size);
  1713. VersionSet versions(db_path_, &db_options, soptions, tc.get(), &wb, &wc,
  1714. /*block_cache_tracer=*/nullptr);
  1715. std::vector<ColumnFamilyDescriptor> dummy;
  1716. ColumnFamilyDescriptor dummy_descriptor(kDefaultColumnFamilyName,
  1717. ColumnFamilyOptions(opt));
  1718. dummy.push_back(dummy_descriptor);
  1719. // We rely the VersionSet::Recover to tell us the internal data structures
  1720. // in the db. And the Recover() should never do any change
  1721. // (like LogAndApply) to the manifest file.
  1722. Status st = versions.Recover(dummy);
  1723. if (!st.ok()) {
  1724. return st;
  1725. }
  1726. int max = -1;
  1727. auto default_cfd = versions.GetColumnFamilySet()->GetDefault();
  1728. for (int i = 0; i < default_cfd->NumberLevels(); i++) {
  1729. if (default_cfd->current()->storage_info()->NumLevelFiles(i)) {
  1730. max = i;
  1731. }
  1732. }
  1733. *levels = max + 1;
  1734. return st;
  1735. }
  1736. void ReduceDBLevelsCommand::DoCommand() {
  1737. if (new_levels_ <= 1) {
  1738. exec_state_ =
  1739. LDBCommandExecuteResult::Failed("Invalid number of levels.\n");
  1740. return;
  1741. }
  1742. Status st;
  1743. Options opt = PrepareOptionsForOpenDB();
  1744. int old_level_num = -1;
  1745. opt.file_system.reset(new LegacyFileSystemWrapper(opt.env));
  1746. ;
  1747. st = GetOldNumOfLevels(opt, &old_level_num);
  1748. if (!st.ok()) {
  1749. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  1750. return;
  1751. }
  1752. if (print_old_levels_) {
  1753. fprintf(stdout, "The old number of levels in use is %d\n", old_level_num);
  1754. }
  1755. if (old_level_num <= new_levels_) {
  1756. return;
  1757. }
  1758. old_levels_ = old_level_num;
  1759. OpenDB();
  1760. if (exec_state_.IsFailed()) {
  1761. return;
  1762. }
  1763. assert(db_ != nullptr);
  1764. // Compact the whole DB to put all files to the highest level.
  1765. fprintf(stdout, "Compacting the db...\n");
  1766. db_->CompactRange(CompactRangeOptions(), GetCfHandle(), nullptr, nullptr);
  1767. CloseDB();
  1768. EnvOptions soptions;
  1769. st = VersionSet::ReduceNumberOfLevels(db_path_, &opt, soptions, new_levels_);
  1770. if (!st.ok()) {
  1771. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  1772. return;
  1773. }
  1774. }
  1775. const std::string ChangeCompactionStyleCommand::ARG_OLD_COMPACTION_STYLE =
  1776. "old_compaction_style";
  1777. const std::string ChangeCompactionStyleCommand::ARG_NEW_COMPACTION_STYLE =
  1778. "new_compaction_style";
  1779. ChangeCompactionStyleCommand::ChangeCompactionStyleCommand(
  1780. const std::vector<std::string>& /*params*/,
  1781. const std::map<std::string, std::string>& options,
  1782. const std::vector<std::string>& flags)
  1783. : LDBCommand(options, flags, false,
  1784. BuildCmdLineOptions(
  1785. {ARG_OLD_COMPACTION_STYLE, ARG_NEW_COMPACTION_STYLE})),
  1786. old_compaction_style_(-1),
  1787. new_compaction_style_(-1) {
  1788. ParseIntOption(option_map_, ARG_OLD_COMPACTION_STYLE, old_compaction_style_,
  1789. exec_state_);
  1790. if (old_compaction_style_ != kCompactionStyleLevel &&
  1791. old_compaction_style_ != kCompactionStyleUniversal) {
  1792. exec_state_ = LDBCommandExecuteResult::Failed(
  1793. "Use --" + ARG_OLD_COMPACTION_STYLE + " to specify old compaction " +
  1794. "style. Check ldb help for proper compaction style value.\n");
  1795. return;
  1796. }
  1797. ParseIntOption(option_map_, ARG_NEW_COMPACTION_STYLE, new_compaction_style_,
  1798. exec_state_);
  1799. if (new_compaction_style_ != kCompactionStyleLevel &&
  1800. new_compaction_style_ != kCompactionStyleUniversal) {
  1801. exec_state_ = LDBCommandExecuteResult::Failed(
  1802. "Use --" + ARG_NEW_COMPACTION_STYLE + " to specify new compaction " +
  1803. "style. Check ldb help for proper compaction style value.\n");
  1804. return;
  1805. }
  1806. if (new_compaction_style_ == old_compaction_style_) {
  1807. exec_state_ = LDBCommandExecuteResult::Failed(
  1808. "Old compaction style is the same as new compaction style. "
  1809. "Nothing to do.\n");
  1810. return;
  1811. }
  1812. if (old_compaction_style_ == kCompactionStyleUniversal &&
  1813. new_compaction_style_ == kCompactionStyleLevel) {
  1814. exec_state_ = LDBCommandExecuteResult::Failed(
  1815. "Convert from universal compaction to level compaction. "
  1816. "Nothing to do.\n");
  1817. return;
  1818. }
  1819. }
  1820. void ChangeCompactionStyleCommand::Help(std::string& ret) {
  1821. ret.append(" ");
  1822. ret.append(ChangeCompactionStyleCommand::Name());
  1823. ret.append(" --" + ARG_OLD_COMPACTION_STYLE + "=<Old compaction style: 0 " +
  1824. "for level compaction, 1 for universal compaction>");
  1825. ret.append(" --" + ARG_NEW_COMPACTION_STYLE + "=<New compaction style: 0 " +
  1826. "for level compaction, 1 for universal compaction>");
  1827. ret.append("\n");
  1828. }
  1829. Options ChangeCompactionStyleCommand::PrepareOptionsForOpenDB() {
  1830. Options opt = LDBCommand::PrepareOptionsForOpenDB();
  1831. if (old_compaction_style_ == kCompactionStyleLevel &&
  1832. new_compaction_style_ == kCompactionStyleUniversal) {
  1833. // In order to convert from level compaction to universal compaction, we
  1834. // need to compact all data into a single file and move it to level 0.
  1835. opt.disable_auto_compactions = true;
  1836. opt.target_file_size_base = INT_MAX;
  1837. opt.target_file_size_multiplier = 1;
  1838. opt.max_bytes_for_level_base = INT_MAX;
  1839. opt.max_bytes_for_level_multiplier = 1;
  1840. }
  1841. return opt;
  1842. }
  1843. void ChangeCompactionStyleCommand::DoCommand() {
  1844. // print db stats before we have made any change
  1845. std::string property;
  1846. std::string files_per_level;
  1847. for (int i = 0; i < db_->NumberLevels(GetCfHandle()); i++) {
  1848. db_->GetProperty(GetCfHandle(),
  1849. "rocksdb.num-files-at-level" + NumberToString(i),
  1850. &property);
  1851. // format print string
  1852. char buf[100];
  1853. snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
  1854. files_per_level += buf;
  1855. }
  1856. fprintf(stdout, "files per level before compaction: %s\n",
  1857. files_per_level.c_str());
  1858. // manual compact into a single file and move the file to level 0
  1859. CompactRangeOptions compact_options;
  1860. compact_options.change_level = true;
  1861. compact_options.target_level = 0;
  1862. db_->CompactRange(compact_options, GetCfHandle(), nullptr, nullptr);
  1863. // verify compaction result
  1864. files_per_level = "";
  1865. int num_files = 0;
  1866. for (int i = 0; i < db_->NumberLevels(GetCfHandle()); i++) {
  1867. db_->GetProperty(GetCfHandle(),
  1868. "rocksdb.num-files-at-level" + NumberToString(i),
  1869. &property);
  1870. // format print string
  1871. char buf[100];
  1872. snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
  1873. files_per_level += buf;
  1874. num_files = atoi(property.c_str());
  1875. // level 0 should have only 1 file
  1876. if (i == 0 && num_files != 1) {
  1877. exec_state_ = LDBCommandExecuteResult::Failed(
  1878. "Number of db files at "
  1879. "level 0 after compaction is " +
  1880. ToString(num_files) + ", not 1.\n");
  1881. return;
  1882. }
  1883. // other levels should have no file
  1884. if (i > 0 && num_files != 0) {
  1885. exec_state_ = LDBCommandExecuteResult::Failed(
  1886. "Number of db files at "
  1887. "level " +
  1888. ToString(i) + " after compaction is " + ToString(num_files) +
  1889. ", not 0.\n");
  1890. return;
  1891. }
  1892. }
  1893. fprintf(stdout, "files per level after compaction: %s\n",
  1894. files_per_level.c_str());
  1895. }
  1896. // ----------------------------------------------------------------------------
  1897. namespace {
  1898. struct StdErrReporter : public log::Reader::Reporter {
  1899. void Corruption(size_t /*bytes*/, const Status& s) override {
  1900. std::cerr << "Corruption detected in log file " << s.ToString() << "\n";
  1901. }
  1902. };
  1903. class InMemoryHandler : public WriteBatch::Handler {
  1904. public:
  1905. InMemoryHandler(std::stringstream& row, bool print_values,
  1906. bool write_after_commit = false)
  1907. : Handler(),
  1908. row_(row),
  1909. print_values_(print_values),
  1910. write_after_commit_(write_after_commit) {}
  1911. void commonPutMerge(const Slice& key, const Slice& value) {
  1912. std::string k = LDBCommand::StringToHex(key.ToString());
  1913. if (print_values_) {
  1914. std::string v = LDBCommand::StringToHex(value.ToString());
  1915. row_ << k << " : ";
  1916. row_ << v << " ";
  1917. } else {
  1918. row_ << k << " ";
  1919. }
  1920. }
  1921. Status PutCF(uint32_t cf, const Slice& key, const Slice& value) override {
  1922. row_ << "PUT(" << cf << ") : ";
  1923. commonPutMerge(key, value);
  1924. return Status::OK();
  1925. }
  1926. Status MergeCF(uint32_t cf, const Slice& key, const Slice& value) override {
  1927. row_ << "MERGE(" << cf << ") : ";
  1928. commonPutMerge(key, value);
  1929. return Status::OK();
  1930. }
  1931. Status MarkNoop(bool) override {
  1932. row_ << "NOOP ";
  1933. return Status::OK();
  1934. }
  1935. Status DeleteCF(uint32_t cf, const Slice& key) override {
  1936. row_ << "DELETE(" << cf << ") : ";
  1937. row_ << LDBCommand::StringToHex(key.ToString()) << " ";
  1938. return Status::OK();
  1939. }
  1940. Status SingleDeleteCF(uint32_t cf, const Slice& key) override {
  1941. row_ << "SINGLE_DELETE(" << cf << ") : ";
  1942. row_ << LDBCommand::StringToHex(key.ToString()) << " ";
  1943. return Status::OK();
  1944. }
  1945. Status DeleteRangeCF(uint32_t cf, const Slice& begin_key,
  1946. const Slice& end_key) override {
  1947. row_ << "DELETE_RANGE(" << cf << ") : ";
  1948. row_ << LDBCommand::StringToHex(begin_key.ToString()) << " ";
  1949. row_ << LDBCommand::StringToHex(end_key.ToString()) << " ";
  1950. return Status::OK();
  1951. }
  1952. Status MarkBeginPrepare(bool unprepare) override {
  1953. row_ << "BEGIN_PREPARE(";
  1954. row_ << (unprepare ? "true" : "false") << ") ";
  1955. return Status::OK();
  1956. }
  1957. Status MarkEndPrepare(const Slice& xid) override {
  1958. row_ << "END_PREPARE(";
  1959. row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
  1960. return Status::OK();
  1961. }
  1962. Status MarkRollback(const Slice& xid) override {
  1963. row_ << "ROLLBACK(";
  1964. row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
  1965. return Status::OK();
  1966. }
  1967. Status MarkCommit(const Slice& xid) override {
  1968. row_ << "COMMIT(";
  1969. row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
  1970. return Status::OK();
  1971. }
  1972. ~InMemoryHandler() override {}
  1973. protected:
  1974. bool WriteAfterCommit() const override { return write_after_commit_; }
  1975. private:
  1976. std::stringstream& row_;
  1977. bool print_values_;
  1978. bool write_after_commit_;
  1979. };
  1980. void DumpWalFile(Options options, std::string wal_file, bool print_header,
  1981. bool print_values, bool is_write_committed,
  1982. LDBCommandExecuteResult* exec_state) {
  1983. Env* env = options.env;
  1984. EnvOptions soptions(options);
  1985. std::unique_ptr<SequentialFileReader> wal_file_reader;
  1986. Status status;
  1987. {
  1988. std::unique_ptr<SequentialFile> file;
  1989. status = env->NewSequentialFile(wal_file, &file, soptions);
  1990. if (status.ok()) {
  1991. wal_file_reader.reset(new SequentialFileReader(
  1992. NewLegacySequentialFileWrapper(file), wal_file));
  1993. }
  1994. }
  1995. if (!status.ok()) {
  1996. if (exec_state) {
  1997. *exec_state = LDBCommandExecuteResult::Failed("Failed to open WAL file " +
  1998. status.ToString());
  1999. } else {
  2000. std::cerr << "Error: Failed to open WAL file " << status.ToString()
  2001. << std::endl;
  2002. }
  2003. } else {
  2004. StdErrReporter reporter;
  2005. uint64_t log_number;
  2006. FileType type;
  2007. // we need the log number, but ParseFilename expects dbname/NNN.log.
  2008. std::string sanitized = wal_file;
  2009. size_t lastslash = sanitized.rfind('/');
  2010. if (lastslash != std::string::npos)
  2011. sanitized = sanitized.substr(lastslash + 1);
  2012. if (!ParseFileName(sanitized, &log_number, &type)) {
  2013. // bogus input, carry on as best we can
  2014. log_number = 0;
  2015. }
  2016. log::Reader reader(options.info_log, std::move(wal_file_reader), &reporter,
  2017. true /* checksum */, log_number);
  2018. std::string scratch;
  2019. WriteBatch batch;
  2020. Slice record;
  2021. std::stringstream row;
  2022. if (print_header) {
  2023. std::cout << "Sequence,Count,ByteSize,Physical Offset,Key(s)";
  2024. if (print_values) {
  2025. std::cout << " : value ";
  2026. }
  2027. std::cout << "\n";
  2028. }
  2029. while (reader.ReadRecord(&record, &scratch)) {
  2030. row.str("");
  2031. if (record.size() < WriteBatchInternal::kHeader) {
  2032. reporter.Corruption(record.size(),
  2033. Status::Corruption("log record too small"));
  2034. } else {
  2035. WriteBatchInternal::SetContents(&batch, record);
  2036. row << WriteBatchInternal::Sequence(&batch) << ",";
  2037. row << WriteBatchInternal::Count(&batch) << ",";
  2038. row << WriteBatchInternal::ByteSize(&batch) << ",";
  2039. row << reader.LastRecordOffset() << ",";
  2040. InMemoryHandler handler(row, print_values, is_write_committed);
  2041. batch.Iterate(&handler);
  2042. row << "\n";
  2043. }
  2044. std::cout << row.str();
  2045. }
  2046. }
  2047. }
  2048. } // namespace
  2049. const std::string WALDumperCommand::ARG_WAL_FILE = "walfile";
  2050. const std::string WALDumperCommand::ARG_WRITE_COMMITTED = "write_committed";
  2051. const std::string WALDumperCommand::ARG_PRINT_VALUE = "print_value";
  2052. const std::string WALDumperCommand::ARG_PRINT_HEADER = "header";
  2053. WALDumperCommand::WALDumperCommand(
  2054. const std::vector<std::string>& /*params*/,
  2055. const std::map<std::string, std::string>& options,
  2056. const std::vector<std::string>& flags)
  2057. : LDBCommand(options, flags, true,
  2058. BuildCmdLineOptions({ARG_WAL_FILE, ARG_WRITE_COMMITTED,
  2059. ARG_PRINT_HEADER, ARG_PRINT_VALUE})),
  2060. print_header_(false),
  2061. print_values_(false),
  2062. is_write_committed_(false) {
  2063. wal_file_.clear();
  2064. std::map<std::string, std::string>::const_iterator itr =
  2065. options.find(ARG_WAL_FILE);
  2066. if (itr != options.end()) {
  2067. wal_file_ = itr->second;
  2068. }
  2069. print_header_ = IsFlagPresent(flags, ARG_PRINT_HEADER);
  2070. print_values_ = IsFlagPresent(flags, ARG_PRINT_VALUE);
  2071. is_write_committed_ = ParseBooleanOption(options, ARG_WRITE_COMMITTED, true);
  2072. if (wal_file_.empty()) {
  2073. exec_state_ = LDBCommandExecuteResult::Failed("Argument " + ARG_WAL_FILE +
  2074. " must be specified.");
  2075. }
  2076. }
  2077. void WALDumperCommand::Help(std::string& ret) {
  2078. ret.append(" ");
  2079. ret.append(WALDumperCommand::Name());
  2080. ret.append(" --" + ARG_WAL_FILE + "=<write_ahead_log_file_path>");
  2081. ret.append(" [--" + ARG_PRINT_HEADER + "] ");
  2082. ret.append(" [--" + ARG_PRINT_VALUE + "] ");
  2083. ret.append(" [--" + ARG_WRITE_COMMITTED + "=true|false] ");
  2084. ret.append("\n");
  2085. }
  2086. void WALDumperCommand::DoCommand() {
  2087. DumpWalFile(options_, wal_file_, print_header_, print_values_,
  2088. is_write_committed_, &exec_state_);
  2089. }
  2090. // ----------------------------------------------------------------------------
  2091. GetCommand::GetCommand(const std::vector<std::string>& params,
  2092. const std::map<std::string, std::string>& options,
  2093. const std::vector<std::string>& flags)
  2094. : LDBCommand(
  2095. options, flags, true,
  2096. BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {
  2097. if (params.size() != 1) {
  2098. exec_state_ = LDBCommandExecuteResult::Failed(
  2099. "<key> must be specified for the get command");
  2100. } else {
  2101. key_ = params.at(0);
  2102. }
  2103. if (is_key_hex_) {
  2104. key_ = HexToString(key_);
  2105. }
  2106. }
  2107. void GetCommand::Help(std::string& ret) {
  2108. ret.append(" ");
  2109. ret.append(GetCommand::Name());
  2110. ret.append(" <key>");
  2111. ret.append(" [--" + ARG_TTL + "]");
  2112. ret.append("\n");
  2113. }
  2114. void GetCommand::DoCommand() {
  2115. if (!db_) {
  2116. assert(GetExecuteState().IsFailed());
  2117. return;
  2118. }
  2119. std::string value;
  2120. Status st = db_->Get(ReadOptions(), GetCfHandle(), key_, &value);
  2121. if (st.ok()) {
  2122. fprintf(stdout, "%s\n",
  2123. (is_value_hex_ ? StringToHex(value) : value).c_str());
  2124. } else {
  2125. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  2126. }
  2127. }
  2128. // ----------------------------------------------------------------------------
  2129. ApproxSizeCommand::ApproxSizeCommand(
  2130. const std::vector<std::string>& /*params*/,
  2131. const std::map<std::string, std::string>& options,
  2132. const std::vector<std::string>& flags)
  2133. : LDBCommand(options, flags, true,
  2134. BuildCmdLineOptions(
  2135. {ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM, ARG_TO})) {
  2136. if (options.find(ARG_FROM) != options.end()) {
  2137. start_key_ = options.find(ARG_FROM)->second;
  2138. } else {
  2139. exec_state_ = LDBCommandExecuteResult::Failed(
  2140. ARG_FROM + " must be specified for approxsize command");
  2141. return;
  2142. }
  2143. if (options.find(ARG_TO) != options.end()) {
  2144. end_key_ = options.find(ARG_TO)->second;
  2145. } else {
  2146. exec_state_ = LDBCommandExecuteResult::Failed(
  2147. ARG_TO + " must be specified for approxsize command");
  2148. return;
  2149. }
  2150. if (is_key_hex_) {
  2151. start_key_ = HexToString(start_key_);
  2152. end_key_ = HexToString(end_key_);
  2153. }
  2154. }
  2155. void ApproxSizeCommand::Help(std::string& ret) {
  2156. ret.append(" ");
  2157. ret.append(ApproxSizeCommand::Name());
  2158. ret.append(HelpRangeCmdArgs());
  2159. ret.append("\n");
  2160. }
  2161. void ApproxSizeCommand::DoCommand() {
  2162. if (!db_) {
  2163. assert(GetExecuteState().IsFailed());
  2164. return;
  2165. }
  2166. Range ranges[1];
  2167. ranges[0] = Range(start_key_, end_key_);
  2168. uint64_t sizes[1];
  2169. db_->GetApproximateSizes(GetCfHandle(), ranges, 1, sizes);
  2170. fprintf(stdout, "%lu\n", (unsigned long)sizes[0]);
  2171. /* Weird that GetApproximateSizes() returns void, although documentation
  2172. * says that it returns a Status object.
  2173. if (!st.ok()) {
  2174. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  2175. }
  2176. */
  2177. }
  2178. // ----------------------------------------------------------------------------
  2179. BatchPutCommand::BatchPutCommand(
  2180. const std::vector<std::string>& params,
  2181. const std::map<std::string, std::string>& options,
  2182. const std::vector<std::string>& flags)
  2183. : LDBCommand(options, flags, false,
  2184. BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
  2185. ARG_VALUE_HEX, ARG_CREATE_IF_MISSING})) {
  2186. if (params.size() < 2) {
  2187. exec_state_ = LDBCommandExecuteResult::Failed(
  2188. "At least one <key> <value> pair must be specified batchput.");
  2189. } else if (params.size() % 2 != 0) {
  2190. exec_state_ = LDBCommandExecuteResult::Failed(
  2191. "Equal number of <key>s and <value>s must be specified for batchput.");
  2192. } else {
  2193. for (size_t i = 0; i < params.size(); i += 2) {
  2194. std::string key = params.at(i);
  2195. std::string value = params.at(i + 1);
  2196. key_values_.push_back(std::pair<std::string, std::string>(
  2197. is_key_hex_ ? HexToString(key) : key,
  2198. is_value_hex_ ? HexToString(value) : value));
  2199. }
  2200. }
  2201. create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
  2202. }
  2203. void BatchPutCommand::Help(std::string& ret) {
  2204. ret.append(" ");
  2205. ret.append(BatchPutCommand::Name());
  2206. ret.append(" <key> <value> [<key> <value>] [..]");
  2207. ret.append(" [--" + ARG_TTL + "]");
  2208. ret.append("\n");
  2209. }
  2210. void BatchPutCommand::DoCommand() {
  2211. if (!db_) {
  2212. assert(GetExecuteState().IsFailed());
  2213. return;
  2214. }
  2215. WriteBatch batch;
  2216. for (std::vector<std::pair<std::string, std::string>>::const_iterator itr =
  2217. key_values_.begin();
  2218. itr != key_values_.end(); ++itr) {
  2219. batch.Put(GetCfHandle(), itr->first, itr->second);
  2220. }
  2221. Status st = db_->Write(WriteOptions(), &batch);
  2222. if (st.ok()) {
  2223. fprintf(stdout, "OK\n");
  2224. } else {
  2225. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  2226. }
  2227. }
  2228. Options BatchPutCommand::PrepareOptionsForOpenDB() {
  2229. Options opt = LDBCommand::PrepareOptionsForOpenDB();
  2230. opt.create_if_missing = create_if_missing_;
  2231. return opt;
  2232. }
  2233. // ----------------------------------------------------------------------------
  2234. ScanCommand::ScanCommand(const std::vector<std::string>& /*params*/,
  2235. const std::map<std::string, std::string>& options,
  2236. const std::vector<std::string>& flags)
  2237. : LDBCommand(
  2238. options, flags, true,
  2239. BuildCmdLineOptions({ARG_TTL, ARG_NO_VALUE, ARG_HEX, ARG_KEY_HEX,
  2240. ARG_TO, ARG_VALUE_HEX, ARG_FROM, ARG_TIMESTAMP,
  2241. ARG_MAX_KEYS, ARG_TTL_START, ARG_TTL_END})),
  2242. start_key_specified_(false),
  2243. end_key_specified_(false),
  2244. max_keys_scanned_(-1),
  2245. no_value_(false) {
  2246. std::map<std::string, std::string>::const_iterator itr =
  2247. options.find(ARG_FROM);
  2248. if (itr != options.end()) {
  2249. start_key_ = itr->second;
  2250. if (is_key_hex_) {
  2251. start_key_ = HexToString(start_key_);
  2252. }
  2253. start_key_specified_ = true;
  2254. }
  2255. itr = options.find(ARG_TO);
  2256. if (itr != options.end()) {
  2257. end_key_ = itr->second;
  2258. if (is_key_hex_) {
  2259. end_key_ = HexToString(end_key_);
  2260. }
  2261. end_key_specified_ = true;
  2262. }
  2263. std::vector<std::string>::const_iterator vitr =
  2264. std::find(flags.begin(), flags.end(), ARG_NO_VALUE);
  2265. if (vitr != flags.end()) {
  2266. no_value_ = true;
  2267. }
  2268. itr = options.find(ARG_MAX_KEYS);
  2269. if (itr != options.end()) {
  2270. try {
  2271. #if defined(CYGWIN)
  2272. max_keys_scanned_ = strtol(itr->second.c_str(), 0, 10);
  2273. #else
  2274. max_keys_scanned_ = std::stoi(itr->second);
  2275. #endif
  2276. } catch (const std::invalid_argument&) {
  2277. exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
  2278. " has an invalid value");
  2279. } catch (const std::out_of_range&) {
  2280. exec_state_ = LDBCommandExecuteResult::Failed(
  2281. ARG_MAX_KEYS + " has a value out-of-range");
  2282. }
  2283. }
  2284. }
  2285. void ScanCommand::Help(std::string& ret) {
  2286. ret.append(" ");
  2287. ret.append(ScanCommand::Name());
  2288. ret.append(HelpRangeCmdArgs());
  2289. ret.append(" [--" + ARG_TTL + "]");
  2290. ret.append(" [--" + ARG_TIMESTAMP + "]");
  2291. ret.append(" [--" + ARG_MAX_KEYS + "=<N>q] ");
  2292. ret.append(" [--" + ARG_TTL_START + "=<N>:- is inclusive]");
  2293. ret.append(" [--" + ARG_TTL_END + "=<N>:- is exclusive]");
  2294. ret.append(" [--" + ARG_NO_VALUE + "]");
  2295. ret.append("\n");
  2296. }
  2297. void ScanCommand::DoCommand() {
  2298. if (!db_) {
  2299. assert(GetExecuteState().IsFailed());
  2300. return;
  2301. }
  2302. int num_keys_scanned = 0;
  2303. ReadOptions scan_read_opts;
  2304. scan_read_opts.total_order_seek = true;
  2305. Iterator* it = db_->NewIterator(scan_read_opts, GetCfHandle());
  2306. if (start_key_specified_) {
  2307. it->Seek(start_key_);
  2308. } else {
  2309. it->SeekToFirst();
  2310. }
  2311. int ttl_start;
  2312. if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
  2313. ttl_start = DBWithTTLImpl::kMinTimestamp; // TTL introduction time
  2314. }
  2315. int ttl_end;
  2316. if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
  2317. ttl_end = DBWithTTLImpl::kMaxTimestamp; // Max time allowed by TTL feature
  2318. }
  2319. if (ttl_end < ttl_start) {
  2320. fprintf(stderr, "Error: End time can't be less than start time\n");
  2321. delete it;
  2322. return;
  2323. }
  2324. if (is_db_ttl_ && timestamp_) {
  2325. fprintf(stdout, "Scanning key-values from %s to %s\n",
  2326. TimeToHumanString(ttl_start).c_str(),
  2327. TimeToHumanString(ttl_end).c_str());
  2328. }
  2329. for ( ;
  2330. it->Valid() && (!end_key_specified_ || it->key().ToString() < end_key_);
  2331. it->Next()) {
  2332. if (is_db_ttl_) {
  2333. TtlIterator* it_ttl = static_cast_with_check<TtlIterator, Iterator>(it);
  2334. int rawtime = it_ttl->timestamp();
  2335. if (rawtime < ttl_start || rawtime >= ttl_end) {
  2336. continue;
  2337. }
  2338. if (timestamp_) {
  2339. fprintf(stdout, "%s ", TimeToHumanString(rawtime).c_str());
  2340. }
  2341. }
  2342. Slice key_slice = it->key();
  2343. std::string formatted_key;
  2344. if (is_key_hex_) {
  2345. formatted_key = "0x" + key_slice.ToString(true /* hex */);
  2346. key_slice = formatted_key;
  2347. } else if (ldb_options_.key_formatter) {
  2348. formatted_key = ldb_options_.key_formatter->Format(key_slice);
  2349. key_slice = formatted_key;
  2350. }
  2351. if (no_value_) {
  2352. fprintf(stdout, "%.*s\n", static_cast<int>(key_slice.size()),
  2353. key_slice.data());
  2354. } else {
  2355. Slice val_slice = it->value();
  2356. std::string formatted_value;
  2357. if (is_value_hex_) {
  2358. formatted_value = "0x" + val_slice.ToString(true /* hex */);
  2359. val_slice = formatted_value;
  2360. }
  2361. fprintf(stdout, "%.*s : %.*s\n", static_cast<int>(key_slice.size()),
  2362. key_slice.data(), static_cast<int>(val_slice.size()),
  2363. val_slice.data());
  2364. }
  2365. num_keys_scanned++;
  2366. if (max_keys_scanned_ >= 0 && num_keys_scanned >= max_keys_scanned_) {
  2367. break;
  2368. }
  2369. }
  2370. if (!it->status().ok()) { // Check for any errors found during the scan
  2371. exec_state_ = LDBCommandExecuteResult::Failed(it->status().ToString());
  2372. }
  2373. delete it;
  2374. }
  2375. // ----------------------------------------------------------------------------
  2376. DeleteCommand::DeleteCommand(const std::vector<std::string>& params,
  2377. const std::map<std::string, std::string>& options,
  2378. const std::vector<std::string>& flags)
  2379. : LDBCommand(options, flags, false,
  2380. BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {
  2381. if (params.size() != 1) {
  2382. exec_state_ = LDBCommandExecuteResult::Failed(
  2383. "KEY must be specified for the delete command");
  2384. } else {
  2385. key_ = params.at(0);
  2386. if (is_key_hex_) {
  2387. key_ = HexToString(key_);
  2388. }
  2389. }
  2390. }
  2391. void DeleteCommand::Help(std::string& ret) {
  2392. ret.append(" ");
  2393. ret.append(DeleteCommand::Name() + " <key>");
  2394. ret.append("\n");
  2395. }
  2396. void DeleteCommand::DoCommand() {
  2397. if (!db_) {
  2398. assert(GetExecuteState().IsFailed());
  2399. return;
  2400. }
  2401. Status st = db_->Delete(WriteOptions(), GetCfHandle(), key_);
  2402. if (st.ok()) {
  2403. fprintf(stdout, "OK\n");
  2404. } else {
  2405. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  2406. }
  2407. }
  2408. DeleteRangeCommand::DeleteRangeCommand(
  2409. const std::vector<std::string>& params,
  2410. const std::map<std::string, std::string>& options,
  2411. const std::vector<std::string>& flags)
  2412. : LDBCommand(options, flags, false,
  2413. BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {
  2414. if (params.size() != 2) {
  2415. exec_state_ = LDBCommandExecuteResult::Failed(
  2416. "begin and end keys must be specified for the delete command");
  2417. } else {
  2418. begin_key_ = params.at(0);
  2419. end_key_ = params.at(1);
  2420. if (is_key_hex_) {
  2421. begin_key_ = HexToString(begin_key_);
  2422. end_key_ = HexToString(end_key_);
  2423. }
  2424. }
  2425. }
  2426. void DeleteRangeCommand::Help(std::string& ret) {
  2427. ret.append(" ");
  2428. ret.append(DeleteRangeCommand::Name() + " <begin key> <end key>");
  2429. ret.append("\n");
  2430. }
  2431. void DeleteRangeCommand::DoCommand() {
  2432. if (!db_) {
  2433. assert(GetExecuteState().IsFailed());
  2434. return;
  2435. }
  2436. Status st =
  2437. db_->DeleteRange(WriteOptions(), GetCfHandle(), begin_key_, end_key_);
  2438. if (st.ok()) {
  2439. fprintf(stdout, "OK\n");
  2440. } else {
  2441. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  2442. }
  2443. }
  2444. PutCommand::PutCommand(const std::vector<std::string>& params,
  2445. const std::map<std::string, std::string>& options,
  2446. const std::vector<std::string>& flags)
  2447. : LDBCommand(options, flags, false,
  2448. BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
  2449. ARG_VALUE_HEX, ARG_CREATE_IF_MISSING})) {
  2450. if (params.size() != 2) {
  2451. exec_state_ = LDBCommandExecuteResult::Failed(
  2452. "<key> and <value> must be specified for the put command");
  2453. } else {
  2454. key_ = params.at(0);
  2455. value_ = params.at(1);
  2456. }
  2457. if (is_key_hex_) {
  2458. key_ = HexToString(key_);
  2459. }
  2460. if (is_value_hex_) {
  2461. value_ = HexToString(value_);
  2462. }
  2463. create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
  2464. }
  2465. void PutCommand::Help(std::string& ret) {
  2466. ret.append(" ");
  2467. ret.append(PutCommand::Name());
  2468. ret.append(" <key> <value> ");
  2469. ret.append(" [--" + ARG_TTL + "]");
  2470. ret.append("\n");
  2471. }
  2472. void PutCommand::DoCommand() {
  2473. if (!db_) {
  2474. assert(GetExecuteState().IsFailed());
  2475. return;
  2476. }
  2477. Status st = db_->Put(WriteOptions(), GetCfHandle(), key_, value_);
  2478. if (st.ok()) {
  2479. fprintf(stdout, "OK\n");
  2480. } else {
  2481. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  2482. }
  2483. }
  2484. Options PutCommand::PrepareOptionsForOpenDB() {
  2485. Options opt = LDBCommand::PrepareOptionsForOpenDB();
  2486. opt.create_if_missing = create_if_missing_;
  2487. return opt;
  2488. }
  2489. // ----------------------------------------------------------------------------
  2490. const char* DBQuerierCommand::HELP_CMD = "help";
  2491. const char* DBQuerierCommand::GET_CMD = "get";
  2492. const char* DBQuerierCommand::PUT_CMD = "put";
  2493. const char* DBQuerierCommand::DELETE_CMD = "delete";
  2494. DBQuerierCommand::DBQuerierCommand(
  2495. const std::vector<std::string>& /*params*/,
  2496. const std::map<std::string, std::string>& options,
  2497. const std::vector<std::string>& flags)
  2498. : LDBCommand(
  2499. options, flags, false,
  2500. BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {
  2501. }
  2502. void DBQuerierCommand::Help(std::string& ret) {
  2503. ret.append(" ");
  2504. ret.append(DBQuerierCommand::Name());
  2505. ret.append(" [--" + ARG_TTL + "]");
  2506. ret.append("\n");
  2507. ret.append(" Starts a REPL shell. Type help for list of available "
  2508. "commands.");
  2509. ret.append("\n");
  2510. }
  2511. void DBQuerierCommand::DoCommand() {
  2512. if (!db_) {
  2513. assert(GetExecuteState().IsFailed());
  2514. return;
  2515. }
  2516. ReadOptions read_options;
  2517. WriteOptions write_options;
  2518. std::string line;
  2519. std::string key;
  2520. std::string value;
  2521. while (getline(std::cin, line, '\n')) {
  2522. // Parse line into std::vector<std::string>
  2523. std::vector<std::string> tokens;
  2524. size_t pos = 0;
  2525. while (true) {
  2526. size_t pos2 = line.find(' ', pos);
  2527. if (pos2 == std::string::npos) {
  2528. break;
  2529. }
  2530. tokens.push_back(line.substr(pos, pos2-pos));
  2531. pos = pos2 + 1;
  2532. }
  2533. tokens.push_back(line.substr(pos));
  2534. const std::string& cmd = tokens[0];
  2535. if (cmd == HELP_CMD) {
  2536. fprintf(stdout,
  2537. "get <key>\n"
  2538. "put <key> <value>\n"
  2539. "delete <key>\n");
  2540. } else if (cmd == DELETE_CMD && tokens.size() == 2) {
  2541. key = (is_key_hex_ ? HexToString(tokens[1]) : tokens[1]);
  2542. db_->Delete(write_options, GetCfHandle(), Slice(key));
  2543. fprintf(stdout, "Successfully deleted %s\n", tokens[1].c_str());
  2544. } else if (cmd == PUT_CMD && tokens.size() == 3) {
  2545. key = (is_key_hex_ ? HexToString(tokens[1]) : tokens[1]);
  2546. value = (is_value_hex_ ? HexToString(tokens[2]) : tokens[2]);
  2547. db_->Put(write_options, GetCfHandle(), Slice(key), Slice(value));
  2548. fprintf(stdout, "Successfully put %s %s\n",
  2549. tokens[1].c_str(), tokens[2].c_str());
  2550. } else if (cmd == GET_CMD && tokens.size() == 2) {
  2551. key = (is_key_hex_ ? HexToString(tokens[1]) : tokens[1]);
  2552. if (db_->Get(read_options, GetCfHandle(), Slice(key), &value).ok()) {
  2553. fprintf(stdout, "%s\n", PrintKeyValue(key, value,
  2554. is_key_hex_, is_value_hex_).c_str());
  2555. } else {
  2556. fprintf(stdout, "Not found %s\n", tokens[1].c_str());
  2557. }
  2558. } else {
  2559. fprintf(stdout, "Unknown command %s\n", line.c_str());
  2560. }
  2561. }
  2562. }
  2563. // ----------------------------------------------------------------------------
  2564. CheckConsistencyCommand::CheckConsistencyCommand(
  2565. const std::vector<std::string>& /*params*/,
  2566. const std::map<std::string, std::string>& options,
  2567. const std::vector<std::string>& flags)
  2568. : LDBCommand(options, flags, false, BuildCmdLineOptions({})) {}
  2569. void CheckConsistencyCommand::Help(std::string& ret) {
  2570. ret.append(" ");
  2571. ret.append(CheckConsistencyCommand::Name());
  2572. ret.append("\n");
  2573. }
  2574. void CheckConsistencyCommand::DoCommand() {
  2575. Options opt = PrepareOptionsForOpenDB();
  2576. opt.paranoid_checks = true;
  2577. if (!exec_state_.IsNotStarted()) {
  2578. return;
  2579. }
  2580. DB* db;
  2581. Status st = DB::OpenForReadOnly(opt, db_path_, &db, false);
  2582. delete db;
  2583. if (st.ok()) {
  2584. fprintf(stdout, "OK\n");
  2585. } else {
  2586. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  2587. }
  2588. }
  2589. // ----------------------------------------------------------------------------
  2590. const std::string CheckPointCommand::ARG_CHECKPOINT_DIR = "checkpoint_dir";
  2591. CheckPointCommand::CheckPointCommand(
  2592. const std::vector<std::string>& /*params*/,
  2593. const std::map<std::string, std::string>& options,
  2594. const std::vector<std::string>& flags)
  2595. : LDBCommand(options, flags, false /* is_read_only */,
  2596. BuildCmdLineOptions({ARG_CHECKPOINT_DIR})) {
  2597. auto itr = options.find(ARG_CHECKPOINT_DIR);
  2598. if (itr != options.end()) {
  2599. checkpoint_dir_ = itr->second;
  2600. }
  2601. }
  2602. void CheckPointCommand::Help(std::string& ret) {
  2603. ret.append(" ");
  2604. ret.append(CheckPointCommand::Name());
  2605. ret.append(" [--" + ARG_CHECKPOINT_DIR + "] ");
  2606. ret.append("\n");
  2607. }
  2608. void CheckPointCommand::DoCommand() {
  2609. if (!db_) {
  2610. assert(GetExecuteState().IsFailed());
  2611. return;
  2612. }
  2613. Checkpoint* checkpoint;
  2614. Status status = Checkpoint::Create(db_, &checkpoint);
  2615. status = checkpoint->CreateCheckpoint(checkpoint_dir_);
  2616. if (status.ok()) {
  2617. fprintf(stdout, "OK\n");
  2618. } else {
  2619. exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  2620. }
  2621. }
  2622. // ----------------------------------------------------------------------------
  2623. RepairCommand::RepairCommand(const std::vector<std::string>& /*params*/,
  2624. const std::map<std::string, std::string>& options,
  2625. const std::vector<std::string>& flags)
  2626. : LDBCommand(options, flags, false, BuildCmdLineOptions({})) {}
  2627. void RepairCommand::Help(std::string& ret) {
  2628. ret.append(" ");
  2629. ret.append(RepairCommand::Name());
  2630. ret.append("\n");
  2631. }
  2632. void RepairCommand::DoCommand() {
  2633. Options options = PrepareOptionsForOpenDB();
  2634. options.info_log.reset(new StderrLogger(InfoLogLevel::WARN_LEVEL));
  2635. Status status = RepairDB(db_path_, options);
  2636. if (status.ok()) {
  2637. fprintf(stdout, "OK\n");
  2638. } else {
  2639. exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  2640. }
  2641. }
  2642. // ----------------------------------------------------------------------------
  2643. const std::string BackupableCommand::ARG_NUM_THREADS = "num_threads";
  2644. const std::string BackupableCommand::ARG_BACKUP_ENV_URI = "backup_env_uri";
  2645. const std::string BackupableCommand::ARG_BACKUP_DIR = "backup_dir";
  2646. const std::string BackupableCommand::ARG_STDERR_LOG_LEVEL = "stderr_log_level";
  2647. BackupableCommand::BackupableCommand(
  2648. const std::vector<std::string>& /*params*/,
  2649. const std::map<std::string, std::string>& options,
  2650. const std::vector<std::string>& flags)
  2651. : LDBCommand(options, flags, false /* is_read_only */,
  2652. BuildCmdLineOptions({ARG_BACKUP_ENV_URI, ARG_BACKUP_DIR,
  2653. ARG_NUM_THREADS, ARG_STDERR_LOG_LEVEL})),
  2654. num_threads_(1) {
  2655. auto itr = options.find(ARG_NUM_THREADS);
  2656. if (itr != options.end()) {
  2657. num_threads_ = std::stoi(itr->second);
  2658. }
  2659. itr = options.find(ARG_BACKUP_ENV_URI);
  2660. if (itr != options.end()) {
  2661. backup_env_uri_ = itr->second;
  2662. }
  2663. itr = options.find(ARG_BACKUP_DIR);
  2664. if (itr == options.end()) {
  2665. exec_state_ = LDBCommandExecuteResult::Failed("--" + ARG_BACKUP_DIR +
  2666. ": missing backup directory");
  2667. } else {
  2668. backup_dir_ = itr->second;
  2669. }
  2670. itr = options.find(ARG_STDERR_LOG_LEVEL);
  2671. if (itr != options.end()) {
  2672. int stderr_log_level = std::stoi(itr->second);
  2673. if (stderr_log_level < 0 ||
  2674. stderr_log_level >= InfoLogLevel::NUM_INFO_LOG_LEVELS) {
  2675. exec_state_ = LDBCommandExecuteResult::Failed(
  2676. ARG_STDERR_LOG_LEVEL + " must be >= 0 and < " +
  2677. std::to_string(InfoLogLevel::NUM_INFO_LOG_LEVELS) + ".");
  2678. } else {
  2679. logger_.reset(
  2680. new StderrLogger(static_cast<InfoLogLevel>(stderr_log_level)));
  2681. }
  2682. }
  2683. }
  2684. void BackupableCommand::Help(const std::string& name, std::string& ret) {
  2685. ret.append(" ");
  2686. ret.append(name);
  2687. ret.append(" [--" + ARG_BACKUP_ENV_URI + "] ");
  2688. ret.append(" [--" + ARG_BACKUP_DIR + "] ");
  2689. ret.append(" [--" + ARG_NUM_THREADS + "] ");
  2690. ret.append(" [--" + ARG_STDERR_LOG_LEVEL + "=<int (InfoLogLevel)>] ");
  2691. ret.append("\n");
  2692. }
  2693. // ----------------------------------------------------------------------------
  2694. BackupCommand::BackupCommand(const std::vector<std::string>& params,
  2695. const std::map<std::string, std::string>& options,
  2696. const std::vector<std::string>& flags)
  2697. : BackupableCommand(params, options, flags) {}
  2698. void BackupCommand::Help(std::string& ret) {
  2699. BackupableCommand::Help(Name(), ret);
  2700. }
  2701. void BackupCommand::DoCommand() {
  2702. BackupEngine* backup_engine;
  2703. Status status;
  2704. if (!db_) {
  2705. assert(GetExecuteState().IsFailed());
  2706. return;
  2707. }
  2708. fprintf(stdout, "open db OK\n");
  2709. Env* custom_env = nullptr;
  2710. Env::LoadEnv(backup_env_uri_, &custom_env, &backup_env_guard_);
  2711. assert(custom_env != nullptr);
  2712. BackupableDBOptions backup_options =
  2713. BackupableDBOptions(backup_dir_, custom_env);
  2714. backup_options.info_log = logger_.get();
  2715. backup_options.max_background_operations = num_threads_;
  2716. status = BackupEngine::Open(custom_env, backup_options, &backup_engine);
  2717. if (status.ok()) {
  2718. fprintf(stdout, "open backup engine OK\n");
  2719. } else {
  2720. exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  2721. return;
  2722. }
  2723. status = backup_engine->CreateNewBackup(db_);
  2724. if (status.ok()) {
  2725. fprintf(stdout, "create new backup OK\n");
  2726. } else {
  2727. exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  2728. return;
  2729. }
  2730. }
  2731. // ----------------------------------------------------------------------------
  2732. RestoreCommand::RestoreCommand(
  2733. const std::vector<std::string>& params,
  2734. const std::map<std::string, std::string>& options,
  2735. const std::vector<std::string>& flags)
  2736. : BackupableCommand(params, options, flags) {}
  2737. void RestoreCommand::Help(std::string& ret) {
  2738. BackupableCommand::Help(Name(), ret);
  2739. }
  2740. void RestoreCommand::DoCommand() {
  2741. Env* custom_env = nullptr;
  2742. Env::LoadEnv(backup_env_uri_, &custom_env, &backup_env_guard_);
  2743. assert(custom_env != nullptr);
  2744. std::unique_ptr<BackupEngineReadOnly> restore_engine;
  2745. Status status;
  2746. {
  2747. BackupableDBOptions opts(backup_dir_, custom_env);
  2748. opts.info_log = logger_.get();
  2749. opts.max_background_operations = num_threads_;
  2750. BackupEngineReadOnly* raw_restore_engine_ptr;
  2751. status =
  2752. BackupEngineReadOnly::Open(custom_env, opts, &raw_restore_engine_ptr);
  2753. if (status.ok()) {
  2754. restore_engine.reset(raw_restore_engine_ptr);
  2755. }
  2756. }
  2757. if (status.ok()) {
  2758. fprintf(stdout, "open restore engine OK\n");
  2759. status = restore_engine->RestoreDBFromLatestBackup(db_path_, db_path_);
  2760. }
  2761. if (status.ok()) {
  2762. fprintf(stdout, "restore from backup OK\n");
  2763. } else {
  2764. exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  2765. }
  2766. }
  2767. // ----------------------------------------------------------------------------
  2768. namespace {
  2769. void DumpSstFile(Options options, std::string filename, bool output_hex,
  2770. bool show_properties) {
  2771. std::string from_key;
  2772. std::string to_key;
  2773. if (filename.length() <= 4 ||
  2774. filename.rfind(".sst") != filename.length() - 4) {
  2775. std::cout << "Invalid sst file name." << std::endl;
  2776. return;
  2777. }
  2778. // no verification
  2779. // TODO: add support for decoding blob indexes in ldb as well
  2780. ROCKSDB_NAMESPACE::SstFileDumper dumper(
  2781. options, filename, /* verify_checksum */ false, output_hex,
  2782. /* decode_blob_index */ false);
  2783. Status st = dumper.ReadSequential(true, std::numeric_limits<uint64_t>::max(),
  2784. false, // has_from
  2785. from_key, false, // has_to
  2786. to_key);
  2787. if (!st.ok()) {
  2788. std::cerr << "Error in reading SST file " << filename << st.ToString()
  2789. << std::endl;
  2790. return;
  2791. }
  2792. if (show_properties) {
  2793. const ROCKSDB_NAMESPACE::TableProperties* table_properties;
  2794. std::shared_ptr<const ROCKSDB_NAMESPACE::TableProperties>
  2795. table_properties_from_reader;
  2796. st = dumper.ReadTableProperties(&table_properties_from_reader);
  2797. if (!st.ok()) {
  2798. std::cerr << filename << ": " << st.ToString()
  2799. << ". Try to use initial table properties" << std::endl;
  2800. table_properties = dumper.GetInitTableProperties();
  2801. } else {
  2802. table_properties = table_properties_from_reader.get();
  2803. }
  2804. if (table_properties != nullptr) {
  2805. std::cout << std::endl << "Table Properties:" << std::endl;
  2806. std::cout << table_properties->ToString("\n") << std::endl;
  2807. }
  2808. }
  2809. }
  2810. } // namespace
  2811. DBFileDumperCommand::DBFileDumperCommand(
  2812. const std::vector<std::string>& /*params*/,
  2813. const std::map<std::string, std::string>& options,
  2814. const std::vector<std::string>& flags)
  2815. : LDBCommand(options, flags, true, BuildCmdLineOptions({})) {}
  2816. void DBFileDumperCommand::Help(std::string& ret) {
  2817. ret.append(" ");
  2818. ret.append(DBFileDumperCommand::Name());
  2819. ret.append("\n");
  2820. }
  2821. void DBFileDumperCommand::DoCommand() {
  2822. if (!db_) {
  2823. assert(GetExecuteState().IsFailed());
  2824. return;
  2825. }
  2826. Status s;
  2827. std::cout << "Manifest File" << std::endl;
  2828. std::cout << "==============================" << std::endl;
  2829. std::string manifest_filename;
  2830. s = ReadFileToString(db_->GetEnv(), CurrentFileName(db_->GetName()),
  2831. &manifest_filename);
  2832. if (!s.ok() || manifest_filename.empty() ||
  2833. manifest_filename.back() != '\n') {
  2834. std::cerr << "Error when reading CURRENT file "
  2835. << CurrentFileName(db_->GetName()) << std::endl;
  2836. }
  2837. // remove the trailing '\n'
  2838. manifest_filename.resize(manifest_filename.size() - 1);
  2839. std::string manifest_filepath = db_->GetName() + "/" + manifest_filename;
  2840. std::cout << manifest_filepath << std::endl;
  2841. DumpManifestFile(options_, manifest_filepath, false, false, false);
  2842. std::cout << std::endl;
  2843. std::cout << "SST Files" << std::endl;
  2844. std::cout << "==============================" << std::endl;
  2845. std::vector<LiveFileMetaData> metadata;
  2846. db_->GetLiveFilesMetaData(&metadata);
  2847. for (auto& fileMetadata : metadata) {
  2848. std::string filename = fileMetadata.db_path + fileMetadata.name;
  2849. std::cout << filename << " level:" << fileMetadata.level << std::endl;
  2850. std::cout << "------------------------------" << std::endl;
  2851. DumpSstFile(options_, filename, false, true);
  2852. std::cout << std::endl;
  2853. }
  2854. std::cout << std::endl;
  2855. std::cout << "Write Ahead Log Files" << std::endl;
  2856. std::cout << "==============================" << std::endl;
  2857. ROCKSDB_NAMESPACE::VectorLogPtr wal_files;
  2858. s = db_->GetSortedWalFiles(wal_files);
  2859. if (!s.ok()) {
  2860. std::cerr << "Error when getting WAL files" << std::endl;
  2861. } else {
  2862. for (auto& wal : wal_files) {
  2863. // TODO(qyang): option.wal_dir should be passed into ldb command
  2864. std::string filename = db_->GetOptions().wal_dir + wal->PathName();
  2865. std::cout << filename << std::endl;
  2866. // TODO(myabandeh): allow configuring is_write_commited
  2867. DumpWalFile(options_, filename, true, true, true /* is_write_commited */,
  2868. &exec_state_);
  2869. }
  2870. }
  2871. }
  2872. void WriteExternalSstFilesCommand::Help(std::string& ret) {
  2873. ret.append(" ");
  2874. ret.append(WriteExternalSstFilesCommand::Name());
  2875. ret.append(" <output_sst_path>");
  2876. ret.append("\n");
  2877. }
  2878. WriteExternalSstFilesCommand::WriteExternalSstFilesCommand(
  2879. const std::vector<std::string>& params,
  2880. const std::map<std::string, std::string>& options,
  2881. const std::vector<std::string>& flags)
  2882. : LDBCommand(
  2883. options, flags, false /* is_read_only */,
  2884. BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM,
  2885. ARG_TO, ARG_CREATE_IF_MISSING})) {
  2886. create_if_missing_ =
  2887. IsFlagPresent(flags, ARG_CREATE_IF_MISSING) ||
  2888. ParseBooleanOption(options, ARG_CREATE_IF_MISSING, false);
  2889. if (params.size() != 1) {
  2890. exec_state_ = LDBCommandExecuteResult::Failed(
  2891. "output SST file path must be specified");
  2892. } else {
  2893. output_sst_path_ = params.at(0);
  2894. }
  2895. }
  2896. void WriteExternalSstFilesCommand::DoCommand() {
  2897. if (!db_) {
  2898. assert(GetExecuteState().IsFailed());
  2899. return;
  2900. }
  2901. ColumnFamilyHandle* cfh = GetCfHandle();
  2902. SstFileWriter sst_file_writer(EnvOptions(), db_->GetOptions(), cfh);
  2903. Status status = sst_file_writer.Open(output_sst_path_);
  2904. if (!status.ok()) {
  2905. exec_state_ = LDBCommandExecuteResult::Failed("failed to open SST file: " +
  2906. status.ToString());
  2907. return;
  2908. }
  2909. int bad_lines = 0;
  2910. std::string line;
  2911. std::ifstream ifs_stdin("/dev/stdin");
  2912. std::istream* istream_p = ifs_stdin.is_open() ? &ifs_stdin : &std::cin;
  2913. while (getline(*istream_p, line, '\n')) {
  2914. std::string key;
  2915. std::string value;
  2916. if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
  2917. status = sst_file_writer.Put(key, value);
  2918. if (!status.ok()) {
  2919. exec_state_ = LDBCommandExecuteResult::Failed(
  2920. "failed to write record to file: " + status.ToString());
  2921. return;
  2922. }
  2923. } else if (0 == line.find("Keys in range:")) {
  2924. // ignore this line
  2925. } else if (0 == line.find("Created bg thread 0x")) {
  2926. // ignore this line
  2927. } else {
  2928. bad_lines++;
  2929. }
  2930. }
  2931. status = sst_file_writer.Finish();
  2932. if (!status.ok()) {
  2933. exec_state_ = LDBCommandExecuteResult::Failed(
  2934. "Failed to finish writing to file: " + status.ToString());
  2935. return;
  2936. }
  2937. if (bad_lines > 0) {
  2938. fprintf(stderr, "Warning: %d bad lines ignored.\n", bad_lines);
  2939. }
  2940. exec_state_ = LDBCommandExecuteResult::Succeed(
  2941. "external SST file written to " + output_sst_path_);
  2942. }
  2943. Options WriteExternalSstFilesCommand::PrepareOptionsForOpenDB() {
  2944. Options opt = LDBCommand::PrepareOptionsForOpenDB();
  2945. opt.create_if_missing = create_if_missing_;
  2946. return opt;
  2947. }
  2948. const std::string IngestExternalSstFilesCommand::ARG_MOVE_FILES = "move_files";
  2949. const std::string IngestExternalSstFilesCommand::ARG_SNAPSHOT_CONSISTENCY =
  2950. "snapshot_consistency";
  2951. const std::string IngestExternalSstFilesCommand::ARG_ALLOW_GLOBAL_SEQNO =
  2952. "allow_global_seqno";
  2953. const std::string IngestExternalSstFilesCommand::ARG_ALLOW_BLOCKING_FLUSH =
  2954. "allow_blocking_flush";
  2955. const std::string IngestExternalSstFilesCommand::ARG_INGEST_BEHIND =
  2956. "ingest_behind";
  2957. const std::string IngestExternalSstFilesCommand::ARG_WRITE_GLOBAL_SEQNO =
  2958. "write_global_seqno";
  2959. void IngestExternalSstFilesCommand::Help(std::string& ret) {
  2960. ret.append(" ");
  2961. ret.append(IngestExternalSstFilesCommand::Name());
  2962. ret.append(" <input_sst_path>");
  2963. ret.append(" [--" + ARG_MOVE_FILES + "] ");
  2964. ret.append(" [--" + ARG_SNAPSHOT_CONSISTENCY + "] ");
  2965. ret.append(" [--" + ARG_ALLOW_GLOBAL_SEQNO + "] ");
  2966. ret.append(" [--" + ARG_ALLOW_BLOCKING_FLUSH + "] ");
  2967. ret.append(" [--" + ARG_INGEST_BEHIND + "] ");
  2968. ret.append(" [--" + ARG_WRITE_GLOBAL_SEQNO + "] ");
  2969. ret.append("\n");
  2970. }
  2971. IngestExternalSstFilesCommand::IngestExternalSstFilesCommand(
  2972. const std::vector<std::string>& params,
  2973. const std::map<std::string, std::string>& options,
  2974. const std::vector<std::string>& flags)
  2975. : LDBCommand(
  2976. options, flags, false /* is_read_only */,
  2977. BuildCmdLineOptions({ARG_MOVE_FILES, ARG_SNAPSHOT_CONSISTENCY,
  2978. ARG_ALLOW_GLOBAL_SEQNO, ARG_CREATE_IF_MISSING,
  2979. ARG_ALLOW_BLOCKING_FLUSH, ARG_INGEST_BEHIND,
  2980. ARG_WRITE_GLOBAL_SEQNO})),
  2981. move_files_(false),
  2982. snapshot_consistency_(true),
  2983. allow_global_seqno_(true),
  2984. allow_blocking_flush_(true),
  2985. ingest_behind_(false),
  2986. write_global_seqno_(true) {
  2987. create_if_missing_ =
  2988. IsFlagPresent(flags, ARG_CREATE_IF_MISSING) ||
  2989. ParseBooleanOption(options, ARG_CREATE_IF_MISSING, false);
  2990. move_files_ = IsFlagPresent(flags, ARG_MOVE_FILES) ||
  2991. ParseBooleanOption(options, ARG_MOVE_FILES, false);
  2992. snapshot_consistency_ =
  2993. IsFlagPresent(flags, ARG_SNAPSHOT_CONSISTENCY) ||
  2994. ParseBooleanOption(options, ARG_SNAPSHOT_CONSISTENCY, true);
  2995. allow_global_seqno_ =
  2996. IsFlagPresent(flags, ARG_ALLOW_GLOBAL_SEQNO) ||
  2997. ParseBooleanOption(options, ARG_ALLOW_GLOBAL_SEQNO, true);
  2998. allow_blocking_flush_ =
  2999. IsFlagPresent(flags, ARG_ALLOW_BLOCKING_FLUSH) ||
  3000. ParseBooleanOption(options, ARG_ALLOW_BLOCKING_FLUSH, true);
  3001. ingest_behind_ = IsFlagPresent(flags, ARG_INGEST_BEHIND) ||
  3002. ParseBooleanOption(options, ARG_INGEST_BEHIND, false);
  3003. write_global_seqno_ =
  3004. IsFlagPresent(flags, ARG_WRITE_GLOBAL_SEQNO) ||
  3005. ParseBooleanOption(options, ARG_WRITE_GLOBAL_SEQNO, true);
  3006. if (allow_global_seqno_) {
  3007. if (!write_global_seqno_) {
  3008. fprintf(stderr,
  3009. "Warning: not writing global_seqno to the ingested SST can\n"
  3010. "prevent older versions of RocksDB from being able to open it\n");
  3011. }
  3012. } else {
  3013. if (write_global_seqno_) {
  3014. exec_state_ = LDBCommandExecuteResult::Failed(
  3015. "ldb cannot write global_seqno to the ingested SST when global_seqno "
  3016. "is not allowed");
  3017. }
  3018. }
  3019. if (params.size() != 1) {
  3020. exec_state_ =
  3021. LDBCommandExecuteResult::Failed("input SST path must be specified");
  3022. } else {
  3023. input_sst_path_ = params.at(0);
  3024. }
  3025. }
  3026. void IngestExternalSstFilesCommand::DoCommand() {
  3027. if (!db_) {
  3028. assert(GetExecuteState().IsFailed());
  3029. return;
  3030. }
  3031. if (GetExecuteState().IsFailed()) {
  3032. return;
  3033. }
  3034. ColumnFamilyHandle* cfh = GetCfHandle();
  3035. IngestExternalFileOptions ifo;
  3036. ifo.move_files = move_files_;
  3037. ifo.snapshot_consistency = snapshot_consistency_;
  3038. ifo.allow_global_seqno = allow_global_seqno_;
  3039. ifo.allow_blocking_flush = allow_blocking_flush_;
  3040. ifo.ingest_behind = ingest_behind_;
  3041. ifo.write_global_seqno = write_global_seqno_;
  3042. Status status = db_->IngestExternalFile(cfh, {input_sst_path_}, ifo);
  3043. if (!status.ok()) {
  3044. exec_state_ = LDBCommandExecuteResult::Failed(
  3045. "failed to ingest external SST: " + status.ToString());
  3046. } else {
  3047. exec_state_ =
  3048. LDBCommandExecuteResult::Succeed("external SST files ingested");
  3049. }
  3050. }
  3051. Options IngestExternalSstFilesCommand::PrepareOptionsForOpenDB() {
  3052. Options opt = LDBCommand::PrepareOptionsForOpenDB();
  3053. opt.create_if_missing = create_if_missing_;
  3054. return opt;
  3055. }
  3056. ListFileRangeDeletesCommand::ListFileRangeDeletesCommand(
  3057. const std::map<std::string, std::string>& options,
  3058. const std::vector<std::string>& flags)
  3059. : LDBCommand(options, flags, true, BuildCmdLineOptions({ARG_MAX_KEYS})) {
  3060. std::map<std::string, std::string>::const_iterator itr =
  3061. options.find(ARG_MAX_KEYS);
  3062. if (itr != options.end()) {
  3063. try {
  3064. #if defined(CYGWIN)
  3065. max_keys_ = strtol(itr->second.c_str(), 0, 10);
  3066. #else
  3067. max_keys_ = std::stoi(itr->second);
  3068. #endif
  3069. } catch (const std::invalid_argument&) {
  3070. exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
  3071. " has an invalid value");
  3072. } catch (const std::out_of_range&) {
  3073. exec_state_ = LDBCommandExecuteResult::Failed(
  3074. ARG_MAX_KEYS + " has a value out-of-range");
  3075. }
  3076. }
  3077. }
  3078. void ListFileRangeDeletesCommand::Help(std::string& ret) {
  3079. ret.append(" ");
  3080. ret.append(ListFileRangeDeletesCommand::Name());
  3081. ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
  3082. ret.append(" : print tombstones in SST files.\n");
  3083. }
  3084. void ListFileRangeDeletesCommand::DoCommand() {
  3085. if (!db_) {
  3086. assert(GetExecuteState().IsFailed());
  3087. return;
  3088. }
  3089. DBImpl* db_impl = static_cast_with_check<DBImpl, DB>(db_->GetRootDB());
  3090. std::string out_str;
  3091. Status st =
  3092. db_impl->TablesRangeTombstoneSummary(GetCfHandle(), max_keys_, &out_str);
  3093. if (st.ok()) {
  3094. TEST_SYNC_POINT_CALLBACK(
  3095. "ListFileRangeDeletesCommand::DoCommand:BeforePrint", &out_str);
  3096. fprintf(stdout, "%s\n", out_str.c_str());
  3097. } else {
  3098. exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  3099. }
  3100. }
  3101. } // namespace ROCKSDB_NAMESPACE
  3102. #endif // ROCKSDB_LITE