1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/drive/drive_cache.h"
#include <vector>
#include "base/file_util.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "base/task_runner_util.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/drive_cache_metadata.h"
#include "chrome/browser/chromeos/drive/drive_cache_observer.h"
#include "chrome/browser/chromeos/drive/drive_file_system_util.h"
#include "chrome/browser/google_apis/task_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "content/public/browser/browser_thread.h"
using content::BrowserThread;
namespace drive {
namespace {
const FilePath::CharType kDriveCacheVersionDir[] = FILE_PATH_LITERAL("v1");
const FilePath::CharType kDriveCacheMetaDir[] = FILE_PATH_LITERAL("meta");
const FilePath::CharType kDriveCachePinnedDir[] = FILE_PATH_LITERAL("pinned");
const FilePath::CharType kDriveCacheOutgoingDir[] =
FILE_PATH_LITERAL("outgoing");
const FilePath::CharType kDriveCachePersistentDir[] =
FILE_PATH_LITERAL("persistent");
const FilePath::CharType kDriveCacheTmpDir[] = FILE_PATH_LITERAL("tmp");
const FilePath::CharType kDriveCacheTmpDownloadsDir[] =
FILE_PATH_LITERAL("tmp/downloads");
const FilePath::CharType kDriveCacheTmpDocumentsDir[] =
FILE_PATH_LITERAL("tmp/documents");
// Create cache directory paths and set permissions.
bool InitCachePaths(const std::vector<FilePath>& cache_paths) {
if (cache_paths.size() < DriveCache::NUM_CACHE_TYPES) {
NOTREACHED();
LOG(ERROR) << "Size of cache_paths is invalid.";
return false;
}
if (!DriveCache::CreateCacheDirectories(cache_paths))
return false;
// Change permissions of cache persistent directory to u+rwx,og+x (711) in
// order to allow archive files in that directory to be mounted by cros-disks.
file_util::SetPosixFilePermissions(
cache_paths[DriveCache::CACHE_TYPE_PERSISTENT],
file_util::FILE_PERMISSION_USER_MASK |
file_util::FILE_PERMISSION_EXECUTE_BY_GROUP |
file_util::FILE_PERMISSION_EXECUTE_BY_OTHERS);
return true;
}
// Remove all files under the given directory, non-recursively.
// Do not remove recursively as we don't want to touch <gcache>/tmp/downloads,
// which is used for user initiated downloads like "Save As"
void RemoveAllFiles(const FilePath& directory) {
using file_util::FileEnumerator;
FileEnumerator enumerator(directory, false /* recursive */,
FileEnumerator::FILES);
for (FilePath file_path = enumerator.Next(); !file_path.empty();
file_path = enumerator.Next()) {
DVLOG(1) << "Removing " << file_path.value();
if (!file_util::Delete(file_path, false /* recursive */))
LOG(WARNING) << "Failed to delete " << file_path.value();
}
}
// Deletes the symlink.
void DeleteSymlink(const FilePath& symlink_path) {
// We try to save one file operation by not checking if link exists before
// deleting it, so unlink may return error if link doesn't exist, but it
// doesn't really matter to us.
file_util::Delete(symlink_path, false);
}
// Creates a symlink.
bool CreateSymlink(const FilePath& cache_file_path,
const FilePath& symlink_path) {
// Remove symlink because creating a link will not overwrite an existing one.
DeleteSymlink(symlink_path);
// Create new symlink to |cache_file_path|.
if (!file_util::CreateSymbolicLink(cache_file_path, symlink_path)) {
LOG(ERROR) << "Failed to create a symlink from " << symlink_path.value()
<< " to " << cache_file_path.value();
return false;
}
return true;
}
// Moves the file.
bool MoveFile(const FilePath& source_path, const FilePath& dest_path) {
if (!file_util::Move(source_path, dest_path)) {
LOG(ERROR) << "Failed to move " << source_path.value()
<< " to " << dest_path.value();
return false;
}
DVLOG(1) << "Moved " << source_path.value() << " to " << dest_path.value();
return true;
}
// Copies the file.
bool CopyFile(const FilePath& source_path, const FilePath& dest_path) {
if (!file_util::CopyFile(source_path, dest_path)) {
LOG(ERROR) << "Failed to copy " << source_path.value()
<< " to " << dest_path.value();
return false;
}
DVLOG(1) << "Copied " << source_path.value() << " to " << dest_path.value();
return true;
}
// Deletes all files that match |path_to_delete_pattern| except for
// |path_to_keep| on blocking pool.
// If |path_to_keep| is empty, all files in |path_to_delete_pattern| are
// deleted.
void DeleteFilesSelectively(const FilePath& path_to_delete_pattern,
const FilePath& path_to_keep) {
// Enumerate all files in directory of |path_to_delete_pattern| that match
// base name of |path_to_delete_pattern|.
// If a file is not |path_to_keep|, delete it.
bool success = true;
file_util::FileEnumerator enumerator(path_to_delete_pattern.DirName(),
false, // not recursive
file_util::FileEnumerator::FILES |
file_util::FileEnumerator::SHOW_SYM_LINKS,
path_to_delete_pattern.BaseName().value());
for (FilePath current = enumerator.Next(); !current.empty();
current = enumerator.Next()) {
// If |path_to_keep| is not empty and same as current, don't delete it.
if (!path_to_keep.empty() && current == path_to_keep)
continue;
success = file_util::Delete(current, false);
if (!success)
DVLOG(1) << "Error deleting " << current.value();
else
DVLOG(1) << "Deleted " << current.value();
}
}
// Runs callback with pointers dereferenced.
// Used to implement GetFile, MarkAsMounted.
void RunGetFileFromCacheCallback(
const GetFileFromCacheCallback& callback,
scoped_ptr<std::pair<DriveFileError, FilePath> > result) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
DCHECK(result.get());
callback.Run(result->first, result->second);
}
// Runs callback with pointers dereferenced.
// Used to implement GetCacheEntry().
void RunGetCacheEntryCallback(const GetCacheEntryCallback& callback,
DriveCacheEntry* cache_entry,
bool success) {
DCHECK(cache_entry);
DCHECK(!callback.is_null());
callback.Run(success, *cache_entry);
}
} // namespace
DriveCache::DriveCache(const FilePath& cache_root_path,
base::SequencedTaskRunner* blocking_task_runner,
FreeDiskSpaceGetterInterface* free_disk_space_getter)
: cache_root_path_(cache_root_path),
cache_paths_(GetCachePaths(cache_root_path_)),
blocking_task_runner_(blocking_task_runner),
free_disk_space_getter_(free_disk_space_getter),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
DCHECK(blocking_task_runner_);
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
DriveCache::~DriveCache() {
// Must be on the sequenced worker pool, as |metadata_| must be deleted on
// the sequenced worker pool.
AssertOnSequencedWorkerPool();
}
FilePath DriveCache::GetCacheDirectoryPath(
CacheSubDirectoryType sub_dir_type) const {
DCHECK_LE(0, sub_dir_type);
DCHECK_GT(NUM_CACHE_TYPES, sub_dir_type);
return cache_paths_[sub_dir_type];
}
FilePath DriveCache::GetCacheFilePath(const std::string& resource_id,
const std::string& md5,
CacheSubDirectoryType sub_dir_type,
CachedFileOrigin file_origin) const {
DCHECK(sub_dir_type != CACHE_TYPE_META);
// Runs on any thread.
// Filename is formatted as resource_id.md5, i.e. resource_id is the base
// name and md5 is the extension.
std::string base_name = util::EscapeCacheFileName(resource_id);
if (file_origin == CACHED_FILE_LOCALLY_MODIFIED) {
DCHECK(sub_dir_type == CACHE_TYPE_PERSISTENT);
base_name += FilePath::kExtensionSeparator;
base_name += util::kLocallyModifiedFileExtension;
} else if (!md5.empty()) {
base_name += FilePath::kExtensionSeparator;
base_name += util::EscapeCacheFileName(md5);
}
// For mounted archives the filename is formatted as resource_id.md5.mounted,
// i.e. resource_id.md5 is the base name and ".mounted" is the extension
if (file_origin == CACHED_FILE_MOUNTED) {
DCHECK(sub_dir_type == CACHE_TYPE_PERSISTENT);
base_name += FilePath::kExtensionSeparator;
base_name += util::kMountedArchiveFileExtension;
}
return GetCacheDirectoryPath(sub_dir_type).Append(base_name);
}
void DriveCache::AssertOnSequencedWorkerPool() {
DCHECK(!blocking_task_runner_ ||
blocking_task_runner_->RunsTasksOnCurrentThread());
}
bool DriveCache::IsUnderDriveCacheDirectory(const FilePath& path) const {
return cache_root_path_ == path || cache_root_path_.IsParent(path);
}
void DriveCache::AddObserver(DriveCacheObserver* observer) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
observers_.AddObserver(observer);
}
void DriveCache::RemoveObserver(DriveCacheObserver* observer) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
observers_.RemoveObserver(observer);
}
void DriveCache::GetCacheEntry(const std::string& resource_id,
const std::string& md5,
const GetCacheEntryCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
DriveCacheEntry* cache_entry = new DriveCacheEntry;
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::GetCacheEntryOnBlockingPool,
base::Unretained(this), resource_id, md5, cache_entry),
base::Bind(&RunGetCacheEntryCallback,
callback, base::Owned(cache_entry)));
}
void DriveCache::Iterate(const CacheIterateCallback& iteration_callback,
const base::Closure& completion_callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!iteration_callback.is_null());
DCHECK(!completion_callback.is_null());
blocking_task_runner_->PostTaskAndReply(
FROM_HERE,
base::Bind(&DriveCache::IterateOnBlockingPool,
base::Unretained(this),
google_apis::CreateRelayCallback(iteration_callback)),
completion_callback);
}
void DriveCache::FreeDiskSpaceIfNeededFor(
int64 num_bytes,
const InitializeCacheCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::FreeDiskSpaceOnBlockingPoolIfNeededFor,
base::Unretained(this),
num_bytes),
callback);
}
void DriveCache::GetFile(const std::string& resource_id,
const std::string& md5,
const GetFileFromCacheCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::GetFileOnBlockingPool,
base::Unretained(this), resource_id, md5),
base::Bind(&RunGetFileFromCacheCallback, callback));
}
void DriveCache::Store(const std::string& resource_id,
const std::string& md5,
const FilePath& source_path,
FileOperationType file_operation_type,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::StoreOnBlockingPool,
base::Unretained(this),
resource_id, md5, source_path, file_operation_type),
callback);
}
void DriveCache::Pin(const std::string& resource_id,
const std::string& md5,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::PinOnBlockingPool,
base::Unretained(this), resource_id, md5),
base::Bind(&DriveCache::OnPinned,
weak_ptr_factory_.GetWeakPtr(), resource_id, md5, callback));
}
void DriveCache::Unpin(const std::string& resource_id,
const std::string& md5,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::UnpinOnBlockingPool,
base::Unretained(this), resource_id, md5),
base::Bind(&DriveCache::OnUnpinned,
weak_ptr_factory_.GetWeakPtr(), resource_id, md5, callback));
}
void DriveCache::MarkAsMounted(const std::string& resource_id,
const std::string& md5,
const GetFileFromCacheCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::MarkAsMountedOnBlockingPool,
base::Unretained(this), resource_id, md5),
base::Bind(RunGetFileFromCacheCallback, callback));
}
void DriveCache::MarkAsUnmounted(const FilePath& file_path,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::MarkAsUnmountedOnBlockingPool,
base::Unretained(this), file_path),
callback);
}
void DriveCache::MarkDirty(const std::string& resource_id,
const std::string& md5,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::MarkDirtyOnBlockingPool,
base::Unretained(this), resource_id, md5),
callback);
}
void DriveCache::CommitDirty(const std::string& resource_id,
const std::string& md5,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::CommitDirtyOnBlockingPool,
base::Unretained(this), resource_id, md5),
base::Bind(&DriveCache::OnCommitDirty,
weak_ptr_factory_.GetWeakPtr(), resource_id, callback));
}
void DriveCache::ClearDirty(const std::string& resource_id,
const std::string& md5,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::ClearDirtyOnBlockingPool,
base::Unretained(this), resource_id, md5),
callback);
}
void DriveCache::Remove(const std::string& resource_id,
const FileOperationCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::RemoveOnBlockingPool,
base::Unretained(this), resource_id),
callback);
}
void DriveCache::ClearAll(const InitializeCacheCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::ClearAllOnBlockingPool, base::Unretained(this)),
callback);
}
void DriveCache::RequestInitialize(const InitializeCacheCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
base::PostTaskAndReplyWithResult(
blocking_task_runner_,
FROM_HERE,
base::Bind(&DriveCache::InitializeOnBlockingPool, base::Unretained(this)),
callback);
}
void DriveCache::RequestInitializeForTesting() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
blocking_task_runner_->PostTask(
FROM_HERE,
base::Bind(&DriveCache::InitializeOnBlockingPoolForTesting,
base::Unretained(this)));
}
void DriveCache::Destroy() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Invalidate the weak pointer.
weak_ptr_factory_.InvalidateWeakPtrs();
// Destroy myself on the blocking pool.
// Note that base::DeletePointer<> cannot be used as the destructor of this
// class is private.
blocking_task_runner_->PostTask(
FROM_HERE,
base::Bind(&DriveCache::DestroyOnBlockingPool, base::Unretained(this)));
}
bool DriveCache::InitializeOnBlockingPool() {
AssertOnSequencedWorkerPool();
if (!InitCachePaths(cache_paths_))
return false;
metadata_ = DriveCacheMetadata::CreateDriveCacheMetadata(
blocking_task_runner_);
return metadata_->Initialize(cache_paths_);
}
void DriveCache::InitializeOnBlockingPoolForTesting() {
AssertOnSequencedWorkerPool();
InitCachePaths(cache_paths_);
metadata_ = DriveCacheMetadata::CreateDriveCacheMetadataForTesting(
blocking_task_runner_);
metadata_->Initialize(cache_paths_);
}
void DriveCache::DestroyOnBlockingPool() {
AssertOnSequencedWorkerPool();
delete this;
}
bool DriveCache::GetCacheEntryOnBlockingPool(const std::string& resource_id,
const std::string& md5,
DriveCacheEntry* entry) {
DCHECK(entry);
AssertOnSequencedWorkerPool();
return metadata_->GetCacheEntry(resource_id, md5, entry);
}
void DriveCache::IterateOnBlockingPool(
const CacheIterateCallback& iteration_callback) {
AssertOnSequencedWorkerPool();
DCHECK(!iteration_callback.is_null());
metadata_->Iterate(iteration_callback);
}
bool DriveCache::FreeDiskSpaceOnBlockingPoolIfNeededFor(int64 num_bytes) {
AssertOnSequencedWorkerPool();
// Do nothing and return if we have enough space.
if (HasEnoughSpaceFor(num_bytes, cache_root_path_))
return true;
// Otherwise, try to free up the disk space.
DVLOG(1) << "Freeing up disk space for " << num_bytes;
// First remove temporary files from the metadata.
metadata_->RemoveTemporaryFiles();
// Then remove all files under "tmp" directory.
RemoveAllFiles(GetCacheDirectoryPath(CACHE_TYPE_TMP));
// Check the disk space again.
return HasEnoughSpaceFor(num_bytes, cache_root_path_);
}
scoped_ptr<DriveCache::GetFileResult> DriveCache::GetFileOnBlockingPool(
const std::string& resource_id,
const std::string& md5) {
AssertOnSequencedWorkerPool();
scoped_ptr<GetFileResult> result(new GetFileResult);
DriveCacheEntry cache_entry;
if (!GetCacheEntryOnBlockingPool(resource_id, md5, &cache_entry) ||
!cache_entry.is_present()) {
result->first = DRIVE_FILE_ERROR_NOT_FOUND;
return result.Pass();
}
CachedFileOrigin file_origin;
if (cache_entry.is_mounted()) {
file_origin = CACHED_FILE_MOUNTED;
} else if (cache_entry.is_dirty()) {
file_origin = CACHED_FILE_LOCALLY_MODIFIED;
} else {
file_origin = CACHED_FILE_FROM_SERVER;
}
result->first = DRIVE_FILE_OK;
result->second = GetCacheFilePath(resource_id,
md5,
GetSubDirectoryType(cache_entry),
file_origin);
return result.Pass();
}
DriveFileError DriveCache::StoreOnBlockingPool(
const std::string& resource_id,
const std::string& md5,
const FilePath& source_path,
FileOperationType file_operation_type) {
AssertOnSequencedWorkerPool();
if (file_operation_type == FILE_OPERATION_COPY) {
int64 file_size;
if (!file_util::GetFileSize(source_path, &file_size)) {
LOG(WARNING) << "Couldn't get file size for: " << source_path.value();
return DRIVE_FILE_ERROR_FAILED;
}
const bool enough_space = FreeDiskSpaceOnBlockingPoolIfNeededFor(file_size);
if (!enough_space)
return DRIVE_FILE_ERROR_NO_SPACE;
}
FilePath symlink_path;
CacheSubDirectoryType sub_dir_type = CACHE_TYPE_TMP;
// If file was previously pinned, store it in persistent dir.
DriveCacheEntry cache_entry;
if (GetCacheEntryOnBlockingPool(resource_id, md5, &cache_entry)) {
// File exists in cache.
// If file is dirty or mounted, return error.
if (cache_entry.is_dirty() || cache_entry.is_mounted()) {
LOG(WARNING) << "Can't store a file to replace a "
<< (cache_entry.is_dirty() ? "dirty" : "mounted")
<< " file: res_id=" << resource_id
<< ", md5=" << md5;
return DRIVE_FILE_ERROR_IN_USE;
}
if (cache_entry.is_pinned())
sub_dir_type = CACHE_TYPE_PERSISTENT;
}
FilePath dest_path = GetCacheFilePath(resource_id, md5, sub_dir_type,
CACHED_FILE_FROM_SERVER);
bool success = false;
switch (file_operation_type) {
case FILE_OPERATION_MOVE:
success = MoveFile(source_path, dest_path);
break;
case FILE_OPERATION_COPY:
success = CopyFile(source_path, dest_path);
break;
default:
NOTREACHED();
}
// Create symlink in pinned directory if the file is pinned.
if (success && cache_entry.is_pinned()) {
FilePath symlink_path = GetCacheFilePath(resource_id, std::string(),
CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER);
success = CreateSymlink(dest_path, symlink_path);
}
// Determine search pattern for stale filenames corresponding to resource_id,
// either "<resource_id>*" or "<resource_id>.*".
FilePath stale_filenames_pattern;
if (md5.empty()) {
// No md5 means no extension, append '*' after base name, i.e.
// "<resource_id>*".
// Cannot call |dest_path|.ReplaceExtension when there's no md5 extension:
// if base name of |dest_path| (i.e. escaped resource_id) contains the
// extension separator '.', ReplaceExtension will remove it and everything
// after it. The result will be nothing like the escaped resource_id.
stale_filenames_pattern = FilePath(dest_path.value() + util::kWildCard);
} else {
// Replace md5 extension with '*' i.e. "<resource_id>.*".
// Note that ReplaceExtension automatically prefixes the extension with the
// extension separator '.'.
stale_filenames_pattern = dest_path.ReplaceExtension(util::kWildCard);
}
// Delete files that match |stale_filenames_pattern| except for |dest_path|.
DeleteFilesSelectively(stale_filenames_pattern, dest_path);
if (success) {
// Now that file operations have completed, update metadata.
cache_entry.set_md5(md5);
cache_entry.set_is_present(true);
cache_entry.set_is_persistent(sub_dir_type == CACHE_TYPE_PERSISTENT);
metadata_->AddOrUpdateCacheEntry(resource_id, cache_entry);
}
return success ? DRIVE_FILE_OK : DRIVE_FILE_ERROR_FAILED;
}
DriveFileError DriveCache::PinOnBlockingPool(const std::string& resource_id,
const std::string& md5) {
AssertOnSequencedWorkerPool();
FilePath dest_path;
CacheSubDirectoryType sub_dir_type = CACHE_TYPE_PERSISTENT;
DriveCacheEntry cache_entry;
if (!GetCacheEntryOnBlockingPool(resource_id, md5, &cache_entry)) {
// Entry does not exist in cache. Set |dest_path| to /dev/null, so that
// symlinks to /dev/null will be picked up by DriveSyncClient to download
// pinned files that don't exist in cache.
dest_path = FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull);
// Set sub_dir_type to TMP. The file will be first downloaded in 'tmp',
// then moved to 'persistent'.
sub_dir_type = CACHE_TYPE_TMP;
} else { // File exists in cache, determines destination path.
// Determine source and destination paths.
// If file is dirty or mounted, don't move it.
if (cache_entry.is_dirty() || cache_entry.is_mounted()) {
DCHECK(cache_entry.is_persistent());
dest_path = GetCacheFilePath(resource_id,
md5,
GetSubDirectoryType(cache_entry),
CACHED_FILE_LOCALLY_MODIFIED);
} else {
// If file was pinned before but actual file blob doesn't exist in cache:
// - don't need to move the file.
// - don't create symlink since it already exists.
if (!cache_entry.is_present()) {
DCHECK(cache_entry.is_pinned());
return DRIVE_FILE_OK;
}
// File exists, move it to persistent dir.
// Gets the current path of the file in cache.
FilePath source_path = GetCacheFilePath(resource_id,
md5,
GetSubDirectoryType(cache_entry),
CACHED_FILE_FROM_SERVER);
dest_path = GetCacheFilePath(resource_id,
md5,
CACHE_TYPE_PERSISTENT,
CACHED_FILE_FROM_SERVER);
if (!MoveFile(source_path, dest_path))
return DRIVE_FILE_ERROR_FAILED;
}
}
// Create symlink in pinned dir.
FilePath symlink_path = GetCacheFilePath(resource_id,
std::string(),
CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER);
DCHECK(!dest_path.empty());
if (!CreateSymlink(dest_path, symlink_path))
return DRIVE_FILE_ERROR_FAILED;
// Now that file operations have completed, update metadata.
cache_entry.set_md5(md5);
cache_entry.set_is_pinned(true);
cache_entry.set_is_persistent(sub_dir_type == CACHE_TYPE_PERSISTENT);
metadata_->AddOrUpdateCacheEntry(resource_id, cache_entry);
return DRIVE_FILE_OK;
}
DriveFileError DriveCache::UnpinOnBlockingPool(const std::string& resource_id,
const std::string& md5) {
AssertOnSequencedWorkerPool();
// Unpinning a file means its entry must exist in cache.
DriveCacheEntry cache_entry;
if (!GetCacheEntryOnBlockingPool(resource_id, md5, &cache_entry)) {
LOG(WARNING) << "Can't unpin a file that wasn't pinned or cached: res_id="
<< resource_id
<< ", md5=" << md5;
return DRIVE_FILE_ERROR_NOT_FOUND;
}
CacheSubDirectoryType sub_dir_type = CACHE_TYPE_TMP;
// If file is dirty or mounted, don't move it.
if (cache_entry.is_dirty() || cache_entry.is_mounted()) {
sub_dir_type = CACHE_TYPE_PERSISTENT;
DCHECK(cache_entry.is_persistent());
} else {
// If file was pinned but actual file blob still doesn't exist in cache,
// don't need to move the file.
if (cache_entry.is_present()) {
// Gets the current path of the file in cache.
FilePath source_path = GetCacheFilePath(resource_id,
md5,
GetSubDirectoryType(cache_entry),
CACHED_FILE_FROM_SERVER);
// File exists, move it to tmp dir.
FilePath dest_path = GetCacheFilePath(resource_id,
md5,
CACHE_TYPE_TMP,
CACHED_FILE_FROM_SERVER);
if (!MoveFile(source_path, dest_path))
return DRIVE_FILE_ERROR_FAILED;
}
}
// If file was pinned, remove the symlink in pinned dir.
if (cache_entry.is_pinned()) {
FilePath symlink_path = GetCacheFilePath(resource_id,
std::string(),
CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER);
DeleteSymlink(symlink_path);
}
// Now that file operations have completed, update metadata.
if (cache_entry.is_present()) {
cache_entry.set_md5(md5);
cache_entry.set_is_pinned(false);
cache_entry.set_is_persistent(sub_dir_type == CACHE_TYPE_PERSISTENT);
metadata_->AddOrUpdateCacheEntry(resource_id, cache_entry);
} else {
// Remove the existing entry if we are unpinning a non-present file.
metadata_->RemoveCacheEntry(resource_id);
}
return DRIVE_FILE_OK;
}
scoped_ptr<DriveCache::GetFileResult> DriveCache::MarkAsMountedOnBlockingPool(
const std::string& resource_id,
const std::string& md5) {
AssertOnSequencedWorkerPool();
scoped_ptr<GetFileResult> result(new GetFileResult);
// Get cache entry associated with the resource_id and md5
DriveCacheEntry cache_entry;
if (!GetCacheEntryOnBlockingPool(resource_id, md5, &cache_entry)) {
result->first = DRIVE_FILE_ERROR_NOT_FOUND;
return result.Pass();
}
if (cache_entry.is_mounted()) {
result->first = DRIVE_FILE_ERROR_INVALID_OPERATION;
return result.Pass();
}
// Get the subdir type and path for the unmounted state.
CacheSubDirectoryType unmounted_subdir =
cache_entry.is_pinned() ? CACHE_TYPE_PERSISTENT : CACHE_TYPE_TMP;
FilePath unmounted_path = GetCacheFilePath(
resource_id, md5, unmounted_subdir, CACHED_FILE_FROM_SERVER);
// Get the subdir type and path for the mounted state.
CacheSubDirectoryType mounted_subdir = CACHE_TYPE_PERSISTENT;
FilePath mounted_path = GetCacheFilePath(
resource_id, md5, mounted_subdir, CACHED_FILE_MOUNTED);
// Move cache file.
bool success = MoveFile(unmounted_path, mounted_path);
if (success) {
// Now that cache operation is complete, update metadata.
cache_entry.set_md5(md5);
cache_entry.set_is_mounted(true);
cache_entry.set_is_persistent(true);
metadata_->AddOrUpdateCacheEntry(resource_id, cache_entry);
}
result->first = success ? DRIVE_FILE_OK : DRIVE_FILE_ERROR_FAILED;
result->second = mounted_path;
return result.Pass();
}
DriveFileError DriveCache::MarkAsUnmountedOnBlockingPool(
const FilePath& file_path) {
AssertOnSequencedWorkerPool();
// Parse file path to obtain resource_id, md5 and extra_extension.
std::string resource_id;
std::string md5;
std::string extra_extension;
util::ParseCacheFilePath(file_path, &resource_id, &md5, &extra_extension);
// The extra_extension shall be ".mounted" iff we're unmounting.
DCHECK(extra_extension == util::kMountedArchiveFileExtension);
// Get cache entry associated with the resource_id and md5
DriveCacheEntry cache_entry;
if (!GetCacheEntryOnBlockingPool(resource_id, md5, &cache_entry))
return DRIVE_FILE_ERROR_NOT_FOUND;
if (!cache_entry.is_mounted())
return DRIVE_FILE_ERROR_INVALID_OPERATION;
// Get the subdir type and path for the unmounted state.
CacheSubDirectoryType unmounted_subdir =
cache_entry.is_pinned() ? CACHE_TYPE_PERSISTENT : CACHE_TYPE_TMP;
FilePath unmounted_path = GetCacheFilePath(
resource_id, md5, unmounted_subdir, CACHED_FILE_FROM_SERVER);
// Get the subdir type and path for the mounted state.
CacheSubDirectoryType mounted_subdir = CACHE_TYPE_PERSISTENT;
FilePath mounted_path = GetCacheFilePath(
resource_id, md5, mounted_subdir, CACHED_FILE_MOUNTED);
// Move cache file.
if (!MoveFile(mounted_path, unmounted_path))
return DRIVE_FILE_ERROR_FAILED;
// Now that cache operation is complete, update metadata.
cache_entry.set_md5(md5);
cache_entry.set_is_mounted(false);
cache_entry.set_is_persistent(unmounted_subdir == CACHE_TYPE_PERSISTENT);
metadata_->AddOrUpdateCacheEntry(resource_id, cache_entry);
return DRIVE_FILE_OK;
}
DriveFileError DriveCache::MarkDirtyOnBlockingPool(
const std::string& resource_id,
const std::string& md5) {
AssertOnSequencedWorkerPool();
// If file has already been marked dirty in previous instance of chrome, we
// would have lost the md5 info during cache initialization, because the file
// would have been renamed to .local extension.
// So, search for entry in cache without comparing md5.
// Marking a file dirty means its entry and actual file blob must exist in
// cache.
DriveCacheEntry cache_entry;
if (!GetCacheEntryOnBlockingPool(resource_id, std::string(), &cache_entry) ||
!cache_entry.is_present()) {
LOG(WARNING) << "Can't mark dirty a file that wasn't cached: res_id="
<< resource_id
<< ", md5=" << md5;
return DRIVE_FILE_ERROR_NOT_FOUND;
}
// If a file is already dirty (i.e. MarkDirtyInCache was called before),
// delete outgoing symlink if it exists.
// TODO(benchan): We should only delete outgoing symlink if file is currently
// not being uploaded. However, for now, cache doesn't know if uploading of a
// file is in progress. Per zel, the upload process should be canceled before
// MarkDirtyInCache is called again.
if (cache_entry.is_dirty()) {
// The file must be in persistent dir.
DCHECK(cache_entry.is_persistent());
// Determine symlink path in outgoing dir, so as to remove it.
FilePath symlink_path = GetCacheFilePath(resource_id,
std::string(),
CACHE_TYPE_OUTGOING,
CACHED_FILE_FROM_SERVER);
DeleteSymlink(symlink_path);
return DRIVE_FILE_OK;
}
// Move file to persistent dir with new .local extension.
// Get the current path of the file in cache.
FilePath source_path = GetCacheFilePath(resource_id,
md5,
GetSubDirectoryType(cache_entry),
CACHED_FILE_FROM_SERVER);
// Determine destination path.
const CacheSubDirectoryType sub_dir_type = CACHE_TYPE_PERSISTENT;
FilePath cache_file_path = GetCacheFilePath(resource_id,
md5,
sub_dir_type,
CACHED_FILE_LOCALLY_MODIFIED);
bool success = MoveFile(source_path, cache_file_path);
// If file is pinned, update symlink in pinned dir.
if (success && cache_entry.is_pinned()) {
FilePath symlink_path = GetCacheFilePath(resource_id,
std::string(),
CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER);
success = CreateSymlink(cache_file_path, symlink_path);
}
if (success) {
// Now that file operations have completed, update metadata.
cache_entry.set_md5(md5);
cache_entry.set_is_dirty(true);
cache_entry.set_is_persistent(sub_dir_type == CACHE_TYPE_PERSISTENT);
metadata_->AddOrUpdateCacheEntry(resource_id, cache_entry);
}
return success ? DRIVE_FILE_OK : DRIVE_FILE_ERROR_FAILED;
}
DriveFileError DriveCache::CommitDirtyOnBlockingPool(
const std::string& resource_id,
const std::string& md5) {
AssertOnSequencedWorkerPool();
// If file has already been marked dirty in previous instance of chrome, we
// would have lost the md5 info during cache initialization, because the file
// would have been renamed to .local extension.
// So, search for entry in cache without comparing md5.
// Committing a file dirty means its entry and actual file blob must exist in
// cache.
DriveCacheEntry cache_entry;
if (!GetCacheEntryOnBlockingPool(resource_id, std::string(), &cache_entry) ||
!cache_entry.is_present()) {
LOG(WARNING) << "Can't commit dirty a file that wasn't cached: res_id="
<< resource_id
<< ", md5=" << md5;
return DRIVE_FILE_ERROR_NOT_FOUND;
}
// If a file is not dirty (it should have been marked dirty via
// MarkDirtyInCache), committing it dirty is an invalid operation.
if (!cache_entry.is_dirty()) {
LOG(WARNING) << "Can't commit a non-dirty file: res_id="
<< resource_id
<< ", md5=" << md5;
return DRIVE_FILE_ERROR_INVALID_OPERATION;
}
// Dirty files must be in persistent dir.
DCHECK(cache_entry.is_persistent());
// Create symlink in outgoing dir.
FilePath symlink_path = GetCacheFilePath(resource_id,
std::string(),
CACHE_TYPE_OUTGOING,
CACHED_FILE_FROM_SERVER);
// Get target path of symlink i.e. current path of the file in cache.
FilePath target_path = GetCacheFilePath(resource_id,
md5,
GetSubDirectoryType(cache_entry),
CACHED_FILE_LOCALLY_MODIFIED);
return CreateSymlink(target_path, symlink_path) ?
DRIVE_FILE_OK : DRIVE_FILE_ERROR_FAILED;
}
DriveFileError DriveCache::ClearDirtyOnBlockingPool(
const std::string& resource_id,
const std::string& md5) {
AssertOnSequencedWorkerPool();
// |md5| is the new .<md5> extension to rename the file to.
// So, search for entry in cache without comparing md5.
DriveCacheEntry cache_entry;
// Clearing a dirty file means its entry and actual file blob must exist in
// cache.
if (!GetCacheEntryOnBlockingPool(resource_id, std::string(), &cache_entry) ||
!cache_entry.is_present()) {
LOG(WARNING) << "Can't clear dirty state of a file that wasn't cached: "
<< "res_id=" << resource_id
<< ", md5=" << md5;
return DRIVE_FILE_ERROR_NOT_FOUND;
}
// If a file is not dirty (it should have been marked dirty via
// MarkDirtyInCache), clearing its dirty state is an invalid operation.
if (!cache_entry.is_dirty()) {
LOG(WARNING) << "Can't clear dirty state of a non-dirty file: res_id="
<< resource_id
<< ", md5=" << md5;
return DRIVE_FILE_ERROR_INVALID_OPERATION;
}
// File must be dirty and hence in persistent dir.
DCHECK(cache_entry.is_persistent());
// Get the current path of the file in cache.
FilePath source_path = GetCacheFilePath(resource_id,
md5,
GetSubDirectoryType(cache_entry),
CACHED_FILE_LOCALLY_MODIFIED);
// Determine destination path.
// If file is pinned, move it to persistent dir with .md5 extension;
// otherwise, move it to tmp dir with .md5 extension.
const CacheSubDirectoryType sub_dir_type =
cache_entry.is_pinned() ? CACHE_TYPE_PERSISTENT : CACHE_TYPE_TMP;
FilePath dest_path = GetCacheFilePath(resource_id,
md5,
sub_dir_type,
CACHED_FILE_FROM_SERVER);
bool success = MoveFile(source_path, dest_path);
if (success) {
// Delete symlink in outgoing dir.
FilePath symlink_path = GetCacheFilePath(resource_id,
std::string(),
CACHE_TYPE_OUTGOING,
CACHED_FILE_FROM_SERVER);
DeleteSymlink(symlink_path);
}
// If file is pinned, update symlink in pinned dir.
if (success && cache_entry.is_pinned()) {
FilePath symlink_path = GetCacheFilePath(resource_id,
std::string(),
CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER);
success = CreateSymlink(dest_path, symlink_path);
}
if (success) {
// Now that file operations have completed, update metadata.
cache_entry.set_md5(md5);
cache_entry.set_is_dirty(false);
cache_entry.set_is_persistent(sub_dir_type == CACHE_TYPE_PERSISTENT);
metadata_->AddOrUpdateCacheEntry(resource_id, cache_entry);
}
return success ? DRIVE_FILE_OK : DRIVE_FILE_ERROR_FAILED;
}
DriveFileError DriveCache::RemoveOnBlockingPool(
const std::string& resource_id) {
AssertOnSequencedWorkerPool();
// MD5 is not passed into RemoveCacheEntry because we would delete all
// cache files corresponding to <resource_id> regardless of the md5.
// So, search for entry in cache without taking md5 into account.
DriveCacheEntry cache_entry;
// If entry doesn't exist or is dirty or mounted in cache, nothing to do.
const bool entry_found =
GetCacheEntryOnBlockingPool(resource_id, std::string(), &cache_entry);
if (!entry_found || cache_entry.is_dirty() || cache_entry.is_mounted()) {
DVLOG(1) << "Entry is "
<< (entry_found ?
(cache_entry.is_dirty() ? "dirty" : "mounted") :
"non-existent")
<< " in cache, not removing";
return DRIVE_FILE_OK;
}
// Determine paths to delete all cache versions of |resource_id| in
// persistent, tmp and pinned directories.
std::vector<FilePath> paths_to_delete;
// For files in persistent and tmp dirs, delete files that match
// "<resource_id>.*".
paths_to_delete.push_back(GetCacheFilePath(resource_id,
util::kWildCard,
CACHE_TYPE_PERSISTENT,
CACHED_FILE_FROM_SERVER));
paths_to_delete.push_back(GetCacheFilePath(resource_id,
util::kWildCard,
CACHE_TYPE_TMP,
CACHED_FILE_FROM_SERVER));
// For pinned files, filename is "<resource_id>" with no extension, so delete
// "<resource_id>".
paths_to_delete.push_back(GetCacheFilePath(resource_id,
std::string(),
CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER));
// Don't delete locally modified (i.e. dirty and possibly outgoing) files.
// Since we're not deleting outgoing symlinks, we don't need to append
// outgoing path to |paths_to_delete|.
FilePath path_to_keep = GetCacheFilePath(resource_id,
std::string(),
CACHE_TYPE_PERSISTENT,
CACHED_FILE_LOCALLY_MODIFIED);
for (size_t i = 0; i < paths_to_delete.size(); ++i) {
DeleteFilesSelectively(paths_to_delete[i], path_to_keep);
}
// Now that all file operations have completed, remove from metadata.
metadata_->RemoveCacheEntry(resource_id);
return DRIVE_FILE_OK;
}
bool DriveCache::ClearAllOnBlockingPool() {
AssertOnSequencedWorkerPool();
if (!file_util::Delete(cache_root_path_, true)) {
LOG(WARNING) << "Failed to delete the cache directory";
return false;
}
if (!InitializeOnBlockingPool()) {
LOG(WARNING) << "Failed to initialize the cache";
return false;
}
return true;
}
void DriveCache::OnPinned(const std::string& resource_id,
const std::string& md5,
const FileOperationCallback& callback,
DriveFileError error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
callback.Run(error);
if (error == DRIVE_FILE_OK)
FOR_EACH_OBSERVER(DriveCacheObserver,
observers_,
OnCachePinned(resource_id, md5));
}
void DriveCache::OnUnpinned(const std::string& resource_id,
const std::string& md5,
const FileOperationCallback& callback,
DriveFileError error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
callback.Run(error);
if (error == DRIVE_FILE_OK)
FOR_EACH_OBSERVER(DriveCacheObserver,
observers_,
OnCacheUnpinned(resource_id, md5));
// Now the file is moved from "persistent" to "tmp" directory.
// It's a chance to free up space if needed.
blocking_task_runner_->PostTask(
FROM_HERE,
base::Bind(
base::IgnoreResult(
&DriveCache::FreeDiskSpaceOnBlockingPoolIfNeededFor),
base::Unretained(this), 0));
}
void DriveCache::OnCommitDirty(const std::string& resource_id,
const FileOperationCallback& callback,
DriveFileError error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
callback.Run(error);
if (error == DRIVE_FILE_OK)
FOR_EACH_OBSERVER(DriveCacheObserver,
observers_,
OnCacheCommitted(resource_id));
}
bool DriveCache::HasEnoughSpaceFor(int64 num_bytes, const FilePath& path) {
int64 free_space = 0;
if (free_disk_space_getter_)
free_space = free_disk_space_getter_->AmountOfFreeDiskSpace();
else
free_space = base::SysInfo::AmountOfFreeDiskSpace(path);
// Subtract this as if this portion does not exist.
free_space -= kMinFreeSpace;
return (free_space >= num_bytes);
}
// static
FilePath DriveCache::GetCacheRootPath(Profile* profile) {
FilePath cache_base_path;
chrome::GetUserCacheDirectory(profile->GetPath(), &cache_base_path);
FilePath cache_root_path =
cache_base_path.Append(chrome::kDriveCacheDirname);
return cache_root_path.Append(kDriveCacheVersionDir);
}
// static
std::vector<FilePath> DriveCache::GetCachePaths(
const FilePath& cache_root_path) {
std::vector<FilePath> cache_paths;
// The order should match DriveCache::CacheSubDirectoryType enum.
cache_paths.push_back(cache_root_path.Append(kDriveCacheMetaDir));
cache_paths.push_back(cache_root_path.Append(kDriveCachePinnedDir));
cache_paths.push_back(cache_root_path.Append(kDriveCacheOutgoingDir));
cache_paths.push_back(cache_root_path.Append(kDriveCachePersistentDir));
cache_paths.push_back(cache_root_path.Append(kDriveCacheTmpDir));
cache_paths.push_back(cache_root_path.Append(kDriveCacheTmpDownloadsDir));
cache_paths.push_back(cache_root_path.Append(kDriveCacheTmpDocumentsDir));
return cache_paths;
}
// static
bool DriveCache::CreateCacheDirectories(
const std::vector<FilePath>& paths_to_create) {
bool success = true;
for (size_t i = 0; i < paths_to_create.size(); ++i) {
if (file_util::DirectoryExists(paths_to_create[i]))
continue;
if (!file_util::CreateDirectory(paths_to_create[i])) {
// Error creating this directory, record error and proceed with next one.
success = false;
PLOG(ERROR) << "Error creating directory " << paths_to_create[i].value();
} else {
DVLOG(1) << "Created directory " << paths_to_create[i].value();
}
}
return success;
}
// static
DriveCache::CacheSubDirectoryType DriveCache::GetSubDirectoryType(
const DriveCacheEntry& cache_entry) {
return cache_entry.is_persistent() ? CACHE_TYPE_PERSISTENT : CACHE_TYPE_TMP;
}
} // namespace drive
|