file_cache.h revision f2477e01787aa58f445919b809d89e252beef54f
1// Copyright (c) 2012 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#ifndef CHROME_BROWSER_CHROMEOS_DRIVE_FILE_CACHE_H_
6#define CHROME_BROWSER_CHROMEOS_DRIVE_FILE_CACHE_H_
7
8#include <set>
9#include <string>
10#include <vector>
11
12#include "base/callback_forward.h"
13#include "base/files/file_path.h"
14#include "base/memory/scoped_ptr.h"
15#include "base/memory/weak_ptr.h"
16#include "chrome/browser/chromeos/drive/file_errors.h"
17#include "chrome/browser/chromeos/drive/resource_metadata_storage.h"
18
19namespace base {
20class SequencedTaskRunner;
21}  // namespace base
22
23namespace drive {
24
25class FileCacheEntry;
26
27namespace internal {
28
29// Callback for GetFileFromCache.
30typedef base::Callback<void(FileError error,
31                            const base::FilePath& cache_file_path)>
32    GetFileFromCacheCallback;
33
34// Interface class used for getting the free disk space. Tests can inject an
35// implementation that reports fake free disk space.
36class FreeDiskSpaceGetterInterface {
37 public:
38  virtual ~FreeDiskSpaceGetterInterface() {}
39  virtual int64 AmountOfFreeDiskSpace() = 0;
40};
41
42// FileCache is used to maintain cache states of FileSystem.
43//
44// All non-static public member functions, unless mentioned otherwise (see
45// GetCacheFilePath() for example), should be run with |blocking_task_runner|.
46class FileCache {
47 public:
48  // Enum defining type of file operation e.g. copy or move, etc.
49  enum FileOperationType {
50    FILE_OPERATION_MOVE = 0,
51    FILE_OPERATION_COPY,
52  };
53
54  typedef ResourceMetadataStorage::CacheEntryIterator Iterator;
55
56  // |cache_file_directory| stores cached files.
57  //
58  // |blocking_task_runner| is used to post a task to the blocking worker
59  // pool for file operations. Must not be null.
60  //
61  // |free_disk_space_getter| is used to inject a custom free disk space
62  // getter for testing. NULL must be passed for production code.
63  //
64  // Must be called on the UI thread.
65  FileCache(ResourceMetadataStorage* storage,
66            const base::FilePath& cache_file_directory,
67            base::SequencedTaskRunner* blocking_task_runner,
68            FreeDiskSpaceGetterInterface* free_disk_space_getter);
69
70  // Returns true if the given path is under drive cache directory, i.e.
71  // <user_profile_dir>/GCache/v1
72  //
73  // Can be called on any thread.
74  bool IsUnderFileCacheDirectory(const base::FilePath& path) const;
75
76  // Gets the cache entry for file corresponding to |id| and returns true if
77  // entry exists in cache map.
78  bool GetCacheEntry(const std::string& id, FileCacheEntry* entry);
79
80  // Returns an object to iterate over entries.
81  scoped_ptr<Iterator> GetIterator();
82
83  // Frees up disk space to store a file with |num_bytes| size content, while
84  // keeping kMinFreeSpace bytes on the disk, if needed.
85  // Returns true if we successfully manage to have enough space, otherwise
86  // false.
87  bool FreeDiskSpaceIfNeededFor(int64 num_bytes);
88
89  // Checks if file corresponding to |id| exists in cache, and returns
90  // FILE_ERROR_OK with |cache_file_path| storing the path to the file.
91  // |cache_file_path| must not be null.
92  FileError GetFile(const std::string& id, base::FilePath* cache_file_path);
93
94  // Stores |source_path| as a cache of the remote content of the file
95  // with |id| and |md5|.
96  FileError Store(const std::string& id,
97                  const std::string& md5,
98                  const base::FilePath& source_path,
99                  FileOperationType file_operation_type);
100
101  // Runs Pin() on |blocking_task_runner_|, and calls |callback| with the result
102  // asynchronously.
103  // |callback| must not be null.
104  // Must be called on the UI thread.
105  void PinOnUIThread(const std::string& id,
106                     const FileOperationCallback& callback);
107
108  // Pins the specified entry.
109  FileError Pin(const std::string& id);
110
111  // Runs Unpin() on |blocking_task_runner_|, and calls |callback| with the
112  // result asynchronously.
113  // |callback| must not be null.
114  // Must be called on the UI thread.
115  void UnpinOnUIThread(const std::string& id,
116                       const FileOperationCallback& callback);
117
118  // Unpins the specified entry.
119  FileError Unpin(const std::string& id);
120
121  // Runs MarkAsMounted() on |blocking_task_runner_|, and calls |callback| with
122  // the result asynchronously.
123  // |callback| must not be null.
124  // Must be called on the UI thread.
125  void MarkAsMountedOnUIThread(const std::string& id,
126                               const GetFileFromCacheCallback& callback);
127
128  // Sets the state of the cache entry corresponding to |id| as mounted.
129  FileError MarkAsMounted(const std::string& id,
130                          base::FilePath* cache_file_path);
131
132  // Set the state of the cache entry corresponding to file_path as unmounted.
133  // |callback| must not be null.
134  // Must be called on the UI thread.
135  void MarkAsUnmountedOnUIThread(const base::FilePath& file_path,
136                                 const FileOperationCallback& callback);
137
138  // Marks the specified entry dirty.
139  FileError MarkDirty(const std::string& id);
140
141  // Clears dirty state of the specified entry and updates its MD5.
142  FileError ClearDirty(const std::string& id, const std::string& md5);
143
144  // Removes the specified cache entry and delete cache files if available.
145  FileError Remove(const std::string& id);
146
147  // Removes all the files in the cache directory and cache entries in DB.
148  bool ClearAll();
149
150  // Initializes the cache. Returns true on success.
151  bool Initialize();
152
153  // Destroys this cache. This function posts a task to the blocking task
154  // runner to safely delete the object.
155  // Must be called on the UI thread.
156  void Destroy();
157
158  // Moves files in the cache directory which are not manged by FileCache to
159  // |dest_directory|.
160  // |recovered_cache_info| should contain cache info recovered from the trashed
161  // metadata DB. It is used to ignore non-dirty files.
162  bool RecoverFilesFromCacheDirectory(
163      const base::FilePath& dest_directory,
164      const ResourceMetadataStorage::RecoveredCacheInfoMap&
165          recovered_cache_info);
166
167 private:
168  friend class FileCacheTest;
169  friend class FileCacheTestOnUIThread;
170
171  ~FileCache();
172
173  // Returns absolute path of the file if it were cached or to be cached.
174  //
175  // Can be called on any thread.
176  base::FilePath GetCacheFilePath(const std::string& id) const;
177
178  // Checks whether the current thread is on the right sequenced worker pool
179  // with the right sequence ID. If not, DCHECK will fail.
180  void AssertOnSequencedWorkerPool();
181
182  // Destroys the cache on the blocking pool.
183  void DestroyOnBlockingPool();
184
185  // Used to implement Store and StoreLocallyModifiedOnUIThread.
186  // TODO(hidehiko): Merge this method with Store(), after
187  // StoreLocallyModifiedOnUIThread is removed.
188  FileError StoreInternal(const std::string& id,
189                          const std::string& md5,
190                          const base::FilePath& source_path,
191                          FileOperationType file_operation_type);
192
193  // Used to implement MarkAsUnmountedOnUIThread.
194  FileError MarkAsUnmounted(const base::FilePath& file_path);
195
196  // Returns true if we have sufficient space to store the given number of
197  // bytes, while keeping kMinFreeSpace bytes on the disk.
198  bool HasEnoughSpaceFor(int64 num_bytes, const base::FilePath& path);
199
200  // Renames cache files from old "prefix:id.md5" format to the new format.
201  // TODO(hashimoto): Remove this method at some point.
202  bool RenameCacheFilesToNewFormat();
203
204  const base::FilePath cache_file_directory_;
205
206  scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
207
208  ResourceMetadataStorage* storage_;
209
210  FreeDiskSpaceGetterInterface* free_disk_space_getter_;  // Not owned.
211
212  // IDs of files marked mounted.
213  std::set<std::string> mounted_files_;
214
215  // Note: This should remain the last member so it'll be destroyed and
216  // invalidate its weak pointers before any other members are destroyed.
217  base::WeakPtrFactory<FileCache> weak_ptr_factory_;
218  DISALLOW_COPY_AND_ASSIGN(FileCache);
219};
220
221// The minimum free space to keep. Operations that add cache files return
222// FILE_ERROR_NO_LOCAL_SPACE if the available space is smaller than
223// this value.
224//
225// Copied from cryptohome/homedirs.h.
226// TODO(satorux): Share the constant.
227const int64 kMinFreeSpace = 512 * 1LL << 20;
228
229}  // namespace internal
230}  // namespace drive
231
232#endif  // CHROME_BROWSER_CHROMEOS_DRIVE_FILE_CACHE_H_
233