sst_file_writer.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. #include "rocksdb/sst_file_writer.h"
  6. #include <vector>
  7. #include "db/dbformat.h"
  8. #include "env/composite_env_wrapper.h"
  9. #include "file/writable_file_writer.h"
  10. #include "rocksdb/table.h"
  11. #include "table/block_based/block_based_table_builder.h"
  12. #include "table/sst_file_writer_collectors.h"
  13. #include "test_util/sync_point.h"
  14. namespace ROCKSDB_NAMESPACE {
  15. const std::string ExternalSstFilePropertyNames::kVersion =
  16. "rocksdb.external_sst_file.version";
  17. const std::string ExternalSstFilePropertyNames::kGlobalSeqno =
  18. "rocksdb.external_sst_file.global_seqno";
  19. #ifndef ROCKSDB_LITE
  20. const size_t kFadviseTrigger = 1024 * 1024; // 1MB
  21. struct SstFileWriter::Rep {
  22. Rep(const EnvOptions& _env_options, const Options& options,
  23. Env::IOPriority _io_priority, const Comparator* _user_comparator,
  24. ColumnFamilyHandle* _cfh, bool _invalidate_page_cache, bool _skip_filters)
  25. : env_options(_env_options),
  26. ioptions(options),
  27. mutable_cf_options(options),
  28. io_priority(_io_priority),
  29. internal_comparator(_user_comparator),
  30. cfh(_cfh),
  31. invalidate_page_cache(_invalidate_page_cache),
  32. last_fadvise_size(0),
  33. skip_filters(_skip_filters) {}
  34. std::unique_ptr<WritableFileWriter> file_writer;
  35. std::unique_ptr<TableBuilder> builder;
  36. EnvOptions env_options;
  37. ImmutableCFOptions ioptions;
  38. MutableCFOptions mutable_cf_options;
  39. Env::IOPriority io_priority;
  40. InternalKeyComparator internal_comparator;
  41. ExternalSstFileInfo file_info;
  42. InternalKey ikey;
  43. std::string column_family_name;
  44. ColumnFamilyHandle* cfh;
  45. // If true, We will give the OS a hint that this file pages is not needed
  46. // every time we write 1MB to the file.
  47. bool invalidate_page_cache;
  48. // The size of the file during the last time we called Fadvise to remove
  49. // cached pages from page cache.
  50. uint64_t last_fadvise_size;
  51. bool skip_filters;
  52. Status Add(const Slice& user_key, const Slice& value,
  53. const ValueType value_type) {
  54. if (!builder) {
  55. return Status::InvalidArgument("File is not opened");
  56. }
  57. if (file_info.num_entries == 0) {
  58. file_info.smallest_key.assign(user_key.data(), user_key.size());
  59. } else {
  60. if (internal_comparator.user_comparator()->Compare(
  61. user_key, file_info.largest_key) <= 0) {
  62. // Make sure that keys are added in order
  63. return Status::InvalidArgument(
  64. "Keys must be added in strict ascending order.");
  65. }
  66. }
  67. // TODO(tec) : For external SST files we could omit the seqno and type.
  68. switch (value_type) {
  69. case ValueType::kTypeValue:
  70. ikey.Set(user_key, 0 /* Sequence Number */,
  71. ValueType::kTypeValue /* Put */);
  72. break;
  73. case ValueType::kTypeMerge:
  74. ikey.Set(user_key, 0 /* Sequence Number */,
  75. ValueType::kTypeMerge /* Merge */);
  76. break;
  77. case ValueType::kTypeDeletion:
  78. ikey.Set(user_key, 0 /* Sequence Number */,
  79. ValueType::kTypeDeletion /* Delete */);
  80. break;
  81. default:
  82. return Status::InvalidArgument("Value type is not supported");
  83. }
  84. builder->Add(ikey.Encode(), value);
  85. // update file info
  86. file_info.num_entries++;
  87. file_info.largest_key.assign(user_key.data(), user_key.size());
  88. file_info.file_size = builder->FileSize();
  89. InvalidatePageCache(false /* closing */);
  90. return Status::OK();
  91. }
  92. Status DeleteRange(const Slice& begin_key, const Slice& end_key) {
  93. if (!builder) {
  94. return Status::InvalidArgument("File is not opened");
  95. }
  96. RangeTombstone tombstone(begin_key, end_key, 0 /* Sequence Number */);
  97. if (file_info.num_range_del_entries == 0) {
  98. file_info.smallest_range_del_key.assign(tombstone.start_key_.data(),
  99. tombstone.start_key_.size());
  100. file_info.largest_range_del_key.assign(tombstone.end_key_.data(),
  101. tombstone.end_key_.size());
  102. } else {
  103. if (internal_comparator.user_comparator()->Compare(
  104. tombstone.start_key_, file_info.smallest_range_del_key) < 0) {
  105. file_info.smallest_range_del_key.assign(tombstone.start_key_.data(),
  106. tombstone.start_key_.size());
  107. }
  108. if (internal_comparator.user_comparator()->Compare(
  109. tombstone.end_key_, file_info.largest_range_del_key) > 0) {
  110. file_info.largest_range_del_key.assign(tombstone.end_key_.data(),
  111. tombstone.end_key_.size());
  112. }
  113. }
  114. auto ikey_and_end_key = tombstone.Serialize();
  115. builder->Add(ikey_and_end_key.first.Encode(), ikey_and_end_key.second);
  116. // update file info
  117. file_info.num_range_del_entries++;
  118. file_info.file_size = builder->FileSize();
  119. InvalidatePageCache(false /* closing */);
  120. return Status::OK();
  121. }
  122. void InvalidatePageCache(bool closing) {
  123. if (invalidate_page_cache == false) {
  124. // Fadvise disabled
  125. return;
  126. }
  127. uint64_t bytes_since_last_fadvise =
  128. builder->FileSize() - last_fadvise_size;
  129. if (bytes_since_last_fadvise > kFadviseTrigger || closing) {
  130. TEST_SYNC_POINT_CALLBACK("SstFileWriter::Rep::InvalidatePageCache",
  131. &(bytes_since_last_fadvise));
  132. // Tell the OS that we dont need this file in page cache
  133. file_writer->InvalidateCache(0, 0);
  134. last_fadvise_size = builder->FileSize();
  135. }
  136. }
  137. };
  138. SstFileWriter::SstFileWriter(const EnvOptions& env_options,
  139. const Options& options,
  140. const Comparator* user_comparator,
  141. ColumnFamilyHandle* column_family,
  142. bool invalidate_page_cache,
  143. Env::IOPriority io_priority, bool skip_filters)
  144. : rep_(new Rep(env_options, options, io_priority, user_comparator,
  145. column_family, invalidate_page_cache, skip_filters)) {
  146. rep_->file_info.file_size = 0;
  147. }
  148. SstFileWriter::~SstFileWriter() {
  149. if (rep_->builder) {
  150. // User did not call Finish() or Finish() failed, we need to
  151. // abandon the builder.
  152. rep_->builder->Abandon();
  153. }
  154. }
  155. Status SstFileWriter::Open(const std::string& file_path) {
  156. Rep* r = rep_.get();
  157. Status s;
  158. std::unique_ptr<WritableFile> sst_file;
  159. s = r->ioptions.env->NewWritableFile(file_path, &sst_file, r->env_options);
  160. if (!s.ok()) {
  161. return s;
  162. }
  163. sst_file->SetIOPriority(r->io_priority);
  164. CompressionType compression_type;
  165. CompressionOptions compression_opts;
  166. if (r->ioptions.bottommost_compression != kDisableCompressionOption) {
  167. compression_type = r->ioptions.bottommost_compression;
  168. if (r->ioptions.bottommost_compression_opts.enabled) {
  169. compression_opts = r->ioptions.bottommost_compression_opts;
  170. } else {
  171. compression_opts = r->ioptions.compression_opts;
  172. }
  173. } else if (!r->ioptions.compression_per_level.empty()) {
  174. // Use the compression of the last level if we have per level compression
  175. compression_type = *(r->ioptions.compression_per_level.rbegin());
  176. compression_opts = r->ioptions.compression_opts;
  177. } else {
  178. compression_type = r->mutable_cf_options.compression;
  179. compression_opts = r->ioptions.compression_opts;
  180. }
  181. uint64_t sample_for_compression =
  182. r->mutable_cf_options.sample_for_compression;
  183. std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
  184. int_tbl_prop_collector_factories;
  185. // SstFileWriter properties collector to add SstFileWriter version.
  186. int_tbl_prop_collector_factories.emplace_back(
  187. new SstFileWriterPropertiesCollectorFactory(2 /* version */,
  188. 0 /* global_seqno*/));
  189. // User collector factories
  190. auto user_collector_factories =
  191. r->ioptions.table_properties_collector_factories;
  192. for (size_t i = 0; i < user_collector_factories.size(); i++) {
  193. int_tbl_prop_collector_factories.emplace_back(
  194. new UserKeyTablePropertiesCollectorFactory(
  195. user_collector_factories[i]));
  196. }
  197. int unknown_level = -1;
  198. uint32_t cf_id;
  199. if (r->cfh != nullptr) {
  200. // user explicitly specified that this file will be ingested into cfh,
  201. // we can persist this information in the file.
  202. cf_id = r->cfh->GetID();
  203. r->column_family_name = r->cfh->GetName();
  204. } else {
  205. r->column_family_name = "";
  206. cf_id = TablePropertiesCollectorFactory::Context::kUnknownColumnFamily;
  207. }
  208. TableBuilderOptions table_builder_options(
  209. r->ioptions, r->mutable_cf_options, r->internal_comparator,
  210. &int_tbl_prop_collector_factories, compression_type,
  211. sample_for_compression, compression_opts, r->skip_filters,
  212. r->column_family_name, unknown_level);
  213. r->file_writer.reset(
  214. new WritableFileWriter(NewLegacyWritableFileWrapper(std::move(sst_file)),
  215. file_path, r->env_options, r->ioptions.env,
  216. nullptr /* stats */, r->ioptions.listeners));
  217. // TODO(tec) : If table_factory is using compressed block cache, we will
  218. // be adding the external sst file blocks into it, which is wasteful.
  219. r->builder.reset(r->ioptions.table_factory->NewTableBuilder(
  220. table_builder_options, cf_id, r->file_writer.get()));
  221. r->file_info = ExternalSstFileInfo();
  222. r->file_info.file_path = file_path;
  223. r->file_info.version = 2;
  224. return s;
  225. }
  226. Status SstFileWriter::Add(const Slice& user_key, const Slice& value) {
  227. return rep_->Add(user_key, value, ValueType::kTypeValue);
  228. }
  229. Status SstFileWriter::Put(const Slice& user_key, const Slice& value) {
  230. return rep_->Add(user_key, value, ValueType::kTypeValue);
  231. }
  232. Status SstFileWriter::Merge(const Slice& user_key, const Slice& value) {
  233. return rep_->Add(user_key, value, ValueType::kTypeMerge);
  234. }
  235. Status SstFileWriter::Delete(const Slice& user_key) {
  236. return rep_->Add(user_key, Slice(), ValueType::kTypeDeletion);
  237. }
  238. Status SstFileWriter::DeleteRange(const Slice& begin_key,
  239. const Slice& end_key) {
  240. return rep_->DeleteRange(begin_key, end_key);
  241. }
  242. Status SstFileWriter::Finish(ExternalSstFileInfo* file_info) {
  243. Rep* r = rep_.get();
  244. if (!r->builder) {
  245. return Status::InvalidArgument("File is not opened");
  246. }
  247. if (r->file_info.num_entries == 0 &&
  248. r->file_info.num_range_del_entries == 0) {
  249. return Status::InvalidArgument("Cannot create sst file with no entries");
  250. }
  251. Status s = r->builder->Finish();
  252. r->file_info.file_size = r->builder->FileSize();
  253. if (s.ok()) {
  254. s = r->file_writer->Sync(r->ioptions.use_fsync);
  255. r->InvalidatePageCache(true /* closing */);
  256. if (s.ok()) {
  257. s = r->file_writer->Close();
  258. }
  259. }
  260. if (!s.ok()) {
  261. r->ioptions.env->DeleteFile(r->file_info.file_path);
  262. }
  263. if (file_info != nullptr) {
  264. *file_info = r->file_info;
  265. }
  266. r->builder.reset();
  267. return s;
  268. }
  269. uint64_t SstFileWriter::FileSize() {
  270. return rep_->file_info.file_size;
  271. }
  272. #endif // !ROCKSDB_LITE
  273. } // namespace ROCKSDB_NAMESPACE