Extract SIGPIPE ignoring code to a common place.
[chromium-blink-merge.git] / base / files / important_file_writer.cc
blob536b0fb161b93cadd3a38a355bf2e071b9c1f59d
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/file_path.h"
14 #include "base/file_util.h"
15 #include "base/logging.h"
16 #include "base/task_runner.h"
17 #include "base/metrics/histogram.h"
18 #include "base/string_number_conversions.h"
19 #include "base/threading/thread.h"
20 #include "base/time.h"
22 namespace base {
24 namespace {
26 const int kDefaultCommitIntervalMs = 10000;
28 enum TempFileFailure {
29 FAILED_CREATING,
30 FAILED_OPENING,
31 FAILED_CLOSING,
32 FAILED_WRITING,
33 FAILED_RENAMING,
34 TEMP_FILE_FAILURE_MAX
37 void LogFailure(const FilePath& path, TempFileFailure failure_code,
38 const std::string& message) {
39 UMA_HISTOGRAM_ENUMERATION("ImportantFile.TempFileFailures", failure_code,
40 TEMP_FILE_FAILURE_MAX);
41 DPLOG(WARNING) << "temp file failure: " << path.value().c_str()
42 << " : " << message;
45 void WriteToDiskTask(const FilePath& path, const std::string& data) {
46 // Write the data to a temp file then rename to avoid data loss if we crash
47 // while writing the file. Ensure that the temp file is on the same volume
48 // as target file, so it can be moved in one step, and that the temp file
49 // is securely created.
50 FilePath tmp_file_path;
51 if (!file_util::CreateTemporaryFileInDir(path.DirName(), &tmp_file_path)) {
52 LogFailure(path, FAILED_CREATING, "could not create temporary file");
53 return;
56 int flags = PLATFORM_FILE_OPEN | PLATFORM_FILE_WRITE;
57 PlatformFile tmp_file =
58 CreatePlatformFile(tmp_file_path, flags, NULL, NULL);
59 if (tmp_file == kInvalidPlatformFileValue) {
60 LogFailure(path, FAILED_OPENING, "could not open temporary file");
61 return;
64 // If this happens in the wild something really bad is going on.
65 CHECK_LE(data.length(), static_cast<size_t>(kint32max));
66 int bytes_written = WritePlatformFile(
67 tmp_file, 0, data.data(), static_cast<int>(data.length()));
68 FlushPlatformFile(tmp_file); // Ignore return value.
70 if (!ClosePlatformFile(tmp_file)) {
71 LogFailure(path, FAILED_CLOSING, "failed to close temporary file");
72 file_util::Delete(tmp_file_path, false);
73 return;
76 if (bytes_written < static_cast<int>(data.length())) {
77 LogFailure(path, FAILED_WRITING, "error writing, bytes_written=" +
78 IntToString(bytes_written));
79 file_util::Delete(tmp_file_path, false);
80 return;
83 if (!file_util::ReplaceFile(tmp_file_path, path)) {
84 LogFailure(path, FAILED_RENAMING, "could not rename temporary file");
85 file_util::Delete(tmp_file_path, false);
86 return;
90 } // namespace
92 ImportantFileWriter::ImportantFileWriter(
93 const FilePath& path, base::SequencedTaskRunner* task_runner)
94 : path_(path),
95 task_runner_(task_runner),
96 serializer_(NULL),
97 commit_interval_(TimeDelta::FromMilliseconds(
98 kDefaultCommitIntervalMs)) {
99 DCHECK(CalledOnValidThread());
100 DCHECK(task_runner_.get());
103 ImportantFileWriter::~ImportantFileWriter() {
104 // We're usually a member variable of some other object, which also tends
105 // to be our serializer. It may not be safe to call back to the parent object
106 // being destructed.
107 DCHECK(!HasPendingWrite());
110 bool ImportantFileWriter::HasPendingWrite() const {
111 DCHECK(CalledOnValidThread());
112 return timer_.IsRunning();
115 void ImportantFileWriter::WriteNow(const std::string& data) {
116 DCHECK(CalledOnValidThread());
117 if (data.length() > static_cast<size_t>(kint32max)) {
118 NOTREACHED();
119 return;
122 if (HasPendingWrite())
123 timer_.Stop();
125 if (!task_runner_->PostTask(FROM_HERE,
126 MakeCriticalClosure(Bind(&WriteToDiskTask, path_, data)))) {
127 // Posting the task to background message loop is not expected
128 // to fail, but if it does, avoid losing data and just hit the disk
129 // on the current thread.
130 NOTREACHED();
132 WriteToDiskTask(path_, data);
136 void ImportantFileWriter::ScheduleWrite(DataSerializer* serializer) {
137 DCHECK(CalledOnValidThread());
139 DCHECK(serializer);
140 serializer_ = serializer;
142 if (!timer_.IsRunning()) {
143 timer_.Start(FROM_HERE, commit_interval_, this,
144 &ImportantFileWriter::DoScheduledWrite);
148 void ImportantFileWriter::DoScheduledWrite() {
149 DCHECK(serializer_);
150 std::string data;
151 if (serializer_->SerializeData(&data)) {
152 WriteNow(data);
153 } else {
154 DLOG(WARNING) << "failed to serialize data to be saved in "
155 << path_.value().c_str();
157 serializer_ = NULL;
160 } // namespace base