Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(282)

Side by Side Diff: base/files/important_file_writer.cc

Issue 1265363002: Cleanup nits in ImportantFileWriter and JsonPrefStore. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: rebase Created 5 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « base/files/important_file_writer.h ('k') | base/files/important_file_writer_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "base/files/important_file_writer.h" 5 #include "base/files/important_file_writer.h"
6 6
7 #include <stdio.h> 7 #include <stdio.h>
8 8
9 #include <string> 9 #include <string>
10 10
(...skipping 29 matching lines...) Expand all
40 FAILED_WRITING, 40 FAILED_WRITING,
41 FAILED_RENAMING, 41 FAILED_RENAMING,
42 FAILED_FLUSHING, 42 FAILED_FLUSHING,
43 TEMP_FILE_FAILURE_MAX 43 TEMP_FILE_FAILURE_MAX
44 }; 44 };
45 45
46 void LogFailure(const FilePath& path, TempFileFailure failure_code, 46 void LogFailure(const FilePath& path, TempFileFailure failure_code,
47 const std::string& message) { 47 const std::string& message) {
48 UMA_HISTOGRAM_ENUMERATION("ImportantFile.TempFileFailures", failure_code, 48 UMA_HISTOGRAM_ENUMERATION("ImportantFile.TempFileFailures", failure_code,
49 TEMP_FILE_FAILURE_MAX); 49 TEMP_FILE_FAILURE_MAX);
50 DPLOG(WARNING) << "temp file failure: " << path.value().c_str() 50 DPLOG(WARNING) << "temp file failure: " << path.value() << " : " << message;
51 << " : " << message;
52 } 51 }
53 52
54 // Helper function to call WriteFileAtomically() with a scoped_ptr<std::string>. 53 // Helper function to call WriteFileAtomically() with a scoped_ptr<std::string>.
55 bool WriteScopedStringToFileAtomically(const FilePath& path, 54 bool WriteScopedStringToFileAtomically(const FilePath& path,
56 scoped_ptr<std::string> data) { 55 scoped_ptr<std::string> data) {
57 return ImportantFileWriter::WriteFileAtomically(path, *data); 56 return ImportantFileWriter::WriteFileAtomically(path, *data);
58 } 57 }
59 58
60 } // namespace 59 } // namespace
61 60
62 // static 61 // static
63 bool ImportantFileWriter::WriteFileAtomically(const FilePath& path, 62 bool ImportantFileWriter::WriteFileAtomically(const FilePath& path,
64 const std::string& data) { 63 const std::string& data) {
65 #if defined(OS_CHROMEOS) 64 #if defined(OS_CHROMEOS)
66 // On Chrome OS, chrome gets killed when it cannot finish shutdown quickly, 65 // 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. 66 // and this function seems to be one of the slowest shutdown steps.
68 // Include some info to the report for investigation. crbug.com/418627 67 // Include some info to the report for investigation. crbug.com/418627
69 // TODO(hashimoto): Remove this. 68 // TODO(hashimoto): Remove this.
70 struct { 69 struct {
71 size_t data_size; 70 size_t data_size;
72 char path[128]; 71 char path[128];
73 } file_info; 72 } file_info;
74 file_info.data_size = data.size(); 73 file_info.data_size = data.size();
75 base::strlcpy(file_info.path, path.value().c_str(), 74 strlcpy(file_info.path, path.value().c_str(), arraysize(file_info.path));
76 arraysize(file_info.path)); 75 debug::Alias(&file_info);
77 base::debug::Alias(&file_info);
78 #endif 76 #endif
77
79 // Write the data to a temp file then rename to avoid data loss if we crash 78 // 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 79 // 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 80 // as target file, so it can be moved in one step, and that the temp file
82 // is securely created. 81 // is securely created.
83 FilePath tmp_file_path; 82 FilePath tmp_file_path;
84 if (!base::CreateTemporaryFileInDir(path.DirName(), &tmp_file_path)) { 83 if (!CreateTemporaryFileInDir(path.DirName(), &tmp_file_path)) {
85 LogFailure(path, FAILED_CREATING, "could not create temporary file"); 84 LogFailure(path, FAILED_CREATING, "could not create temporary file");
86 return false; 85 return false;
87 } 86 }
88 87
89 File tmp_file(tmp_file_path, File::FLAG_OPEN | File::FLAG_WRITE); 88 File tmp_file(tmp_file_path, File::FLAG_OPEN | File::FLAG_WRITE);
90 if (!tmp_file.IsValid()) { 89 if (!tmp_file.IsValid()) {
91 LogFailure(path, FAILED_OPENING, "could not open temporary file"); 90 LogFailure(path, FAILED_OPENING, "could not open temporary file");
92 return false; 91 return false;
93 } 92 }
94 93
95 // If this happens in the wild something really bad is going on. 94 // If this happens in the wild something really bad is going on.
96 CHECK_LE(data.length(), static_cast<size_t>(kint32max)); 95 CHECK_LE(data.length(),
97 int bytes_written = tmp_file.Write(0, data.data(), 96 static_cast<size_t>(std::numeric_limits<int32>::max()));
cmumford 2015/08/05 21:16:56 Oh also - you might want to take a look at base::I
Lei Zhang 2015/08/06 07:13:41 Good suggestion. That wasn't around when this was
98 static_cast<int>(data.length())); 97 const int data_length = static_cast<int>(data.length());
98 int bytes_written = tmp_file.Write(0, data.data(), data_length);
99 bool flush_success = tmp_file.Flush(); 99 bool flush_success = tmp_file.Flush();
100 tmp_file.Close(); 100 tmp_file.Close();
101 101
102 if (bytes_written < static_cast<int>(data.length())) { 102 if (bytes_written < data_length) {
103 LogFailure(path, FAILED_WRITING, "error writing, bytes_written=" + 103 LogFailure(path, FAILED_WRITING, "error writing, bytes_written=" +
104 IntToString(bytes_written)); 104 IntToString(bytes_written));
105 base::DeleteFile(tmp_file_path, false); 105 DeleteFile(tmp_file_path, false);
106 return false; 106 return false;
107 } 107 }
108 108
109 if (!flush_success) { 109 if (!flush_success) {
110 LogFailure(path, FAILED_FLUSHING, "error flushing"); 110 LogFailure(path, FAILED_FLUSHING, "error flushing");
111 base::DeleteFile(tmp_file_path, false); 111 DeleteFile(tmp_file_path, false);
112 return false; 112 return false;
113 } 113 }
114 114
115 if (!base::ReplaceFile(tmp_file_path, path, NULL)) { 115 if (!ReplaceFile(tmp_file_path, path, nullptr)) {
116 LogFailure(path, FAILED_RENAMING, "could not rename temporary file"); 116 LogFailure(path, FAILED_RENAMING, "could not rename temporary file");
117 base::DeleteFile(tmp_file_path, false); 117 DeleteFile(tmp_file_path, false);
118 return false; 118 return false;
119 } 119 }
120 120
121 return true; 121 return true;
122 } 122 }
123 123
124 ImportantFileWriter::ImportantFileWriter( 124 ImportantFileWriter::ImportantFileWriter(
125 const FilePath& path, 125 const FilePath& path,
126 const scoped_refptr<base::SequencedTaskRunner>& task_runner) 126 const scoped_refptr<SequencedTaskRunner>& task_runner)
127 : ImportantFileWriter(
128 path,
129 task_runner,
130 TimeDelta::FromMilliseconds(kDefaultCommitIntervalMs)) {
131 }
132
133 ImportantFileWriter::ImportantFileWriter(
134 const FilePath& path,
135 const scoped_refptr<SequencedTaskRunner>& task_runner,
136 TimeDelta interval)
127 : path_(path), 137 : path_(path),
128 task_runner_(task_runner), 138 task_runner_(task_runner),
129 serializer_(NULL), 139 serializer_(nullptr),
130 commit_interval_(TimeDelta::FromMilliseconds(kDefaultCommitIntervalMs)), 140 commit_interval_(interval),
131 weak_factory_(this) { 141 weak_factory_(this) {
132 DCHECK(CalledOnValidThread()); 142 DCHECK(CalledOnValidThread());
133 DCHECK(task_runner_); 143 DCHECK(task_runner_);
134 } 144 }
135 145
136 ImportantFileWriter::~ImportantFileWriter() { 146 ImportantFileWriter::~ImportantFileWriter() {
137 // We're usually a member variable of some other object, which also tends 147 // We're usually a member variable of some other object, which also tends
138 // to be our serializer. It may not be safe to call back to the parent object 148 // to be our serializer. It may not be safe to call back to the parent object
139 // being destructed. 149 // being destructed.
140 DCHECK(!HasPendingWrite()); 150 DCHECK(!HasPendingWrite());
141 } 151 }
142 152
143 bool ImportantFileWriter::HasPendingWrite() const { 153 bool ImportantFileWriter::HasPendingWrite() const {
144 DCHECK(CalledOnValidThread()); 154 DCHECK(CalledOnValidThread());
145 return timer_.IsRunning(); 155 return timer_.IsRunning();
146 } 156 }
147 157
148 void ImportantFileWriter::WriteNow(scoped_ptr<std::string> data) { 158 void ImportantFileWriter::WriteNow(scoped_ptr<std::string> data) {
149 DCHECK(CalledOnValidThread()); 159 DCHECK(CalledOnValidThread());
150 if (data->length() > static_cast<size_t>(kint32max)) { 160 if (data->length() > static_cast<size_t>(std::numeric_limits<int32>::max())) {
151 NOTREACHED(); 161 NOTREACHED();
152 return; 162 return;
153 } 163 }
154 164
155 if (HasPendingWrite()) 165 if (HasPendingWrite())
156 timer_.Stop(); 166 timer_.Stop();
157 167
158 auto task = Bind(&WriteScopedStringToFileAtomically, path_, Passed(&data)); 168 auto task = Bind(&WriteScopedStringToFileAtomically, path_, Passed(&data));
159 if (!PostWriteTask(task)) { 169 if (!PostWriteTask(task)) {
160 // Posting the task to background message loop is not expected 170 // Posting the task to background message loop is not expected
(...skipping 17 matching lines...) Expand all
178 } 188 }
179 } 189 }
180 190
181 void ImportantFileWriter::DoScheduledWrite() { 191 void ImportantFileWriter::DoScheduledWrite() {
182 DCHECK(serializer_); 192 DCHECK(serializer_);
183 scoped_ptr<std::string> data(new std::string); 193 scoped_ptr<std::string> data(new std::string);
184 if (serializer_->SerializeData(data.get())) { 194 if (serializer_->SerializeData(data.get())) {
185 WriteNow(data.Pass()); 195 WriteNow(data.Pass());
186 } else { 196 } else {
187 DLOG(WARNING) << "failed to serialize data to be saved in " 197 DLOG(WARNING) << "failed to serialize data to be saved in "
188 << path_.value().c_str(); 198 << path_.value();
189 } 199 }
190 serializer_ = NULL; 200 serializer_ = nullptr;
191 } 201 }
192 202
193 void ImportantFileWriter::RegisterOnNextSuccessfulWriteCallback( 203 void ImportantFileWriter::RegisterOnNextSuccessfulWriteCallback(
194 const base::Closure& on_next_successful_write) { 204 const Closure& on_next_successful_write) {
195 DCHECK(on_next_successful_write_.is_null()); 205 DCHECK(on_next_successful_write_.is_null());
196 on_next_successful_write_ = on_next_successful_write; 206 on_next_successful_write_ = on_next_successful_write;
197 } 207 }
198 208
199 bool ImportantFileWriter::PostWriteTask(const Callback<bool()>& task) { 209 bool ImportantFileWriter::PostWriteTask(const Callback<bool()>& task) {
200 // TODO(gab): This code could always use PostTaskAndReplyWithResult and let 210 // TODO(gab): This code could always use PostTaskAndReplyWithResult and let
201 // ForwardSuccessfulWrite() no-op if |on_next_successful_write_| is null, but 211 // ForwardSuccessfulWrite() no-op if |on_next_successful_write_| is null, but
202 // PostTaskAndReply causes memory leaks in tests (crbug.com/371974) and 212 // PostTaskAndReply causes memory leaks in tests (crbug.com/371974) and
203 // suppressing all of those is unrealistic hence we avoid most of them by 213 // suppressing all of those is unrealistic hence we avoid most of them by
204 // using PostTask() in the typical scenario below. 214 // using PostTask() in the typical scenario below.
205 if (!on_next_successful_write_.is_null()) { 215 if (!on_next_successful_write_.is_null()) {
206 return base::PostTaskAndReplyWithResult( 216 return PostTaskAndReplyWithResult(
207 task_runner_.get(), 217 task_runner_.get(),
208 FROM_HERE, 218 FROM_HERE,
209 MakeCriticalClosure(task), 219 MakeCriticalClosure(task),
210 Bind(&ImportantFileWriter::ForwardSuccessfulWrite, 220 Bind(&ImportantFileWriter::ForwardSuccessfulWrite,
211 weak_factory_.GetWeakPtr())); 221 weak_factory_.GetWeakPtr()));
212 } 222 }
213 return task_runner_->PostTask( 223 return task_runner_->PostTask(
214 FROM_HERE, 224 FROM_HERE,
215 MakeCriticalClosure(base::Bind(IgnoreResult(task)))); 225 MakeCriticalClosure(Bind(IgnoreResult(task))));
216 } 226 }
217 227
218 void ImportantFileWriter::ForwardSuccessfulWrite(bool result) { 228 void ImportantFileWriter::ForwardSuccessfulWrite(bool result) {
219 DCHECK(CalledOnValidThread()); 229 DCHECK(CalledOnValidThread());
220 if (result && !on_next_successful_write_.is_null()) { 230 if (result && !on_next_successful_write_.is_null()) {
221 on_next_successful_write_.Run(); 231 on_next_successful_write_.Run();
222 on_next_successful_write_.Reset(); 232 on_next_successful_write_.Reset();
223 } 233 }
224 } 234 }
225 235
226 } // namespace base 236 } // namespace base
OLDNEW
« no previous file with comments | « base/files/important_file_writer.h ('k') | base/files/important_file_writer_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698