- add sources.
[platform/framework/web/crosswalk.git] / src / base / files / important_file_writer.cc
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.
4
5 #if defined _MSC_VER && _MSC_VER == 1800
6 // TODO(scottmg): Internal errors on VS2013 RC in LTCG. This should be removed
7 // after RTM. http://crbug.com/288948
8 #pragma optimize("", off)
9 #endif
10
11 #include "base/files/important_file_writer.h"
12
13 #include <stdio.h>
14
15 #include <string>
16
17 #include "base/bind.h"
18 #include "base/critical_closure.h"
19 #include "base/file_util.h"
20 #include "base/files/file_path.h"
21 #include "base/logging.h"
22 #include "base/metrics/histogram.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/task_runner.h"
25 #include "base/threading/thread.h"
26 #include "base/time/time.h"
27
28 namespace base {
29
30 namespace {
31
32 const int kDefaultCommitIntervalMs = 10000;
33
34 enum TempFileFailure {
35   FAILED_CREATING,
36   FAILED_OPENING,
37   FAILED_CLOSING,
38   FAILED_WRITING,
39   FAILED_RENAMING,
40   TEMP_FILE_FAILURE_MAX
41 };
42
43 void LogFailure(const FilePath& path, TempFileFailure failure_code,
44                 const std::string& message) {
45   UMA_HISTOGRAM_ENUMERATION("ImportantFile.TempFileFailures", failure_code,
46                             TEMP_FILE_FAILURE_MAX);
47   DPLOG(WARNING) << "temp file failure: " << path.value().c_str()
48                  << " : " << message;
49 }
50
51 }  // namespace
52
53 // static
54 bool ImportantFileWriter::WriteFileAtomically(const FilePath& path,
55                                               const std::string& data) {
56   // Write the data to a temp file then rename to avoid data loss if we crash
57   // while writing the file. Ensure that the temp file is on the same volume
58   // as target file, so it can be moved in one step, and that the temp file
59   // is securely created.
60   FilePath tmp_file_path;
61   if (!file_util::CreateTemporaryFileInDir(path.DirName(), &tmp_file_path)) {
62     LogFailure(path, FAILED_CREATING, "could not create temporary file");
63     return false;
64   }
65
66   int flags = PLATFORM_FILE_OPEN | PLATFORM_FILE_WRITE;
67   PlatformFile tmp_file =
68       CreatePlatformFile(tmp_file_path, flags, NULL, NULL);
69   if (tmp_file == kInvalidPlatformFileValue) {
70     LogFailure(path, FAILED_OPENING, "could not open temporary file");
71     return false;
72   }
73
74   // If this happens in the wild something really bad is going on.
75   CHECK_LE(data.length(), static_cast<size_t>(kint32max));
76   int bytes_written = WritePlatformFile(
77       tmp_file, 0, data.data(), static_cast<int>(data.length()));
78   FlushPlatformFile(tmp_file);  // Ignore return value.
79
80   if (!ClosePlatformFile(tmp_file)) {
81     LogFailure(path, FAILED_CLOSING, "failed to close temporary file");
82     base::DeleteFile(tmp_file_path, false);
83     return false;
84   }
85
86   if (bytes_written < static_cast<int>(data.length())) {
87     LogFailure(path, FAILED_WRITING, "error writing, bytes_written=" +
88                IntToString(bytes_written));
89     base::DeleteFile(tmp_file_path, false);
90     return false;
91   }
92
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;
97   }
98
99   return true;
100 }
101
102 ImportantFileWriter::ImportantFileWriter(
103     const FilePath& path, base::SequencedTaskRunner* task_runner)
104         : path_(path),
105           task_runner_(task_runner),
106           serializer_(NULL),
107           commit_interval_(TimeDelta::FromMilliseconds(
108               kDefaultCommitIntervalMs)) {
109   DCHECK(CalledOnValidThread());
110   DCHECK(task_runner_.get());
111 }
112
113 ImportantFileWriter::~ImportantFileWriter() {
114   // We're usually a member variable of some other object, which also tends
115   // to be our serializer. It may not be safe to call back to the parent object
116   // being destructed.
117   DCHECK(!HasPendingWrite());
118 }
119
120 bool ImportantFileWriter::HasPendingWrite() const {
121   DCHECK(CalledOnValidThread());
122   return timer_.IsRunning();
123 }
124
125 void ImportantFileWriter::WriteNow(const std::string& data) {
126   DCHECK(CalledOnValidThread());
127   if (data.length() > static_cast<size_t>(kint32max)) {
128     NOTREACHED();
129     return;
130   }
131
132   if (HasPendingWrite())
133     timer_.Stop();
134
135   if (!task_runner_->PostTask(
136           FROM_HERE,
137           MakeCriticalClosure(
138               Bind(IgnoreResult(&ImportantFileWriter::WriteFileAtomically),
139                    path_, data)))) {
140     // Posting the task to background message loop is not expected
141     // to fail, but if it does, avoid losing data and just hit the disk
142     // on the current thread.
143     NOTREACHED();
144
145     WriteFileAtomically(path_, data);
146   }
147 }
148
149 void ImportantFileWriter::ScheduleWrite(DataSerializer* serializer) {
150   DCHECK(CalledOnValidThread());
151
152   DCHECK(serializer);
153   serializer_ = serializer;
154
155   if (!timer_.IsRunning()) {
156     timer_.Start(FROM_HERE, commit_interval_, this,
157                  &ImportantFileWriter::DoScheduledWrite);
158   }
159 }
160
161 void ImportantFileWriter::DoScheduledWrite() {
162   DCHECK(serializer_);
163   std::string data;
164   if (serializer_->SerializeData(&data)) {
165     WriteNow(data);
166   } else {
167     DLOG(WARNING) << "failed to serialize data to be saved in "
168                   << path_.value().c_str();
169   }
170   serializer_ = NULL;
171 }
172
173 }  // namespace base