file_util.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. #include "file/file_util.h"
  7. #include <algorithm>
  8. #include <string>
  9. #include "file/random_access_file_reader.h"
  10. #include "file/sequence_file_reader.h"
  11. #include "file/sst_file_manager_impl.h"
  12. #include "file/writable_file_writer.h"
  13. #include "rocksdb/env.h"
  14. #include "rocksdb/statistics.h"
  15. namespace ROCKSDB_NAMESPACE {
  16. // Utility function to copy a file up to a specified length
  17. IOStatus CopyFile(FileSystem* fs, const std::string& source,
  18. Temperature src_temp_hint,
  19. std::unique_ptr<WritableFileWriter>& dest_writer,
  20. uint64_t size, bool use_fsync,
  21. const std::shared_ptr<IOTracer>& io_tracer,
  22. uint64_t max_read_buffer_size,
  23. const std::optional<IOOptions>& readIOOptions,
  24. const std::optional<IOOptions>& writeIOOptions) {
  25. FileOptions soptions;
  26. IOStatus io_s;
  27. std::unique_ptr<SequentialFileReader> src_reader;
  28. const IOOptions opts;
  29. {
  30. soptions.temperature = src_temp_hint;
  31. std::unique_ptr<FSSequentialFile> srcfile;
  32. io_s = fs->NewSequentialFile(source, soptions, &srcfile, nullptr);
  33. if (!io_s.ok()) {
  34. return io_s;
  35. }
  36. if (size == 0) {
  37. // default argument means copy everything
  38. io_s =
  39. fs->GetFileSize(source, readIOOptions.value_or(opts), &size, nullptr);
  40. if (!io_s.ok()) {
  41. return io_s;
  42. }
  43. }
  44. src_reader.reset(
  45. new SequentialFileReader(std::move(srcfile), source, io_tracer));
  46. }
  47. const size_t read_buffer_size = std::max(
  48. static_cast<size_t>(4096), static_cast<size_t>(max_read_buffer_size));
  49. std::unique_ptr<char[]> buffer;
  50. buffer.reset(new char[read_buffer_size]);
  51. Env::IOPriority read_rate_limiter_priority = Env::IO_TOTAL;
  52. if (readIOOptions.has_value()) {
  53. read_rate_limiter_priority = readIOOptions.value().rate_limiter_priority;
  54. }
  55. Slice slice;
  56. while (size > 0) {
  57. size_t bytes_to_read = std::min(static_cast<size_t>(read_buffer_size),
  58. static_cast<size_t>(size));
  59. // TODO: rate limit copy file
  60. io_s = status_to_io_status(src_reader->Read(
  61. bytes_to_read, &slice, buffer.get(),
  62. read_rate_limiter_priority /* rate_limiter_priority */));
  63. if (!io_s.ok()) {
  64. return io_s;
  65. }
  66. if (slice.size() == 0) {
  67. return IOStatus::Corruption(
  68. "File smaller than expected for copy: " + source + " expecting " +
  69. std::to_string(size) + " more bytes after " +
  70. std::to_string(dest_writer->GetFileSize()));
  71. }
  72. io_s = dest_writer->Append(writeIOOptions.value_or(opts), slice);
  73. if (!io_s.ok()) {
  74. return io_s;
  75. }
  76. size -= slice.size();
  77. }
  78. return dest_writer->Sync(writeIOOptions.value_or(opts), use_fsync);
  79. }
  80. IOStatus CopyFile(FileSystem* fs, const std::string& source,
  81. Temperature src_temp_hint, const std::string& destination,
  82. Temperature dst_temp, uint64_t size, bool use_fsync,
  83. const std::shared_ptr<IOTracer>& io_tracer,
  84. uint64_t max_read_buffer_size,
  85. const std::optional<IOOptions>& readIOOptions,
  86. const std::optional<IOOptions>& writeIOOptions) {
  87. FileOptions options;
  88. IOStatus io_s;
  89. std::unique_ptr<WritableFileWriter> dest_writer;
  90. {
  91. options.temperature = dst_temp;
  92. std::unique_ptr<FSWritableFile> destfile;
  93. io_s = fs->NewWritableFile(destination, options, &destfile, nullptr);
  94. if (!io_s.ok()) {
  95. return io_s;
  96. }
  97. // TODO: pass in Histograms if the destination file is sst or blob
  98. dest_writer.reset(
  99. new WritableFileWriter(std::move(destfile), destination, options));
  100. }
  101. return CopyFile(fs, source, src_temp_hint, dest_writer, size, use_fsync,
  102. io_tracer, max_read_buffer_size, readIOOptions,
  103. writeIOOptions);
  104. }
  105. // Utility function to create a file with the provided contents
  106. IOStatus CreateFile(FileSystem* fs, const std::string& destination,
  107. const std::string& contents, bool use_fsync) {
  108. const EnvOptions soptions;
  109. IOStatus io_s;
  110. std::unique_ptr<WritableFileWriter> dest_writer;
  111. const IOOptions opts;
  112. std::unique_ptr<FSWritableFile> destfile;
  113. io_s = fs->NewWritableFile(destination, soptions, &destfile, nullptr);
  114. if (!io_s.ok()) {
  115. return io_s;
  116. }
  117. // TODO: pass in Histograms if the destination file is sst or blob
  118. dest_writer.reset(
  119. new WritableFileWriter(std::move(destfile), destination, soptions));
  120. io_s = dest_writer->Append(opts, Slice(contents));
  121. if (!io_s.ok()) {
  122. return io_s;
  123. }
  124. return dest_writer->Sync(opts, use_fsync);
  125. }
  126. Status DeleteDBFile(const ImmutableDBOptions* db_options,
  127. const std::string& fname, const std::string& dir_to_sync,
  128. const bool force_bg, const bool force_fg) {
  129. SstFileManagerImpl* sfm = static_cast_with_check<SstFileManagerImpl>(
  130. db_options->sst_file_manager.get());
  131. if (sfm && !force_fg) {
  132. return sfm->ScheduleFileDeletion(fname, dir_to_sync, force_bg);
  133. } else {
  134. return db_options->env->DeleteFile(fname);
  135. }
  136. }
  137. Status DeleteUnaccountedDBFile(const ImmutableDBOptions* db_options,
  138. const std::string& fname,
  139. const std::string& dir_to_sync,
  140. const bool force_bg, const bool force_fg,
  141. std::optional<int32_t> bucket) {
  142. SstFileManagerImpl* sfm = static_cast_with_check<SstFileManagerImpl>(
  143. db_options->sst_file_manager.get());
  144. if (sfm && !force_fg) {
  145. return sfm->ScheduleUnaccountedFileDeletion(fname, dir_to_sync, force_bg,
  146. bucket);
  147. } else {
  148. return db_options->env->DeleteFile(fname);
  149. }
  150. }
  151. // requested_checksum_func_name brings the function name of the checksum
  152. // generator in checksum_factory. Empty string is permitted, in which case the
  153. // name of the generator created by the factory is unchecked. When
  154. // `requested_checksum_func_name` is non-empty, however, the created generator's
  155. // name must match it, otherwise an `InvalidArgument` error is returned.
  156. IOStatus GenerateOneFileChecksum(
  157. FileSystem* fs, const std::string& file_path,
  158. FileChecksumGenFactory* checksum_factory,
  159. const std::string& requested_checksum_func_name, std::string* file_checksum,
  160. std::string* file_checksum_func_name,
  161. size_t verify_checksums_readahead_size, bool /*allow_mmap_reads*/,
  162. std::shared_ptr<IOTracer>& io_tracer, RateLimiter* rate_limiter,
  163. const ReadOptions& read_options, Statistics* stats, SystemClock* clock) {
  164. if (checksum_factory == nullptr) {
  165. return IOStatus::InvalidArgument("Checksum factory is invalid");
  166. }
  167. assert(file_checksum != nullptr);
  168. assert(file_checksum_func_name != nullptr);
  169. FileChecksumGenContext gen_context;
  170. gen_context.requested_checksum_func_name = requested_checksum_func_name;
  171. gen_context.file_name = file_path;
  172. std::unique_ptr<FileChecksumGenerator> checksum_generator =
  173. checksum_factory->CreateFileChecksumGenerator(gen_context);
  174. if (checksum_generator == nullptr) {
  175. std::string msg =
  176. "Cannot get the file checksum generator based on the requested "
  177. "checksum function name: " +
  178. requested_checksum_func_name +
  179. " from checksum factory: " + checksum_factory->Name();
  180. return IOStatus::InvalidArgument(msg);
  181. } else {
  182. // For backward compatibility and use in file ingestion clients where there
  183. // is no stored checksum function name, `requested_checksum_func_name` can
  184. // be empty. If we give the requested checksum function name, we expect it
  185. // is the same name of the checksum generator.
  186. if (!requested_checksum_func_name.empty() &&
  187. checksum_generator->Name() != requested_checksum_func_name) {
  188. std::string msg = "Expected file checksum generator named '" +
  189. requested_checksum_func_name +
  190. "', while the factory created one "
  191. "named '" +
  192. checksum_generator->Name() + "'";
  193. return IOStatus::InvalidArgument(msg);
  194. }
  195. }
  196. uint64_t size;
  197. IOStatus io_s;
  198. std::unique_ptr<RandomAccessFileReader> reader;
  199. {
  200. std::unique_ptr<FSRandomAccessFile> r_file;
  201. io_s = fs->NewRandomAccessFile(file_path, FileOptions(), &r_file, nullptr);
  202. if (!io_s.ok()) {
  203. return io_s;
  204. }
  205. io_s = fs->GetFileSize(file_path, IOOptions(), &size, nullptr);
  206. if (!io_s.ok()) {
  207. return io_s;
  208. }
  209. reader.reset(new RandomAccessFileReader(
  210. std::move(r_file), file_path, clock, io_tracer, stats,
  211. Histograms::SST_READ_MICROS, nullptr, rate_limiter));
  212. }
  213. // Found that 256 KB readahead size provides the best performance, based on
  214. // experiments, for auto readahead. Experiment data is in PR #3282.
  215. size_t default_max_read_ahead_size = 256 * 1024;
  216. size_t readahead_size = (verify_checksums_readahead_size != 0)
  217. ? verify_checksums_readahead_size
  218. : default_max_read_ahead_size;
  219. std::unique_ptr<char[]> buf;
  220. if (reader->use_direct_io()) {
  221. size_t alignment = reader->file()->GetRequiredBufferAlignment();
  222. readahead_size = (readahead_size + alignment - 1) & ~(alignment - 1);
  223. }
  224. buf.reset(new char[readahead_size]);
  225. Slice slice;
  226. uint64_t offset = 0;
  227. IOOptions opts;
  228. IODebugContext dbg;
  229. io_s = reader->PrepareIOOptions(read_options, opts, &dbg);
  230. if (!io_s.ok()) {
  231. return io_s;
  232. }
  233. while (size > 0) {
  234. size_t bytes_to_read =
  235. static_cast<size_t>(std::min(uint64_t{readahead_size}, size));
  236. io_s = reader->Read(opts, offset, bytes_to_read, &slice, buf.get(), nullptr,
  237. &dbg);
  238. if (!io_s.ok()) {
  239. return IOStatus::Corruption("file read failed with error: " +
  240. io_s.ToString());
  241. }
  242. if (slice.size() == 0) {
  243. return IOStatus::Corruption(
  244. "File smaller than expected for checksum: " + file_path +
  245. " expecting " + std::to_string(size) + " more bytes after " +
  246. std::to_string(offset));
  247. }
  248. checksum_generator->Update(slice.data(), slice.size());
  249. size -= slice.size();
  250. offset += slice.size();
  251. TEST_SYNC_POINT("GenerateOneFileChecksum::Chunk:0");
  252. }
  253. checksum_generator->Finalize();
  254. *file_checksum = checksum_generator->GetChecksum();
  255. *file_checksum_func_name = checksum_generator->Name();
  256. return IOStatus::OK();
  257. }
  258. Status DestroyDir(Env* env, const std::string& dir) {
  259. Status s;
  260. if (env->FileExists(dir).IsNotFound()) {
  261. return s;
  262. }
  263. std::vector<std::string> files_in_dir;
  264. s = env->GetChildren(dir, &files_in_dir);
  265. if (s.ok()) {
  266. for (auto& file_in_dir : files_in_dir) {
  267. std::string path = dir + "/" + file_in_dir;
  268. bool is_dir = false;
  269. s = env->IsDirectory(path, &is_dir);
  270. if (s.ok()) {
  271. if (is_dir) {
  272. s = DestroyDir(env, path);
  273. } else {
  274. s = env->DeleteFile(path);
  275. }
  276. } else if (s.IsNotSupported()) {
  277. s = Status::OK();
  278. }
  279. if (!s.ok()) {
  280. // IsDirectory, etc. might not report NotFound
  281. if (s.IsNotFound() || env->FileExists(path).IsNotFound()) {
  282. // Allow files to be deleted externally
  283. s = Status::OK();
  284. } else {
  285. break;
  286. }
  287. }
  288. }
  289. }
  290. if (s.ok()) {
  291. s = env->DeleteDir(dir);
  292. // DeleteDir might or might not report NotFound
  293. if (!s.ok() && (s.IsNotFound() || env->FileExists(dir).IsNotFound())) {
  294. // Allow to be deleted externally
  295. s = Status::OK();
  296. }
  297. }
  298. return s;
  299. }
  300. } // namespace ROCKSDB_NAMESPACE