blob: 1accf1d817df49448ddc3033ca5f7b23e9630919 [file] [log] [blame]
[email protected]512d03f2012-06-26 01:06:061// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]6faa0e0d2009-04-28 06:50:362// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]43486252012-10-24 16:33:365#ifndef BASE_FILES_IMPORTANT_FILE_WRITER_H_
6#define BASE_FILES_IMPORTANT_FILE_WRITER_H_
[email protected]6faa0e0d2009-04-28 06:50:367
Greg Thompsondfc7d7f42020-05-14 19:30:508#include <memory>
[email protected]6faa0e0d2009-04-28 06:50:369#include <string>
10
[email protected]43486252012-10-24 16:33:3611#include "base/base_export.h"
[email protected]e33c9512014-05-12 02:24:1312#include "base/callback.h"
[email protected]57999812013-02-24 05:40:5213#include "base/files/file_path.h"
avi543540e2015-12-24 05:15:3214#include "base/macros.h"
[email protected]3b63f8f42011-03-28 01:54:1515#include "base/memory/ref_counted.h"
gab7d2fae42017-06-01 14:02:5516#include "base/sequence_checker.h"
bcwhitebe133b52016-04-11 20:03:3817#include "base/strings/string_piece.h"
[email protected]99084f62013-06-28 00:49:0718#include "base/time/time.h"
19#include "base/timer/timer.h"
[email protected]6faa0e0d2009-04-28 06:50:3620
21namespace base {
[email protected]43486252012-10-24 16:33:3622
[email protected]0de615a2012-11-08 04:40:5923class SequencedTaskRunner;
[email protected]6faa0e0d2009-04-28 06:50:3624
tnagelc1d331a2016-08-16 21:39:5425// Helper for atomically writing a file to ensure that it won't be corrupted by
26// *application* crash during write (implemented as create, flush, rename).
[email protected]6faa0e0d2009-04-28 06:50:3627//
tnagelc1d331a2016-08-16 21:39:5428// As an added benefit, ImportantFileWriter makes it less likely that the file
29// is corrupted by *system* crash, though even if the ImportantFileWriter call
30// has already returned at the time of the crash it is not specified which
31// version of the file (old or new) is preserved. And depending on system
32// configuration (hardware and software) a significant likelihood of file
33// corruption may remain, thus using ImportantFileWriter is not a valid
34// substitute for file integrity checks and recovery codepaths for malformed
35// files.
[email protected]6faa0e0d2009-04-28 06:50:3636//
tnagelc1d331a2016-08-16 21:39:5437// Also note that ImportantFileWriter can be *really* slow (cf. File::Flush()
38// for details) and thus please don't block shutdown on ImportantFileWriter.
gab7d2fae42017-06-01 14:02:5539class BASE_EXPORT ImportantFileWriter {
[email protected]6faa0e0d2009-04-28 06:50:3640 public:
[email protected]6c1164042009-05-08 14:41:0841 // Used by ScheduleSave to lazily provide the data to be saved. Allows us
42 // to also batch data serializations.
[email protected]f59f33e2012-11-01 12:05:2743 class BASE_EXPORT DataSerializer {
[email protected]6c1164042009-05-08 14:41:0844 public:
[email protected]6c1164042009-05-08 14:41:0845 // Should put serialized string in |data| and return true on successful
46 // serialization. Will be called on the same thread on which
47 // ImportantFileWriter has been created.
48 virtual bool SerializeData(std::string* data) = 0;
[email protected]512d03f2012-06-26 01:06:0649
50 protected:
Chris Watkins091d6292017-12-13 04:25:5851 virtual ~DataSerializer() = default;
[email protected]6c1164042009-05-08 14:41:0852 };
53
tnagelc1d331a2016-08-16 21:39:5454 // Save |data| to |path| in an atomic manner. Blocks and writes data on the
55 // current thread. Does not guarantee file integrity across system crash (see
56 // the class comment above).
xaerox4ae8d172017-06-20 10:20:1257 static bool WriteFileAtomically(const FilePath& path,
58 StringPiece data,
59 StringPiece histogram_suffix = StringPiece());
[email protected]95b42e22012-11-29 14:00:1260
[email protected]6faa0e0d2009-04-28 06:50:3661 // Initialize the writer.
[email protected]6fad2632009-11-02 05:59:3762 // |path| is the name of file to write.
[email protected]0de615a2012-11-08 04:40:5963 // |task_runner| is the SequencedTaskRunner instance where on which we will
64 // execute file I/O operations.
[email protected]6faa0e0d2009-04-28 06:50:3665 // All non-const methods, ctor and dtor must be called on the same thread.
thestig1433edb2015-08-06 21:45:2766 ImportantFileWriter(const FilePath& path,
xaerox4ae8d172017-06-20 10:20:1267 scoped_refptr<SequencedTaskRunner> task_runner,
68 const char* histogram_suffix = nullptr);
thestig1433edb2015-08-06 21:45:2769
70 // Same as above, but with a custom commit interval.
71 ImportantFileWriter(const FilePath& path,
vmpstr82b0c16d2016-03-18 19:17:2872 scoped_refptr<SequencedTaskRunner> task_runner,
xaerox4ae8d172017-06-20 10:20:1273 TimeDelta interval,
74 const char* histogram_suffix = nullptr);
[email protected]6faa0e0d2009-04-28 06:50:3675
[email protected]6c1164042009-05-08 14:41:0876 // You have to ensure that there are no pending writes at the moment
77 // of destruction.
[email protected]6faa0e0d2009-04-28 06:50:3678 ~ImportantFileWriter();
79
[email protected]a83d42292010-08-17 22:51:1080 const FilePath& path() const { return path_; }
[email protected]6faa0e0d2009-04-28 06:50:3681
[email protected]6c1164042009-05-08 14:41:0882 // Returns true if there is a scheduled write pending which has not yet
83 // been started.
84 bool HasPendingWrite() const;
85
[email protected]6faa0e0d2009-04-28 06:50:3686 // Save |data| to target filename. Does not block. If there is a pending write
thestig1433edb2015-08-06 21:45:2787 // scheduled by ScheduleWrite(), it is cancelled.
dcheng093de9b2016-04-04 21:25:5188 void WriteNow(std::unique_ptr<std::string> data);
[email protected]6faa0e0d2009-04-28 06:50:3689
[email protected]6c1164042009-05-08 14:41:0890 // Schedule a save to target filename. Data will be serialized and saved
91 // to disk after the commit interval. If another ScheduleWrite is issued
92 // before that, only one serialization and write to disk will happen, and
93 // the most recent |serializer| will be used. This operation does not block.
94 // |serializer| should remain valid through the lifetime of
95 // ImportantFileWriter.
96 void ScheduleWrite(DataSerializer* serializer);
97
98 // Serialize data pending to be saved and execute write on backend thread.
99 void DoScheduledWrite();
[email protected]6faa0e0d2009-04-28 06:50:36100
probergec503d692016-09-28 19:51:05101 // Registers |before_next_write_callback| and |after_next_write_callback| to
102 // be synchronously invoked from WriteFileAtomically() before its next write
103 // and after its next write, respectively. The boolean passed to
104 // |after_next_write_callback| indicates whether the write was successful.
105 // Both callbacks must be thread safe as they will be called on |task_runner_|
106 // and may be called during Chrome shutdown.
probergefc46ac12016-09-21 18:03:00107 // If called more than once before a write is scheduled on |task_runner|, the
probergec503d692016-09-28 19:51:05108 // latest callbacks clobber the others.
109 void RegisterOnNextWriteCallbacks(
Christian Dullweberee89d672018-11-29 15:12:28110 OnceClosure before_next_write_callback,
111 OnceCallback<void(bool success)> after_next_write_callback);
[email protected]e33c9512014-05-12 02:24:13112
[email protected]43486252012-10-24 16:33:36113 TimeDelta commit_interval() const {
[email protected]6faa0e0d2009-04-28 06:50:36114 return commit_interval_;
115 }
116
Sam McNally365428e2017-05-22 05:25:22117 // Overrides the timer to use for scheduling writes with |timer_override|.
tzikd93bb0862018-07-19 11:54:14118 void SetTimerForTesting(OneShotTimer* timer_override);
Sam McNally365428e2017-05-22 05:25:22119
[email protected]6faa0e0d2009-04-28 06:50:36120 private:
tzikd93bb0862018-07-19 11:54:14121 const OneShotTimer& timer() const {
122 return timer_override_ ? *timer_override_ : timer_;
Sam McNally365428e2017-05-22 05:25:22123 }
tzikd93bb0862018-07-19 11:54:14124 OneShotTimer& timer() { return timer_override_ ? *timer_override_ : timer_; }
Sam McNally365428e2017-05-22 05:25:22125
Greg Thompsondfc7d7f42020-05-14 19:30:50126 // Helper function to call WriteFileAtomically() with a
127 // std::unique_ptr<std::string>.
128 static void WriteScopedStringToFileAtomically(
129 const FilePath& path,
130 std::unique_ptr<std::string> data,
131 OnceClosure before_write_callback,
132 OnceCallback<void(bool success)> after_write_callback,
133 const std::string& histogram_suffix);
134
135 // Writes |data| to |path|, recording histograms with an optional
136 // |histogram_suffix|. |from_instance| indicates whether the call originates
137 // from an instance of ImportantFileWriter or a direct call to
138 // WriteFileAtomically. When false, the directory containing |path| is added
139 // to the set cleaned by the ImportantFileWriterCleaner (Windows only).
140 static bool WriteFileAtomicallyImpl(const FilePath& path,
141 StringPiece data,
142 StringPiece histogram_suffix,
143 bool from_instance);
144
Sam McNally8f50faa2017-05-19 05:08:00145 void ClearPendingWrite();
146
probergefc46ac12016-09-21 18:03:00147 // Invoked synchronously on the next write event.
Christian Dullweberee89d672018-11-29 15:12:28148 OnceClosure before_next_write_callback_;
149 OnceCallback<void(bool success)> after_next_write_callback_;
[email protected]e33c9512014-05-12 02:24:13150
[email protected]6faa0e0d2009-04-28 06:50:36151 // Path being written to.
152 const FilePath path_;
153
[email protected]0de615a2012-11-08 04:40:59154 // TaskRunner for the thread on which file I/O can be done.
thestig1433edb2015-08-06 21:45:27155 const scoped_refptr<SequencedTaskRunner> task_runner_;
[email protected]6658ca82010-05-20 18:20:29156
[email protected]6faa0e0d2009-04-28 06:50:36157 // Timer used to schedule commit after ScheduleWrite.
danakj8c3eb802015-09-24 07:53:00158 OneShotTimer timer_;
[email protected]6faa0e0d2009-04-28 06:50:36159
Sam McNally365428e2017-05-22 05:25:22160 // An override for |timer_| used for testing.
tzikd93bb0862018-07-19 11:54:14161 OneShotTimer* timer_override_ = nullptr;
Sam McNally365428e2017-05-22 05:25:22162
[email protected]6c1164042009-05-08 14:41:08163 // Serializer which will provide the data to be saved.
164 DataSerializer* serializer_;
[email protected]6faa0e0d2009-04-28 06:50:36165
166 // Time delta after which scheduled data will be written to disk.
thestig1433edb2015-08-06 21:45:27167 const TimeDelta commit_interval_;
[email protected]6faa0e0d2009-04-28 06:50:36168
xaerox4ae8d172017-06-20 10:20:12169 // Custom histogram suffix.
170 const std::string histogram_suffix_;
171
gab7d2fae42017-06-01 14:02:55172 SEQUENCE_CHECKER(sequence_checker_);
173
Jeremy Roman577d88492019-07-05 14:30:23174 WeakPtrFactory<ImportantFileWriter> weak_factory_{this};
[email protected]e33c9512014-05-12 02:24:13175
[email protected]6faa0e0d2009-04-28 06:50:36176 DISALLOW_COPY_AND_ASSIGN(ImportantFileWriter);
177};
178
[email protected]43486252012-10-24 16:33:36179} // namespace base
180
181#endif // BASE_FILES_IMPORTANT_FILE_WRITER_H_