Roll src/third_party/WebKit 4619053:6b63e20 (svn 201059:201060)
[chromium-blink-merge.git] / base / files / important_file_writer.cc
blob1529107bdf36c114c90ed60a67534d75b0a4dbb0
1 // Copyright (c) 2011 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.
5 #include "base/files/important_file_writer.h"
7 #include <stdio.h>
9 #include <string>
11 #include "base/bind.h"
12 #include "base/critical_closure.h"
13 #include "base/debug/alias.h"
14 #include "base/files/file.h"
15 #include "base/files/file_path.h"
16 #include "base/files/file_util.h"
17 #include "base/logging.h"
18 #include "base/metrics/histogram.h"
19 #include "base/numerics/safe_conversions.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_util.h"
22 #include "base/task_runner.h"
23 #include "base/task_runner_util.h"
24 #include "base/threading/thread.h"
25 #include "base/time/time.h"
27 namespace base {
29 namespace {
31 const int kDefaultCommitIntervalMs = 10000;
33 // This enum is used to define the buckets for an enumerated UMA histogram.
34 // Hence,
35 // (a) existing enumerated constants should never be deleted or reordered, and
36 // (b) new constants should only be appended at the end of the enumeration.
37 enum TempFileFailure {
38 FAILED_CREATING,
39 FAILED_OPENING,
40 FAILED_CLOSING, // Unused.
41 FAILED_WRITING,
42 FAILED_RENAMING,
43 FAILED_FLUSHING,
44 TEMP_FILE_FAILURE_MAX
47 void LogFailure(const FilePath& path, TempFileFailure failure_code,
48 const std::string& message) {
49 UMA_HISTOGRAM_ENUMERATION("ImportantFile.TempFileFailures", failure_code,
50 TEMP_FILE_FAILURE_MAX);
51 DPLOG(WARNING) << "temp file failure: " << path.value() << " : " << message;
54 // Helper function to call WriteFileAtomically() with a scoped_ptr<std::string>.
55 bool WriteScopedStringToFileAtomically(const FilePath& path,
56 scoped_ptr<std::string> data) {
57 return ImportantFileWriter::WriteFileAtomically(path, *data);
60 } // namespace
62 // static
63 bool ImportantFileWriter::WriteFileAtomically(const FilePath& path,
64 const std::string& data) {
65 #if defined(OS_CHROMEOS)
66 // On Chrome OS, chrome gets killed when it cannot finish shutdown quickly,
67 // and this function seems to be one of the slowest shutdown steps.
68 // Include some info to the report for investigation. crbug.com/418627
69 // TODO(hashimoto): Remove this.
70 struct {
71 size_t data_size;
72 char path[128];
73 } file_info;
74 file_info.data_size = data.size();
75 strlcpy(file_info.path, path.value().c_str(), arraysize(file_info.path));
76 debug::Alias(&file_info);
77 #endif
79 // Write the data to a temp file then rename to avoid data loss if we crash
80 // while writing the file. Ensure that the temp file is on the same volume
81 // as target file, so it can be moved in one step, and that the temp file
82 // is securely created.
83 FilePath tmp_file_path;
84 if (!CreateTemporaryFileInDir(path.DirName(), &tmp_file_path)) {
85 LogFailure(path, FAILED_CREATING, "could not create temporary file");
86 return false;
89 File tmp_file(tmp_file_path, File::FLAG_OPEN | File::FLAG_WRITE);
90 if (!tmp_file.IsValid()) {
91 LogFailure(path, FAILED_OPENING, "could not open temporary file");
92 return false;
95 // If this fails in the wild, something really bad is going on.
96 const int data_length = checked_cast<int32_t>(data.length());
97 int bytes_written = tmp_file.Write(0, data.data(), data_length);
98 bool flush_success = tmp_file.Flush();
99 tmp_file.Close();
101 if (bytes_written < data_length) {
102 LogFailure(path, FAILED_WRITING, "error writing, bytes_written=" +
103 IntToString(bytes_written));
104 DeleteFile(tmp_file_path, false);
105 return false;
108 if (!flush_success) {
109 LogFailure(path, FAILED_FLUSHING, "error flushing");
110 DeleteFile(tmp_file_path, false);
111 return false;
114 if (!ReplaceFile(tmp_file_path, path, nullptr)) {
115 LogFailure(path, FAILED_RENAMING, "could not rename temporary file");
116 DeleteFile(tmp_file_path, false);
117 return false;
120 return true;
123 ImportantFileWriter::ImportantFileWriter(
124 const FilePath& path,
125 const scoped_refptr<SequencedTaskRunner>& task_runner)
126 : ImportantFileWriter(
127 path,
128 task_runner,
129 TimeDelta::FromMilliseconds(kDefaultCommitIntervalMs)) {
132 ImportantFileWriter::ImportantFileWriter(
133 const FilePath& path,
134 const scoped_refptr<SequencedTaskRunner>& task_runner,
135 TimeDelta interval)
136 : path_(path),
137 task_runner_(task_runner),
138 serializer_(nullptr),
139 commit_interval_(interval),
140 weak_factory_(this) {
141 DCHECK(CalledOnValidThread());
142 DCHECK(task_runner_);
145 ImportantFileWriter::~ImportantFileWriter() {
146 // We're usually a member variable of some other object, which also tends
147 // to be our serializer. It may not be safe to call back to the parent object
148 // being destructed.
149 DCHECK(!HasPendingWrite());
152 bool ImportantFileWriter::HasPendingWrite() const {
153 DCHECK(CalledOnValidThread());
154 return timer_.IsRunning();
157 void ImportantFileWriter::WriteNow(scoped_ptr<std::string> data) {
158 DCHECK(CalledOnValidThread());
159 if (!IsValueInRangeForNumericType<int32_t>(data->length())) {
160 NOTREACHED();
161 return;
164 if (HasPendingWrite())
165 timer_.Stop();
167 auto task = Bind(&WriteScopedStringToFileAtomically, path_, Passed(&data));
168 if (!PostWriteTask(task)) {
169 // Posting the task to background message loop is not expected
170 // to fail, but if it does, avoid losing data and just hit the disk
171 // on the current thread.
172 NOTREACHED();
174 task.Run();
178 void ImportantFileWriter::ScheduleWrite(DataSerializer* serializer) {
179 DCHECK(CalledOnValidThread());
181 DCHECK(serializer);
182 serializer_ = serializer;
184 if (!timer_.IsRunning()) {
185 timer_.Start(FROM_HERE, commit_interval_, this,
186 &ImportantFileWriter::DoScheduledWrite);
190 void ImportantFileWriter::DoScheduledWrite() {
191 DCHECK(serializer_);
192 scoped_ptr<std::string> data(new std::string);
193 if (serializer_->SerializeData(data.get())) {
194 WriteNow(data.Pass());
195 } else {
196 DLOG(WARNING) << "failed to serialize data to be saved in "
197 << path_.value();
199 serializer_ = nullptr;
202 void ImportantFileWriter::RegisterOnNextSuccessfulWriteCallback(
203 const Closure& on_next_successful_write) {
204 DCHECK(on_next_successful_write_.is_null());
205 on_next_successful_write_ = on_next_successful_write;
208 bool ImportantFileWriter::PostWriteTask(const Callback<bool()>& task) {
209 // TODO(gab): This code could always use PostTaskAndReplyWithResult and let
210 // ForwardSuccessfulWrite() no-op if |on_next_successful_write_| is null, but
211 // PostTaskAndReply causes memory leaks in tests (crbug.com/371974) and
212 // suppressing all of those is unrealistic hence we avoid most of them by
213 // using PostTask() in the typical scenario below.
214 if (!on_next_successful_write_.is_null()) {
215 return PostTaskAndReplyWithResult(
216 task_runner_.get(),
217 FROM_HERE,
218 MakeCriticalClosure(task),
219 Bind(&ImportantFileWriter::ForwardSuccessfulWrite,
220 weak_factory_.GetWeakPtr()));
222 return task_runner_->PostTask(
223 FROM_HERE,
224 MakeCriticalClosure(Bind(IgnoreResult(task))));
227 void ImportantFileWriter::ForwardSuccessfulWrite(bool result) {
228 DCHECK(CalledOnValidThread());
229 if (result && !on_next_successful_write_.is_null()) {
230 on_next_successful_write_.Run();
231 on_next_successful_write_.Reset();
235 } // namespace base