important_file_writer_cleaner.cc 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/files/important_file_writer_cleaner.h"
  5. #include <algorithm>
  6. #include <functional>
  7. #include <iterator>
  8. #include <utility>
  9. #include "base/bind.h"
  10. #include "base/files/file_enumerator.h"
  11. #include "base/files/file_util.h"
  12. #include "base/no_destructor.h"
  13. #include "base/process/process.h"
  14. #include "base/task/task_traits.h"
  15. #include "base/task/thread_pool.h"
  16. #include "base/threading/sequenced_task_runner_handle.h"
  17. #include "base/time/time.h"
  18. #include "build/build_config.h"
  19. namespace base {
  20. namespace {
  21. base::Time GetUpperBoundTime() {
  22. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS) || BUILDFLAG(IS_FUCHSIA)
  23. // If process creation time is not available then use instance creation
  24. // time as the upper-bound for old files. Modification times may be
  25. // rounded-down to coarse-grained increments, e.g. FAT has 2s granularity,
  26. // so it is necessary to set the upper-bound earlier than Now() by at least
  27. // that margin to account for modification times being rounded-down.
  28. return Time::Now() - Seconds(2);
  29. #else
  30. return Process::Current().CreationTime() - Seconds(2);
  31. #endif
  32. }
  33. } // namespace
  34. // static
  35. ImportantFileWriterCleaner& ImportantFileWriterCleaner::GetInstance() {
  36. static NoDestructor<ImportantFileWriterCleaner> instance;
  37. return *instance;
  38. }
  39. // static
  40. void ImportantFileWriterCleaner::AddDirectory(const FilePath& directory) {
  41. auto& instance = GetInstance();
  42. scoped_refptr<SequencedTaskRunner> task_runner;
  43. {
  44. AutoLock scoped_lock(instance.task_runner_lock_);
  45. task_runner = instance.task_runner_;
  46. }
  47. if (!task_runner)
  48. return;
  49. if (task_runner->RunsTasksInCurrentSequence()) {
  50. instance.AddDirectoryImpl(directory);
  51. } else {
  52. // Unretained is safe here since the cleaner instance is never destroyed.
  53. task_runner->PostTask(
  54. FROM_HERE, BindOnce(&ImportantFileWriterCleaner::AddDirectoryImpl,
  55. Unretained(&instance), directory));
  56. }
  57. }
  58. void ImportantFileWriterCleaner::Initialize() {
  59. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  60. AutoLock scoped_lock(task_runner_lock_);
  61. DCHECK(!task_runner_ || task_runner_ == SequencedTaskRunnerHandle::Get());
  62. task_runner_ = SequencedTaskRunnerHandle::Get();
  63. }
  64. void ImportantFileWriterCleaner::Start() {
  65. #if DCHECK_IS_ON()
  66. {
  67. AutoLock scoped_lock(task_runner_lock_);
  68. DCHECK(task_runner_);
  69. }
  70. #endif
  71. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  72. if (is_started())
  73. return;
  74. started_ = true;
  75. if (!pending_directories_.empty())
  76. ScheduleTask();
  77. }
  78. void ImportantFileWriterCleaner::Stop() {
  79. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  80. if (!is_started())
  81. return;
  82. if (is_running())
  83. stop_flag_.store(true, std::memory_order_relaxed);
  84. else
  85. DoStop();
  86. }
  87. void ImportantFileWriterCleaner::UninitializeForTesting() {
  88. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  89. DCHECK(!is_started());
  90. {
  91. AutoLock scoped_lock(task_runner_lock_);
  92. task_runner_ = nullptr;
  93. }
  94. // AddDirectory may have been called after Stop. Clear the containers just in
  95. // case.
  96. important_directories_.clear();
  97. pending_directories_.clear();
  98. DETACH_FROM_SEQUENCE(sequence_checker_);
  99. }
  100. base::Time ImportantFileWriterCleaner::GetUpperBoundTimeForTest() const {
  101. return upper_bound_time_;
  102. }
  103. ImportantFileWriterCleaner::ImportantFileWriterCleaner()
  104. : upper_bound_time_(GetUpperBoundTime()) {
  105. DETACH_FROM_SEQUENCE(sequence_checker_);
  106. }
  107. void ImportantFileWriterCleaner::AddDirectoryImpl(const FilePath& directory) {
  108. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  109. if (!important_directories_.insert(directory).second)
  110. return; // This directory has already been seen.
  111. pending_directories_.push_back(directory);
  112. if (!is_started())
  113. return; // Nothing more to do if Start() has not been called.
  114. // Start the background task if it's not already running. If it is running, a
  115. // new task will be posted on completion of the current one by
  116. // OnBackgroundTaskFinished to handle all directories added while it was
  117. // running.
  118. if (!is_running())
  119. ScheduleTask();
  120. }
  121. void ImportantFileWriterCleaner::ScheduleTask() {
  122. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  123. DCHECK(is_started());
  124. DCHECK(!is_running());
  125. DCHECK(!pending_directories_.empty());
  126. DCHECK(!stop_flag_.load(std::memory_order_relaxed));
  127. // Pass the set of directories to be processed.
  128. running_ = ThreadPool::PostTaskAndReplyWithResult(
  129. FROM_HERE,
  130. {TaskPriority::BEST_EFFORT, TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN,
  131. MayBlock()},
  132. BindOnce(&ImportantFileWriterCleaner::CleanInBackground,
  133. upper_bound_time_, std::move(pending_directories_),
  134. std::ref(stop_flag_)),
  135. // Unretained is safe here since the cleaner instance is never destroyed.
  136. BindOnce(&ImportantFileWriterCleaner::OnBackgroundTaskFinished,
  137. Unretained(this)));
  138. }
  139. // static
  140. bool ImportantFileWriterCleaner::CleanInBackground(
  141. Time upper_bound_time,
  142. std::vector<FilePath> directories,
  143. std::atomic_bool& stop_flag) {
  144. DCHECK(!directories.empty());
  145. for (auto scan = directories.begin(), end = directories.end(); scan != end;
  146. ++scan) {
  147. const auto& directory = *scan;
  148. FileEnumerator file_enum(
  149. directory, /*recursive=*/false, FileEnumerator::FILES,
  150. FormatTemporaryFileName(FILE_PATH_LITERAL("*")).value());
  151. for (FilePath path = file_enum.Next(); !path.empty();
  152. path = file_enum.Next()) {
  153. const FileEnumerator::FileInfo info = file_enum.GetInfo();
  154. if (info.GetLastModifiedTime() >= upper_bound_time)
  155. continue;
  156. // Cleanup is a best-effort process, so ignore any failures here and
  157. // continue to clean as much as possible. Metrics tell us that ~98.4% of
  158. // directories are cleaned with no failures.
  159. DeleteFile(path);
  160. // Break out without checking for the next file if a stop is requested.
  161. if (stop_flag.load(std::memory_order_relaxed))
  162. return false;
  163. }
  164. }
  165. return true;
  166. }
  167. void ImportantFileWriterCleaner::OnBackgroundTaskFinished(
  168. bool processing_completed) {
  169. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  170. running_ = false;
  171. // There are no other accessors of |stop_flag_| at this point, so atomic
  172. // operations aren't needed. There is no way to read it without such, so use
  173. // the same (relaxed) ordering as elsewhere.
  174. const bool stop = stop_flag_.exchange(false, std::memory_order_relaxed);
  175. DCHECK(stop || processing_completed);
  176. if (stop) {
  177. DoStop();
  178. } else if (!pending_directories_.empty()) {
  179. // Run the task again with the new directories.
  180. ScheduleTask();
  181. } // else do nothing until a new directory is added.
  182. }
  183. void ImportantFileWriterCleaner::DoStop() {
  184. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  185. DCHECK(is_started());
  186. DCHECK(!is_running());
  187. important_directories_.clear();
  188. pending_directories_.clear();
  189. started_ = false;
  190. }
  191. } // namespace base