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"
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/strings/string_number_conversions.h"
20 #include "base/strings/string_util.h"
21 #include "base/task_runner.h"
22 #include "base/task_runner_util.h"
23 #include "base/threading/thread.h"
24 #include "base/time/time.h"
30 const int kDefaultCommitIntervalMs
= 10000;
32 // This enum is used to define the buckets for an enumerated UMA histogram.
34 // (a) existing enumerated constants should never be deleted or reordered, and
35 // (b) new constants should only be appended at the end of the enumeration.
36 enum TempFileFailure
{
39 FAILED_CLOSING
, // Unused.
46 void LogFailure(const FilePath
& path
, TempFileFailure failure_code
,
47 const std::string
& message
) {
48 UMA_HISTOGRAM_ENUMERATION("ImportantFile.TempFileFailures", failure_code
,
49 TEMP_FILE_FAILURE_MAX
);
50 DPLOG(WARNING
) << "temp file failure: " << path
.value().c_str()
57 bool ImportantFileWriter::WriteFileAtomically(const FilePath
& path
,
58 const std::string
& data
) {
59 #if defined(OS_CHROMEOS)
60 // On Chrome OS, chrome gets killed when it cannot finish shutdown quickly,
61 // and this function seems to be one of the slowest shutdown steps.
62 // Include some info to the report for investigation. crbug.com/418627
63 // TODO(hashimoto): Remove this.
68 file_info
.data_size
= data
.size();
69 base::strlcpy(file_info
.path
, path
.value().c_str(),
70 arraysize(file_info
.path
));
71 base::debug::Alias(&file_info
);
73 // Write the data to a temp file then rename to avoid data loss if we crash
74 // while writing the file. Ensure that the temp file is on the same volume
75 // as target file, so it can be moved in one step, and that the temp file
76 // is securely created.
77 FilePath tmp_file_path
;
78 if (!base::CreateTemporaryFileInDir(path
.DirName(), &tmp_file_path
)) {
79 LogFailure(path
, FAILED_CREATING
, "could not create temporary file");
83 File
tmp_file(tmp_file_path
, File::FLAG_OPEN
| File::FLAG_WRITE
);
84 if (!tmp_file
.IsValid()) {
85 LogFailure(path
, FAILED_OPENING
, "could not open temporary file");
89 // If this happens in the wild something really bad is going on.
90 CHECK_LE(data
.length(), static_cast<size_t>(kint32max
));
91 int bytes_written
= tmp_file
.Write(0, data
.data(),
92 static_cast<int>(data
.length()));
93 bool flush_success
= tmp_file
.Flush();
96 if (bytes_written
< static_cast<int>(data
.length())) {
97 LogFailure(path
, FAILED_WRITING
, "error writing, bytes_written=" +
98 IntToString(bytes_written
));
99 base::DeleteFile(tmp_file_path
, false);
103 if (!flush_success
) {
104 LogFailure(path
, FAILED_FLUSHING
, "error flushing");
105 base::DeleteFile(tmp_file_path
, false);
109 if (!base::ReplaceFile(tmp_file_path
, path
, NULL
)) {
110 LogFailure(path
, FAILED_RENAMING
, "could not rename temporary file");
111 base::DeleteFile(tmp_file_path
, false);
118 ImportantFileWriter::ImportantFileWriter(
119 const FilePath
& path
,
120 const scoped_refptr
<base::SequencedTaskRunner
>& task_runner
)
122 task_runner_(task_runner
),
124 commit_interval_(TimeDelta::FromMilliseconds(kDefaultCommitIntervalMs
)),
125 weak_factory_(this) {
126 DCHECK(CalledOnValidThread());
127 DCHECK(task_runner_
.get());
130 ImportantFileWriter::~ImportantFileWriter() {
131 // We're usually a member variable of some other object, which also tends
132 // to be our serializer. It may not be safe to call back to the parent object
134 DCHECK(!HasPendingWrite());
137 bool ImportantFileWriter::HasPendingWrite() const {
138 DCHECK(CalledOnValidThread());
139 return timer_
.IsRunning();
142 void ImportantFileWriter::WriteNow(const std::string
& data
) {
143 DCHECK(CalledOnValidThread());
144 if (data
.length() > static_cast<size_t>(kint32max
)) {
149 if (HasPendingWrite())
152 if (!PostWriteTask(data
)) {
153 // Posting the task to background message loop is not expected
154 // to fail, but if it does, avoid losing data and just hit the disk
155 // on the current thread.
158 WriteFileAtomically(path_
, data
);
162 void ImportantFileWriter::ScheduleWrite(DataSerializer
* serializer
) {
163 DCHECK(CalledOnValidThread());
166 serializer_
= serializer
;
168 if (!timer_
.IsRunning()) {
169 timer_
.Start(FROM_HERE
, commit_interval_
, this,
170 &ImportantFileWriter::DoScheduledWrite
);
174 void ImportantFileWriter::DoScheduledWrite() {
177 if (serializer_
->SerializeData(&data
)) {
180 DLOG(WARNING
) << "failed to serialize data to be saved in "
181 << path_
.value().c_str();
186 void ImportantFileWriter::RegisterOnNextSuccessfulWriteCallback(
187 const base::Closure
& on_next_successful_write
) {
188 DCHECK(on_next_successful_write_
.is_null());
189 on_next_successful_write_
= on_next_successful_write
;
192 bool ImportantFileWriter::PostWriteTask(const std::string
& data
) {
193 // TODO(gab): This code could always use PostTaskAndReplyWithResult and let
194 // ForwardSuccessfulWrite() no-op if |on_next_successful_write_| is null, but
195 // PostTaskAndReply causes memory leaks in tests (crbug.com/371974) and
196 // suppressing all of those is unrealistic hence we avoid most of them by
197 // using PostTask() in the typical scenario below.
198 if (!on_next_successful_write_
.is_null()) {
199 return base::PostTaskAndReplyWithResult(
203 Bind(&ImportantFileWriter::WriteFileAtomically
, path_
, data
)),
204 Bind(&ImportantFileWriter::ForwardSuccessfulWrite
,
205 weak_factory_
.GetWeakPtr()));
207 return task_runner_
->PostTask(
210 Bind(IgnoreResult(&ImportantFileWriter::WriteFileAtomically
),
214 void ImportantFileWriter::ForwardSuccessfulWrite(bool result
) {
215 DCHECK(CalledOnValidThread());
216 if (result
&& !on_next_successful_write_
.is_null()) {
217 on_next_successful_write_
.Run();
218 on_next_successful_write_
.Reset();