plain_table_builder.cc 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. #ifndef ROCKSDB_LITE
  6. #include "table/plain/plain_table_builder.h"
  7. #include <assert.h>
  8. #include <string>
  9. #include <limits>
  10. #include <map>
  11. #include "db/dbformat.h"
  12. #include "file/writable_file_writer.h"
  13. #include "rocksdb/comparator.h"
  14. #include "rocksdb/env.h"
  15. #include "rocksdb/filter_policy.h"
  16. #include "rocksdb/options.h"
  17. #include "rocksdb/table.h"
  18. #include "table/block_based/block_builder.h"
  19. #include "table/format.h"
  20. #include "table/meta_blocks.h"
  21. #include "table/plain/plain_table_bloom.h"
  22. #include "table/plain/plain_table_factory.h"
  23. #include "table/plain/plain_table_index.h"
  24. #include "util/coding.h"
  25. #include "util/crc32c.h"
  26. #include "util/stop_watch.h"
  27. namespace ROCKSDB_NAMESPACE {
  28. namespace {
  29. // a utility that helps writing block content to the file
  30. // @offset will advance if @block_contents was successfully written.
  31. // @block_handle the block handle this particular block.
  32. Status WriteBlock(const Slice& block_contents, WritableFileWriter* file,
  33. uint64_t* offset, BlockHandle* block_handle) {
  34. block_handle->set_offset(*offset);
  35. block_handle->set_size(block_contents.size());
  36. Status s = file->Append(block_contents);
  37. if (s.ok()) {
  38. *offset += block_contents.size();
  39. }
  40. return s;
  41. }
  42. } // namespace
  43. // kPlainTableMagicNumber was picked by running
  44. // echo rocksdb.table.plain | sha1sum
  45. // and taking the leading 64 bits.
  46. extern const uint64_t kPlainTableMagicNumber = 0x8242229663bf9564ull;
  47. extern const uint64_t kLegacyPlainTableMagicNumber = 0x4f3418eb7a8f13b8ull;
  48. PlainTableBuilder::PlainTableBuilder(
  49. const ImmutableCFOptions& ioptions, const MutableCFOptions& moptions,
  50. const std::vector<std::unique_ptr<IntTblPropCollectorFactory>>*
  51. int_tbl_prop_collector_factories,
  52. uint32_t column_family_id, WritableFileWriter* file, uint32_t user_key_len,
  53. EncodingType encoding_type, size_t index_sparseness,
  54. uint32_t bloom_bits_per_key, const std::string& column_family_name,
  55. uint32_t num_probes, size_t huge_page_tlb_size, double hash_table_ratio,
  56. bool store_index_in_file)
  57. : ioptions_(ioptions),
  58. moptions_(moptions),
  59. bloom_block_(num_probes),
  60. file_(file),
  61. bloom_bits_per_key_(bloom_bits_per_key),
  62. huge_page_tlb_size_(huge_page_tlb_size),
  63. encoder_(encoding_type, user_key_len, moptions.prefix_extractor.get(),
  64. index_sparseness),
  65. store_index_in_file_(store_index_in_file),
  66. prefix_extractor_(moptions.prefix_extractor.get()) {
  67. // Build index block and save it in the file if hash_table_ratio > 0
  68. if (store_index_in_file_) {
  69. assert(hash_table_ratio > 0 || IsTotalOrderMode());
  70. index_builder_.reset(new PlainTableIndexBuilder(
  71. &arena_, ioptions, moptions.prefix_extractor.get(), index_sparseness,
  72. hash_table_ratio, huge_page_tlb_size_));
  73. properties_.user_collected_properties
  74. [PlainTablePropertyNames::kBloomVersion] = "1"; // For future use
  75. }
  76. properties_.fixed_key_len = user_key_len;
  77. // for plain table, we put all the data in a big chuck.
  78. properties_.num_data_blocks = 1;
  79. // Fill it later if store_index_in_file_ == true
  80. properties_.index_size = 0;
  81. properties_.filter_size = 0;
  82. // To support roll-back to previous version, now still use version 0 for
  83. // plain encoding.
  84. properties_.format_version = (encoding_type == kPlain) ? 0 : 1;
  85. properties_.column_family_id = column_family_id;
  86. properties_.column_family_name = column_family_name;
  87. properties_.prefix_extractor_name = moptions_.prefix_extractor != nullptr
  88. ? moptions_.prefix_extractor->Name()
  89. : "nullptr";
  90. std::string val;
  91. PutFixed32(&val, static_cast<uint32_t>(encoder_.GetEncodingType()));
  92. properties_.user_collected_properties
  93. [PlainTablePropertyNames::kEncodingType] = val;
  94. for (auto& collector_factories : *int_tbl_prop_collector_factories) {
  95. table_properties_collectors_.emplace_back(
  96. collector_factories->CreateIntTblPropCollector(column_family_id));
  97. }
  98. }
  99. PlainTableBuilder::~PlainTableBuilder() {
  100. }
  101. void PlainTableBuilder::Add(const Slice& key, const Slice& value) {
  102. // temp buffer for metadata bytes between key and value.
  103. char meta_bytes_buf[6];
  104. size_t meta_bytes_buf_size = 0;
  105. ParsedInternalKey internal_key;
  106. if (!ParseInternalKey(key, &internal_key)) {
  107. assert(false);
  108. return;
  109. }
  110. if (internal_key.type == kTypeRangeDeletion) {
  111. status_ = Status::NotSupported("Range deletion unsupported");
  112. return;
  113. }
  114. // Store key hash
  115. if (store_index_in_file_) {
  116. if (moptions_.prefix_extractor == nullptr) {
  117. keys_or_prefixes_hashes_.push_back(GetSliceHash(internal_key.user_key));
  118. } else {
  119. Slice prefix =
  120. moptions_.prefix_extractor->Transform(internal_key.user_key);
  121. keys_or_prefixes_hashes_.push_back(GetSliceHash(prefix));
  122. }
  123. }
  124. // Write value
  125. assert(offset_ <= std::numeric_limits<uint32_t>::max());
  126. auto prev_offset = static_cast<uint32_t>(offset_);
  127. // Write out the key
  128. encoder_.AppendKey(key, file_, &offset_, meta_bytes_buf,
  129. &meta_bytes_buf_size);
  130. if (SaveIndexInFile()) {
  131. index_builder_->AddKeyPrefix(GetPrefix(internal_key), prev_offset);
  132. }
  133. // Write value length
  134. uint32_t value_size = static_cast<uint32_t>(value.size());
  135. char* end_ptr =
  136. EncodeVarint32(meta_bytes_buf + meta_bytes_buf_size, value_size);
  137. assert(end_ptr <= meta_bytes_buf + sizeof(meta_bytes_buf));
  138. meta_bytes_buf_size = end_ptr - meta_bytes_buf;
  139. file_->Append(Slice(meta_bytes_buf, meta_bytes_buf_size));
  140. // Write value
  141. file_->Append(value);
  142. offset_ += value_size + meta_bytes_buf_size;
  143. properties_.num_entries++;
  144. properties_.raw_key_size += key.size();
  145. properties_.raw_value_size += value.size();
  146. if (internal_key.type == kTypeDeletion ||
  147. internal_key.type == kTypeSingleDeletion) {
  148. properties_.num_deletions++;
  149. } else if (internal_key.type == kTypeMerge) {
  150. properties_.num_merge_operands++;
  151. }
  152. // notify property collectors
  153. NotifyCollectTableCollectorsOnAdd(
  154. key, value, offset_, table_properties_collectors_, ioptions_.info_log);
  155. }
  156. Status PlainTableBuilder::status() const { return status_; }
  157. Status PlainTableBuilder::Finish() {
  158. assert(!closed_);
  159. closed_ = true;
  160. properties_.data_size = offset_;
  161. // Write the following blocks
  162. // 1. [meta block: bloom] - optional
  163. // 2. [meta block: index] - optional
  164. // 3. [meta block: properties]
  165. // 4. [metaindex block]
  166. // 5. [footer]
  167. MetaIndexBuilder meta_index_builer;
  168. if (store_index_in_file_ && (properties_.num_entries > 0)) {
  169. assert(properties_.num_entries <= std::numeric_limits<uint32_t>::max());
  170. Status s;
  171. BlockHandle bloom_block_handle;
  172. if (bloom_bits_per_key_ > 0) {
  173. bloom_block_.SetTotalBits(
  174. &arena_,
  175. static_cast<uint32_t>(properties_.num_entries) * bloom_bits_per_key_,
  176. ioptions_.bloom_locality, huge_page_tlb_size_, ioptions_.info_log);
  177. PutVarint32(&properties_.user_collected_properties
  178. [PlainTablePropertyNames::kNumBloomBlocks],
  179. bloom_block_.GetNumBlocks());
  180. bloom_block_.AddKeysHashes(keys_or_prefixes_hashes_);
  181. Slice bloom_finish_result = bloom_block_.Finish();
  182. properties_.filter_size = bloom_finish_result.size();
  183. s = WriteBlock(bloom_finish_result, file_, &offset_, &bloom_block_handle);
  184. if (!s.ok()) {
  185. return s;
  186. }
  187. meta_index_builer.Add(BloomBlockBuilder::kBloomBlock, bloom_block_handle);
  188. }
  189. BlockHandle index_block_handle;
  190. Slice index_finish_result = index_builder_->Finish();
  191. properties_.index_size = index_finish_result.size();
  192. s = WriteBlock(index_finish_result, file_, &offset_, &index_block_handle);
  193. if (!s.ok()) {
  194. return s;
  195. }
  196. meta_index_builer.Add(PlainTableIndexBuilder::kPlainTableIndexBlock,
  197. index_block_handle);
  198. }
  199. // Calculate bloom block size and index block size
  200. PropertyBlockBuilder property_block_builder;
  201. // -- Add basic properties
  202. property_block_builder.AddTableProperty(properties_);
  203. property_block_builder.Add(properties_.user_collected_properties);
  204. // -- Add user collected properties
  205. NotifyCollectTableCollectorsOnFinish(table_properties_collectors_,
  206. ioptions_.info_log,
  207. &property_block_builder);
  208. // -- Write property block
  209. BlockHandle property_block_handle;
  210. auto s = WriteBlock(
  211. property_block_builder.Finish(),
  212. file_,
  213. &offset_,
  214. &property_block_handle
  215. );
  216. if (!s.ok()) {
  217. return s;
  218. }
  219. meta_index_builer.Add(kPropertiesBlock, property_block_handle);
  220. // -- write metaindex block
  221. BlockHandle metaindex_block_handle;
  222. s = WriteBlock(
  223. meta_index_builer.Finish(),
  224. file_,
  225. &offset_,
  226. &metaindex_block_handle
  227. );
  228. if (!s.ok()) {
  229. return s;
  230. }
  231. // Write Footer
  232. // no need to write out new footer if we're using default checksum
  233. Footer footer(kLegacyPlainTableMagicNumber, 0);
  234. footer.set_metaindex_handle(metaindex_block_handle);
  235. footer.set_index_handle(BlockHandle::NullBlockHandle());
  236. std::string footer_encoding;
  237. footer.EncodeTo(&footer_encoding);
  238. s = file_->Append(footer_encoding);
  239. if (s.ok()) {
  240. offset_ += footer_encoding.size();
  241. }
  242. if (file_ != nullptr) {
  243. file_checksum_ = file_->GetFileChecksum();
  244. }
  245. return s;
  246. }
  247. void PlainTableBuilder::Abandon() {
  248. closed_ = true;
  249. }
  250. uint64_t PlainTableBuilder::NumEntries() const {
  251. return properties_.num_entries;
  252. }
  253. uint64_t PlainTableBuilder::FileSize() const {
  254. return offset_;
  255. }
  256. const char* PlainTableBuilder::GetFileChecksumFuncName() const {
  257. if (file_ != nullptr) {
  258. return file_->GetFileChecksumFuncName();
  259. } else {
  260. return kUnknownFileChecksumFuncName.c_str();
  261. }
  262. }
  263. } // namespace ROCKSDB_NAMESPACE
  264. #endif // ROCKSDB_LITE