'Open as window' removed when --enable-new-bookmark-apps is disabled.
[chromium-blink-merge.git] / base / files / important_file_writer.cc
blobd2562364dfe9cc4ed265b2c72a455a125661c606
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/files/file.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.h"
16 #include "base/logging.h"
17 #include "base/metrics/histogram.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/task_runner.h"
20 #include "base/task_runner_util.h"
21 #include "base/threading/thread.h"
22 #include "base/time/time.h"
24 namespace base {
26 namespace {
28 const int kDefaultCommitIntervalMs = 10000;
30 // This enum is used to define the buckets for an enumerated UMA histogram.
31 // Hence,
32 // (a) existing enumerated constants should never be deleted or reordered, and
33 // (b) new constants should only be appended at the end of the enumeration.
34 enum TempFileFailure {
35 FAILED_CREATING,
36 FAILED_OPENING,
37 FAILED_CLOSING, // Unused.
38 FAILED_WRITING,
39 FAILED_RENAMING,
40 FAILED_FLUSHING,
41 TEMP_FILE_FAILURE_MAX
44 void LogFailure(const FilePath& path, TempFileFailure failure_code,
45 const std::string& message) {
46 UMA_HISTOGRAM_ENUMERATION("ImportantFile.TempFileFailures", failure_code,
47 TEMP_FILE_FAILURE_MAX);
48 DPLOG(WARNING) << "temp file failure: " << path.value().c_str()
49 << " : " << message;
52 } // namespace
54 // static
55 bool ImportantFileWriter::WriteFileAtomically(const FilePath& path,
56 const std::string& data) {
57 // Write the data to a temp file then rename to avoid data loss if we crash
58 // while writing the file. Ensure that the temp file is on the same volume
59 // as target file, so it can be moved in one step, and that the temp file
60 // is securely created.
61 FilePath tmp_file_path;
62 if (!base::CreateTemporaryFileInDir(path.DirName(), &tmp_file_path)) {
63 LogFailure(path, FAILED_CREATING, "could not create temporary file");
64 return false;
67 File tmp_file(tmp_file_path, File::FLAG_OPEN | File::FLAG_WRITE);
68 if (!tmp_file.IsValid()) {
69 LogFailure(path, FAILED_OPENING, "could not open temporary file");
70 return false;
73 // If this happens in the wild something really bad is going on.
74 CHECK_LE(data.length(), static_cast<size_t>(kint32max));
75 int bytes_written = tmp_file.Write(0, data.data(),
76 static_cast<int>(data.length()));
77 bool flush_success = tmp_file.Flush();
78 tmp_file.Close();
80 if (bytes_written < static_cast<int>(data.length())) {
81 LogFailure(path, FAILED_WRITING, "error writing, bytes_written=" +
82 IntToString(bytes_written));
83 base::DeleteFile(tmp_file_path, false);
84 return false;
87 if (!flush_success) {
88 LogFailure(path, FAILED_FLUSHING, "error flushing");
89 base::DeleteFile(tmp_file_path, false);
90 return false;
93 if (!base::ReplaceFile(tmp_file_path, path, NULL)) {
94 LogFailure(path, FAILED_RENAMING, "could not rename temporary file");
95 base::DeleteFile(tmp_file_path, false);
96 return false;
99 return true;
102 ImportantFileWriter::ImportantFileWriter(
103 const FilePath& path,
104 const scoped_refptr<base::SequencedTaskRunner>& task_runner)
105 : path_(path),
106 task_runner_(task_runner),
107 serializer_(NULL),
108 commit_interval_(TimeDelta::FromMilliseconds(kDefaultCommitIntervalMs)),
109 weak_factory_(this) {
110 DCHECK(CalledOnValidThread());
111 DCHECK(task_runner_.get());
114 ImportantFileWriter::~ImportantFileWriter() {
115 // We're usually a member variable of some other object, which also tends
116 // to be our serializer. It may not be safe to call back to the parent object
117 // being destructed.
118 DCHECK(!HasPendingWrite());
121 bool ImportantFileWriter::HasPendingWrite() const {
122 DCHECK(CalledOnValidThread());
123 return timer_.IsRunning();
126 void ImportantFileWriter::WriteNow(const std::string& data) {
127 DCHECK(CalledOnValidThread());
128 if (data.length() > static_cast<size_t>(kint32max)) {
129 NOTREACHED();
130 return;
133 if (HasPendingWrite())
134 timer_.Stop();
136 if (!PostWriteTask(data)) {
137 // Posting the task to background message loop is not expected
138 // to fail, but if it does, avoid losing data and just hit the disk
139 // on the current thread.
140 NOTREACHED();
142 WriteFileAtomically(path_, data);
146 void ImportantFileWriter::ScheduleWrite(DataSerializer* serializer) {
147 DCHECK(CalledOnValidThread());
149 DCHECK(serializer);
150 serializer_ = serializer;
152 if (!timer_.IsRunning()) {
153 timer_.Start(FROM_HERE, commit_interval_, this,
154 &ImportantFileWriter::DoScheduledWrite);
158 void ImportantFileWriter::DoScheduledWrite() {
159 DCHECK(serializer_);
160 std::string data;
161 if (serializer_->SerializeData(&data)) {
162 WriteNow(data);
163 } else {
164 DLOG(WARNING) << "failed to serialize data to be saved in "
165 << path_.value().c_str();
167 serializer_ = NULL;
170 void ImportantFileWriter::RegisterOnNextSuccessfulWriteCallback(
171 const base::Closure& on_next_successful_write) {
172 DCHECK(on_next_successful_write_.is_null());
173 on_next_successful_write_ = on_next_successful_write;
176 bool ImportantFileWriter::PostWriteTask(const std::string& data) {
177 // TODO(gab): This code could always use PostTaskAndReplyWithResult and let
178 // ForwardSuccessfulWrite() no-op if |on_next_successful_write_| is null, but
179 // PostTaskAndReply causes memory leaks in tests (crbug.com/371974) and
180 // suppressing all of those is unrealistic hence we avoid most of them by
181 // using PostTask() in the typical scenario below.
182 if (!on_next_successful_write_.is_null()) {
183 return base::PostTaskAndReplyWithResult(
184 task_runner_.get(),
185 FROM_HERE,
186 MakeCriticalClosure(
187 Bind(&ImportantFileWriter::WriteFileAtomically, path_, data)),
188 Bind(&ImportantFileWriter::ForwardSuccessfulWrite,
189 weak_factory_.GetWeakPtr()));
191 return task_runner_->PostTask(
192 FROM_HERE,
193 MakeCriticalClosure(
194 Bind(IgnoreResult(&ImportantFileWriter::WriteFileAtomically),
195 path_, data)));
198 void ImportantFileWriter::ForwardSuccessfulWrite(bool result) {
199 DCHECK(CalledOnValidThread());
200 if (result && !on_next_successful_write_.is_null()) {
201 on_next_successful_write_.Run();
202 on_next_successful_write_.Reset();
206 } // namespace base