forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdirectory.cc
1572 lines (1369 loc) · 54.1 KB
/
directory.cc
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
// Copyright 2013 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 "sync/syncable/directory.h"
#include <algorithm>
#include <iterator>
#include "base/base64.h"
#include "base/guid.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/trace_event/trace_event.h"
#include "sync/internal_api/public/base/attachment_id_proto.h"
#include "sync/internal_api/public/base/unique_position.h"
#include "sync/internal_api/public/util/unrecoverable_error_handler.h"
#include "sync/syncable/entry.h"
#include "sync/syncable/entry_kernel.h"
#include "sync/syncable/in_memory_directory_backing_store.h"
#include "sync/syncable/on_disk_directory_backing_store.h"
#include "sync/syncable/scoped_kernel_lock.h"
#include "sync/syncable/scoped_parent_child_index_updater.h"
#include "sync/syncable/syncable-inl.h"
#include "sync/syncable/syncable_base_transaction.h"
#include "sync/syncable/syncable_changes_version.h"
#include "sync/syncable/syncable_read_transaction.h"
#include "sync/syncable/syncable_util.h"
#include "sync/syncable/syncable_write_transaction.h"
using std::string;
namespace syncer {
namespace syncable {
// static
const base::FilePath::CharType Directory::kSyncDatabaseFilename[] =
FILE_PATH_LITERAL("SyncData.sqlite3");
Directory::PersistedKernelInfo::PersistedKernelInfo() {
ModelTypeSet protocol_types = ProtocolTypes();
for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
iter.Inc()) {
ResetDownloadProgress(iter.Get());
transaction_version[iter.Get()] = 0;
}
}
Directory::PersistedKernelInfo::~PersistedKernelInfo() {}
void Directory::PersistedKernelInfo::ResetDownloadProgress(
ModelType model_type) {
// Clear everything except the data type id field.
download_progress[model_type].Clear();
download_progress[model_type].set_data_type_id(
GetSpecificsFieldNumberFromModelType(model_type));
// Explicitly set an empty token field to denote no progress.
download_progress[model_type].set_token("");
}
bool Directory::PersistedKernelInfo::HasEmptyDownloadProgress(
ModelType model_type) {
const sync_pb::DataTypeProgressMarker& progress_marker =
download_progress[model_type];
return progress_marker.token().empty();
}
Directory::SaveChangesSnapshot::SaveChangesSnapshot()
: kernel_info_status(KERNEL_SHARE_INFO_INVALID) {
}
Directory::SaveChangesSnapshot::~SaveChangesSnapshot() {
STLDeleteElements(&dirty_metas);
STLDeleteElements(&delete_journals);
}
bool Directory::SaveChangesSnapshot::HasUnsavedMetahandleChanges() const {
return !dirty_metas.empty() || !metahandles_to_purge.empty() ||
!delete_journals.empty() || !delete_journals_to_purge.empty();
}
Directory::Kernel::Kernel(
const std::string& name,
const KernelLoadInfo& info,
DirectoryChangeDelegate* delegate,
const WeakHandle<TransactionObserver>& transaction_observer)
: next_write_transaction_id(0),
name(name),
info_status(Directory::KERNEL_SHARE_INFO_VALID),
persisted_info(info.kernel_info),
cache_guid(info.cache_guid),
next_metahandle(info.max_metahandle + 1),
delegate(delegate),
transaction_observer(transaction_observer) {
DCHECK(delegate);
DCHECK(transaction_observer.IsInitialized());
}
Directory::Kernel::~Kernel() {
STLDeleteContainerPairSecondPointers(metahandles_map.begin(),
metahandles_map.end());
}
Directory::Directory(
DirectoryBackingStore* store,
const WeakHandle<UnrecoverableErrorHandler>& unrecoverable_error_handler,
const base::Closure& report_unrecoverable_error_function,
NigoriHandler* nigori_handler,
Cryptographer* cryptographer)
: kernel_(NULL),
store_(store),
unrecoverable_error_handler_(unrecoverable_error_handler),
report_unrecoverable_error_function_(report_unrecoverable_error_function),
unrecoverable_error_set_(false),
nigori_handler_(nigori_handler),
cryptographer_(cryptographer),
invariant_check_level_(VERIFY_CHANGES),
weak_ptr_factory_(this) {}
Directory::~Directory() {
Close();
}
DirOpenResult Directory::Open(
const string& name,
DirectoryChangeDelegate* delegate,
const WeakHandle<TransactionObserver>& transaction_observer) {
TRACE_EVENT0("sync", "SyncDatabaseOpen");
const DirOpenResult result =
OpenImpl(name, delegate, transaction_observer);
if (OPENED != result)
Close();
return result;
}
void Directory::InitializeIndices(MetahandlesMap* handles_map) {
ScopedKernelLock lock(this);
kernel_->metahandles_map.swap(*handles_map);
for (MetahandlesMap::const_iterator it = kernel_->metahandles_map.begin();
it != kernel_->metahandles_map.end(); ++it) {
EntryKernel* entry = it->second;
if (ParentChildIndex::ShouldInclude(entry))
kernel_->parent_child_index.Insert(entry);
const int64 metahandle = entry->ref(META_HANDLE);
if (entry->ref(IS_UNSYNCED))
kernel_->unsynced_metahandles.insert(metahandle);
if (entry->ref(IS_UNAPPLIED_UPDATE)) {
const ModelType type = entry->GetServerModelType();
kernel_->unapplied_update_metahandles[type].insert(metahandle);
}
if (!entry->ref(UNIQUE_SERVER_TAG).empty()) {
DCHECK(kernel_->server_tags_map.find(entry->ref(UNIQUE_SERVER_TAG)) ==
kernel_->server_tags_map.end())
<< "Unexpected duplicate use of client tag";
kernel_->server_tags_map[entry->ref(UNIQUE_SERVER_TAG)] = entry;
}
if (!entry->ref(UNIQUE_CLIENT_TAG).empty()) {
DCHECK(kernel_->server_tags_map.find(entry->ref(UNIQUE_SERVER_TAG)) ==
kernel_->server_tags_map.end())
<< "Unexpected duplicate use of server tag";
kernel_->client_tags_map[entry->ref(UNIQUE_CLIENT_TAG)] = entry;
}
DCHECK(kernel_->ids_map.find(entry->ref(ID).value()) ==
kernel_->ids_map.end()) << "Unexpected duplicate use of ID";
kernel_->ids_map[entry->ref(ID).value()] = entry;
DCHECK(!entry->is_dirty());
AddToAttachmentIndex(lock, metahandle, entry->ref(ATTACHMENT_METADATA));
}
}
DirOpenResult Directory::OpenImpl(
const string& name,
DirectoryChangeDelegate* delegate,
const WeakHandle<TransactionObserver>&
transaction_observer) {
KernelLoadInfo info;
// Temporary indices before kernel_ initialized in case Load fails. We 0(1)
// swap these later.
Directory::MetahandlesMap tmp_handles_map;
// Avoids mem leaks on failure. Harmlessly deletes the empty hash map after
// the swap in the success case.
STLValueDeleter<MetahandlesMap> deleter(&tmp_handles_map);
JournalIndex delete_journals;
MetahandleSet metahandles_to_purge;
DirOpenResult result = store_->Load(&tmp_handles_map, &delete_journals,
&metahandles_to_purge, &info);
if (OPENED != result)
return result;
DCHECK(!kernel_);
kernel_ = new Kernel(name, info, delegate, transaction_observer);
kernel_->metahandles_to_purge.swap(metahandles_to_purge);
delete_journal_.reset(new DeleteJournal(&delete_journals));
InitializeIndices(&tmp_handles_map);
// Save changes back in case there are any metahandles to purge.
if (!SaveChanges())
return FAILED_INITIAL_WRITE;
// Now that we've successfully opened the store, install an error handler to
// deal with catastrophic errors that may occur later on. Use a weak pointer
// because we cannot guarantee that this Directory will outlive the Closure.
store_->SetCatastrophicErrorHandler(base::Bind(
&Directory::OnCatastrophicError, weak_ptr_factory_.GetWeakPtr()));
return OPENED;
}
DeleteJournal* Directory::delete_journal() {
DCHECK(delete_journal_.get());
return delete_journal_.get();
}
void Directory::Close() {
store_.reset();
if (kernel_) {
delete kernel_;
kernel_ = NULL;
}
}
void Directory::OnUnrecoverableError(const BaseTransaction* trans,
const tracked_objects::Location& location,
const std::string & message) {
DCHECK(trans != NULL);
unrecoverable_error_set_ = true;
unrecoverable_error_handler_.Call(
FROM_HERE, &UnrecoverableErrorHandler::OnUnrecoverableError, location,
message);
}
EntryKernel* Directory::GetEntryById(const Id& id) {
ScopedKernelLock lock(this);
return GetEntryById(lock, id);
}
EntryKernel* Directory::GetEntryById(const ScopedKernelLock& lock,
const Id& id) {
DCHECK(kernel_);
// Find it in the in memory ID index.
IdsMap::iterator id_found = kernel_->ids_map.find(id.value());
if (id_found != kernel_->ids_map.end()) {
return id_found->second;
}
return NULL;
}
EntryKernel* Directory::GetEntryByClientTag(const string& tag) {
ScopedKernelLock lock(this);
DCHECK(kernel_);
TagsMap::iterator it = kernel_->client_tags_map.find(tag);
if (it != kernel_->client_tags_map.end()) {
return it->second;
}
return NULL;
}
EntryKernel* Directory::GetEntryByServerTag(const string& tag) {
ScopedKernelLock lock(this);
DCHECK(kernel_);
TagsMap::iterator it = kernel_->server_tags_map.find(tag);
if (it != kernel_->server_tags_map.end()) {
return it->second;
}
return NULL;
}
EntryKernel* Directory::GetEntryByHandle(int64 metahandle) {
ScopedKernelLock lock(this);
return GetEntryByHandle(lock, metahandle);
}
EntryKernel* Directory::GetEntryByHandle(const ScopedKernelLock& lock,
int64 metahandle) {
// Look up in memory
MetahandlesMap::iterator found =
kernel_->metahandles_map.find(metahandle);
if (found != kernel_->metahandles_map.end()) {
// Found it in memory. Easy.
return found->second;
}
return NULL;
}
bool Directory::GetChildHandlesById(
BaseTransaction* trans, const Id& parent_id,
Directory::Metahandles* result) {
if (!SyncAssert(this == trans->directory(), FROM_HERE,
"Directories don't match", trans))
return false;
result->clear();
ScopedKernelLock lock(this);
AppendChildHandles(lock, parent_id, result);
return true;
}
int Directory::GetTotalNodeCount(
BaseTransaction* trans,
EntryKernel* kernel) const {
if (!SyncAssert(this == trans->directory(), FROM_HERE,
"Directories don't match", trans))
return false;
int count = 1;
std::deque<const OrderedChildSet*> child_sets;
GetChildSetForKernel(trans, kernel, &child_sets);
while (!child_sets.empty()) {
const OrderedChildSet* set = child_sets.front();
child_sets.pop_front();
for (OrderedChildSet::const_iterator it = set->begin();
it != set->end(); ++it) {
count++;
GetChildSetForKernel(trans, *it, &child_sets);
}
}
return count;
}
void Directory::GetChildSetForKernel(
BaseTransaction* trans,
EntryKernel* kernel,
std::deque<const OrderedChildSet*>* child_sets) const {
if (!kernel->ref(IS_DIR))
return; // Not a directory => no children.
const OrderedChildSet* descendants =
kernel_->parent_child_index.GetChildren(kernel->ref(ID));
if (!descendants)
return; // This directory has no children.
// Add our children to the list of items to be traversed.
child_sets->push_back(descendants);
}
int Directory::GetPositionIndex(
BaseTransaction* trans,
EntryKernel* kernel) const {
const OrderedChildSet* siblings =
kernel_->parent_child_index.GetSiblings(kernel);
OrderedChildSet::const_iterator it = siblings->find(kernel);
return std::distance(siblings->begin(), it);
}
bool Directory::InsertEntry(BaseWriteTransaction* trans, EntryKernel* entry) {
ScopedKernelLock lock(this);
return InsertEntry(lock, trans, entry);
}
bool Directory::InsertEntry(const ScopedKernelLock& lock,
BaseWriteTransaction* trans,
EntryKernel* entry) {
if (!SyncAssert(NULL != entry, FROM_HERE, "Entry is null", trans))
return false;
static const char error[] = "Entry already in memory index.";
if (!SyncAssert(
kernel_->metahandles_map.insert(
std::make_pair(entry->ref(META_HANDLE), entry)).second,
FROM_HERE,
error,
trans)) {
return false;
}
if (!SyncAssert(
kernel_->ids_map.insert(
std::make_pair(entry->ref(ID).value(), entry)).second,
FROM_HERE,
error,
trans)) {
return false;
}
if (ParentChildIndex::ShouldInclude(entry)) {
if (!SyncAssert(kernel_->parent_child_index.Insert(entry),
FROM_HERE,
error,
trans)) {
return false;
}
}
AddToAttachmentIndex(
lock, entry->ref(META_HANDLE), entry->ref(ATTACHMENT_METADATA));
// Should NEVER be created with a client tag or server tag.
if (!SyncAssert(entry->ref(UNIQUE_SERVER_TAG).empty(), FROM_HERE,
"Server tag should be empty", trans)) {
return false;
}
if (!SyncAssert(entry->ref(UNIQUE_CLIENT_TAG).empty(), FROM_HERE,
"Client tag should be empty", trans))
return false;
return true;
}
bool Directory::ReindexId(BaseWriteTransaction* trans,
EntryKernel* const entry,
const Id& new_id) {
ScopedKernelLock lock(this);
if (NULL != GetEntryById(lock, new_id))
return false;
{
// Update the indices that depend on the ID field.
ScopedParentChildIndexUpdater updater_b(lock, entry,
&kernel_->parent_child_index);
size_t num_erased = kernel_->ids_map.erase(entry->ref(ID).value());
DCHECK_EQ(1U, num_erased);
entry->put(ID, new_id);
kernel_->ids_map[entry->ref(ID).value()] = entry;
}
return true;
}
bool Directory::ReindexParentId(BaseWriteTransaction* trans,
EntryKernel* const entry,
const Id& new_parent_id) {
ScopedKernelLock lock(this);
{
// Update the indices that depend on the PARENT_ID field.
ScopedParentChildIndexUpdater index_updater(lock, entry,
&kernel_->parent_child_index);
entry->put(PARENT_ID, new_parent_id);
}
return true;
}
void Directory::RemoveFromAttachmentIndex(
const ScopedKernelLock& lock,
const int64 metahandle,
const sync_pb::AttachmentMetadata& attachment_metadata) {
for (int i = 0; i < attachment_metadata.record_size(); ++i) {
AttachmentIdUniqueId unique_id =
attachment_metadata.record(i).id().unique_id();
IndexByAttachmentId::iterator iter =
kernel_->index_by_attachment_id.find(unique_id);
if (iter != kernel_->index_by_attachment_id.end()) {
iter->second.erase(metahandle);
if (iter->second.empty()) {
kernel_->index_by_attachment_id.erase(iter);
}
}
}
}
void Directory::AddToAttachmentIndex(
const ScopedKernelLock& lock,
const int64 metahandle,
const sync_pb::AttachmentMetadata& attachment_metadata) {
for (int i = 0; i < attachment_metadata.record_size(); ++i) {
AttachmentIdUniqueId unique_id =
attachment_metadata.record(i).id().unique_id();
IndexByAttachmentId::iterator iter =
kernel_->index_by_attachment_id.find(unique_id);
if (iter == kernel_->index_by_attachment_id.end()) {
iter = kernel_->index_by_attachment_id.insert(std::make_pair(
unique_id,
MetahandleSet())).first;
}
iter->second.insert(metahandle);
}
}
void Directory::UpdateAttachmentIndex(
const int64 metahandle,
const sync_pb::AttachmentMetadata& old_metadata,
const sync_pb::AttachmentMetadata& new_metadata) {
ScopedKernelLock lock(this);
RemoveFromAttachmentIndex(lock, metahandle, old_metadata);
AddToAttachmentIndex(lock, metahandle, new_metadata);
}
void Directory::GetMetahandlesByAttachmentId(
BaseTransaction* trans,
const sync_pb::AttachmentIdProto& attachment_id_proto,
Metahandles* result) {
DCHECK(result);
result->clear();
ScopedKernelLock lock(this);
IndexByAttachmentId::const_iterator index_iter =
kernel_->index_by_attachment_id.find(attachment_id_proto.unique_id());
if (index_iter == kernel_->index_by_attachment_id.end())
return;
const MetahandleSet& metahandle_set = index_iter->second;
std::copy(
metahandle_set.begin(), metahandle_set.end(), back_inserter(*result));
}
bool Directory::unrecoverable_error_set(const BaseTransaction* trans) const {
DCHECK(trans != NULL);
return unrecoverable_error_set_;
}
void Directory::ClearDirtyMetahandles(const ScopedKernelLock& lock) {
kernel_->transaction_mutex.AssertAcquired();
kernel_->dirty_metahandles.clear();
}
bool Directory::SafeToPurgeFromMemory(WriteTransaction* trans,
const EntryKernel* const entry) const {
bool safe = entry->ref(IS_DEL) && !entry->is_dirty() &&
!entry->ref(SYNCING) && !entry->ref(IS_UNAPPLIED_UPDATE) &&
!entry->ref(IS_UNSYNCED);
if (safe) {
int64 handle = entry->ref(META_HANDLE);
const ModelType type = entry->GetServerModelType();
if (!SyncAssert(kernel_->dirty_metahandles.count(handle) == 0U,
FROM_HERE,
"Dirty metahandles should be empty", trans))
return false;
// TODO(tim): Bug 49278.
if (!SyncAssert(!kernel_->unsynced_metahandles.count(handle),
FROM_HERE,
"Unsynced handles should be empty",
trans))
return false;
if (!SyncAssert(!kernel_->unapplied_update_metahandles[type].count(handle),
FROM_HERE,
"Unapplied metahandles should be empty",
trans))
return false;
}
return safe;
}
void Directory::TakeSnapshotForSaveChanges(SaveChangesSnapshot* snapshot) {
ReadTransaction trans(FROM_HERE, this);
ScopedKernelLock lock(this);
// If there is an unrecoverable error then just bail out.
if (unrecoverable_error_set(&trans))
return;
// Deep copy dirty entries from kernel_->metahandles_index into snapshot and
// clear dirty flags.
for (MetahandleSet::const_iterator i = kernel_->dirty_metahandles.begin();
i != kernel_->dirty_metahandles.end(); ++i) {
EntryKernel* entry = GetEntryByHandle(lock, *i);
if (!entry)
continue;
// Skip over false positives; it happens relatively infrequently.
if (!entry->is_dirty())
continue;
snapshot->dirty_metas.insert(snapshot->dirty_metas.end(),
new EntryKernel(*entry));
DCHECK_EQ(1U, kernel_->dirty_metahandles.count(*i));
// We don't bother removing from the index here as we blow the entire thing
// in a moment, and it unnecessarily complicates iteration.
entry->clear_dirty(NULL);
}
ClearDirtyMetahandles(lock);
// Set purged handles.
DCHECK(snapshot->metahandles_to_purge.empty());
snapshot->metahandles_to_purge.swap(kernel_->metahandles_to_purge);
// Fill kernel_info_status and kernel_info.
snapshot->kernel_info = kernel_->persisted_info;
snapshot->kernel_info_status = kernel_->info_status;
// This one we reset on failure.
kernel_->info_status = KERNEL_SHARE_INFO_VALID;
delete_journal_->TakeSnapshotAndClear(
&trans, &snapshot->delete_journals, &snapshot->delete_journals_to_purge);
}
bool Directory::SaveChanges() {
bool success = false;
base::AutoLock scoped_lock(kernel_->save_changes_mutex);
// Snapshot and save.
SaveChangesSnapshot snapshot;
TakeSnapshotForSaveChanges(&snapshot);
success = store_->SaveChanges(snapshot);
// Handle success or failure.
if (success)
success = VacuumAfterSaveChanges(snapshot);
else
HandleSaveChangesFailure(snapshot);
return success;
}
bool Directory::VacuumAfterSaveChanges(const SaveChangesSnapshot& snapshot) {
if (snapshot.dirty_metas.empty())
return true;
// Need a write transaction as we are about to permanently purge entries.
WriteTransaction trans(FROM_HERE, VACUUM_AFTER_SAVE, this);
ScopedKernelLock lock(this);
// Now drop everything we can out of memory.
for (EntryKernelSet::const_iterator i = snapshot.dirty_metas.begin();
i != snapshot.dirty_metas.end(); ++i) {
MetahandlesMap::iterator found =
kernel_->metahandles_map.find((*i)->ref(META_HANDLE));
EntryKernel* entry = (found == kernel_->metahandles_map.end() ?
NULL : found->second);
if (entry && SafeToPurgeFromMemory(&trans, entry)) {
// We now drop deleted metahandles that are up to date on both the client
// and the server.
size_t num_erased = 0;
num_erased = kernel_->metahandles_map.erase(entry->ref(META_HANDLE));
DCHECK_EQ(1u, num_erased);
num_erased = kernel_->ids_map.erase(entry->ref(ID).value());
DCHECK_EQ(1u, num_erased);
if (!entry->ref(UNIQUE_SERVER_TAG).empty()) {
num_erased =
kernel_->server_tags_map.erase(entry->ref(UNIQUE_SERVER_TAG));
DCHECK_EQ(1u, num_erased);
}
if (!entry->ref(UNIQUE_CLIENT_TAG).empty()) {
num_erased =
kernel_->client_tags_map.erase(entry->ref(UNIQUE_CLIENT_TAG));
DCHECK_EQ(1u, num_erased);
}
if (!SyncAssert(!kernel_->parent_child_index.Contains(entry),
FROM_HERE,
"Deleted entry still present",
(&trans)))
return false;
RemoveFromAttachmentIndex(
lock, entry->ref(META_HANDLE), entry->ref(ATTACHMENT_METADATA));
delete entry;
}
if (trans.unrecoverable_error_set())
return false;
}
return true;
}
void Directory::UnapplyEntry(EntryKernel* entry) {
int64 handle = entry->ref(META_HANDLE);
ModelType server_type = GetModelTypeFromSpecifics(
entry->ref(SERVER_SPECIFICS));
// Clear enough so that on the next sync cycle all local data will
// be overwritten.
// Note: do not modify the root node in order to preserve the
// initial sync ended bit for this type (else on the next restart
// this type will be treated as disabled and therefore fully purged).
if (IsRealDataType(server_type) &&
ModelTypeToRootTag(server_type) == entry->ref(UNIQUE_SERVER_TAG)) {
return;
}
// Set the unapplied bit if this item has server data.
if (IsRealDataType(server_type) && !entry->ref(IS_UNAPPLIED_UPDATE)) {
entry->put(IS_UNAPPLIED_UPDATE, true);
kernel_->unapplied_update_metahandles[server_type].insert(handle);
entry->mark_dirty(&kernel_->dirty_metahandles);
}
// Unset the unsynced bit.
if (entry->ref(IS_UNSYNCED)) {
kernel_->unsynced_metahandles.erase(handle);
entry->put(IS_UNSYNCED, false);
entry->mark_dirty(&kernel_->dirty_metahandles);
}
// Mark the item as locally deleted. No deleted items are allowed in the
// parent child index.
if (!entry->ref(IS_DEL)) {
kernel_->parent_child_index.Remove(entry);
entry->put(IS_DEL, true);
entry->mark_dirty(&kernel_->dirty_metahandles);
}
// Set the version to the "newly created" version.
if (entry->ref(BASE_VERSION) != CHANGES_VERSION) {
entry->put(BASE_VERSION, CHANGES_VERSION);
entry->mark_dirty(&kernel_->dirty_metahandles);
}
// At this point locally created items that aren't synced will become locally
// deleted items, and purged on the next snapshot. All other items will match
// the state they would have had if they were just created via a server
// update. See MutableEntry::MutableEntry(.., CreateNewUpdateItem, ..).
}
void Directory::DeleteEntry(const ScopedKernelLock& lock,
bool save_to_journal,
EntryKernel* entry,
EntryKernelSet* entries_to_journal) {
int64 handle = entry->ref(META_HANDLE);
ModelType server_type = GetModelTypeFromSpecifics(
entry->ref(SERVER_SPECIFICS));
kernel_->metahandles_to_purge.insert(handle);
size_t num_erased = 0;
num_erased = kernel_->metahandles_map.erase(entry->ref(META_HANDLE));
DCHECK_EQ(1u, num_erased);
num_erased = kernel_->ids_map.erase(entry->ref(ID).value());
DCHECK_EQ(1u, num_erased);
num_erased = kernel_->unsynced_metahandles.erase(handle);
DCHECK_EQ(entry->ref(IS_UNSYNCED), num_erased > 0);
num_erased =
kernel_->unapplied_update_metahandles[server_type].erase(handle);
DCHECK_EQ(entry->ref(IS_UNAPPLIED_UPDATE), num_erased > 0);
if (kernel_->parent_child_index.Contains(entry))
kernel_->parent_child_index.Remove(entry);
if (!entry->ref(UNIQUE_CLIENT_TAG).empty()) {
num_erased =
kernel_->client_tags_map.erase(entry->ref(UNIQUE_CLIENT_TAG));
DCHECK_EQ(1u, num_erased);
}
if (!entry->ref(UNIQUE_SERVER_TAG).empty()) {
num_erased =
kernel_->server_tags_map.erase(entry->ref(UNIQUE_SERVER_TAG));
DCHECK_EQ(1u, num_erased);
}
RemoveFromAttachmentIndex(lock, handle, entry->ref(ATTACHMENT_METADATA));
if (save_to_journal) {
entries_to_journal->insert(entry);
} else {
delete entry;
}
}
bool Directory::PurgeEntriesWithTypeIn(ModelTypeSet disabled_types,
ModelTypeSet types_to_journal,
ModelTypeSet types_to_unapply) {
disabled_types.RemoveAll(ProxyTypes());
if (disabled_types.Empty())
return true;
{
WriteTransaction trans(FROM_HERE, PURGE_ENTRIES, this);
EntryKernelSet entries_to_journal;
STLElementDeleter<EntryKernelSet> journal_deleter(&entries_to_journal);
{
ScopedKernelLock lock(this);
bool found_progress = false;
for (ModelTypeSet::Iterator iter = disabled_types.First(); iter.Good();
iter.Inc()) {
if (!kernel_->persisted_info.HasEmptyDownloadProgress(iter.Get()))
found_progress = true;
}
// If none of the disabled types have progress markers, there's nothing to
// purge.
if (!found_progress)
return true;
// We iterate in two passes to avoid a bug in STLport (which is used in
// the Android build). There are some versions of that library where a
// hash_map's iterators can be invalidated when an item is erased from the
// hash_map.
// See http://sourceforge.net/p/stlport/bugs/239/.
std::set<EntryKernel*> to_purge;
for (MetahandlesMap::iterator it = kernel_->metahandles_map.begin();
it != kernel_->metahandles_map.end(); ++it) {
const sync_pb::EntitySpecifics& local_specifics =
it->second->ref(SPECIFICS);
const sync_pb::EntitySpecifics& server_specifics =
it->second->ref(SERVER_SPECIFICS);
ModelType local_type = GetModelTypeFromSpecifics(local_specifics);
ModelType server_type = GetModelTypeFromSpecifics(server_specifics);
if ((IsRealDataType(local_type) && disabled_types.Has(local_type)) ||
(IsRealDataType(server_type) && disabled_types.Has(server_type))) {
to_purge.insert(it->second);
}
}
for (std::set<EntryKernel*>::iterator it = to_purge.begin();
it != to_purge.end(); ++it) {
EntryKernel* entry = *it;
const sync_pb::EntitySpecifics& local_specifics =
(*it)->ref(SPECIFICS);
const sync_pb::EntitySpecifics& server_specifics =
(*it)->ref(SERVER_SPECIFICS);
ModelType local_type = GetModelTypeFromSpecifics(local_specifics);
ModelType server_type = GetModelTypeFromSpecifics(server_specifics);
if (types_to_unapply.Has(local_type) ||
types_to_unapply.Has(server_type)) {
UnapplyEntry(entry);
} else {
bool save_to_journal =
(types_to_journal.Has(local_type) ||
types_to_journal.Has(server_type)) &&
(delete_journal_->IsDeleteJournalEnabled(local_type) ||
delete_journal_->IsDeleteJournalEnabled(server_type));
DeleteEntry(lock, save_to_journal, entry, &entries_to_journal);
}
}
delete_journal_->AddJournalBatch(&trans, entries_to_journal);
// Ensure meta tracking for these data types reflects the purged state.
for (ModelTypeSet::Iterator it = disabled_types.First();
it.Good(); it.Inc()) {
kernel_->persisted_info.transaction_version[it.Get()] = 0;
// Don't discard progress markers or context for unapplied types.
if (!types_to_unapply.Has(it.Get())) {
kernel_->persisted_info.ResetDownloadProgress(it.Get());
kernel_->persisted_info.datatype_context[it.Get()].Clear();
}
}
kernel_->info_status = KERNEL_SHARE_INFO_DIRTY;
}
}
return true;
}
bool Directory::ResetVersionsForType(BaseWriteTransaction* trans,
ModelType type) {
if (!ProtocolTypes().Has(type))
return false;
DCHECK_NE(type, BOOKMARKS) << "Only non-hierarchical types are supported";
EntryKernel* type_root = GetEntryByServerTag(ModelTypeToRootTag(type));
if (!type_root)
return false;
ScopedKernelLock lock(this);
const Id& type_root_id = type_root->ref(ID);
Directory::Metahandles children;
AppendChildHandles(lock, type_root_id, &children);
for (Metahandles::iterator it = children.begin(); it != children.end();
++it) {
EntryKernel* entry = GetEntryByHandle(lock, *it);
if (!entry)
continue;
if (entry->ref(BASE_VERSION) > 1)
entry->put(BASE_VERSION, 1);
if (entry->ref(SERVER_VERSION) > 1)
entry->put(SERVER_VERSION, 1);
// Note that we do not unset IS_UNSYNCED or IS_UNAPPLIED_UPDATE in order
// to ensure no in-transit data is lost.
entry->mark_dirty(&kernel_->dirty_metahandles);
}
return true;
}
bool Directory::IsAttachmentLinked(
const sync_pb::AttachmentIdProto& attachment_id_proto) const {
ScopedKernelLock lock(this);
IndexByAttachmentId::const_iterator iter =
kernel_->index_by_attachment_id.find(attachment_id_proto.unique_id());
if (iter != kernel_->index_by_attachment_id.end() && !iter->second.empty()) {
return true;
}
return false;
}
void Directory::HandleSaveChangesFailure(const SaveChangesSnapshot& snapshot) {
WriteTransaction trans(FROM_HERE, HANDLE_SAVE_FAILURE, this);
ScopedKernelLock lock(this);
kernel_->info_status = KERNEL_SHARE_INFO_DIRTY;
// Because we optimistically cleared the dirty bit on the real entries when
// taking the snapshot, we must restore it on failure. Not doing this could
// cause lost data, if no other changes are made to the in-memory entries
// that would cause the dirty bit to get set again. Setting the bit ensures
// that SaveChanges will at least try again later.
for (EntryKernelSet::const_iterator i = snapshot.dirty_metas.begin();
i != snapshot.dirty_metas.end(); ++i) {
MetahandlesMap::iterator found =
kernel_->metahandles_map.find((*i)->ref(META_HANDLE));
if (found != kernel_->metahandles_map.end()) {
found->second->mark_dirty(&kernel_->dirty_metahandles);
}
}
kernel_->metahandles_to_purge.insert(snapshot.metahandles_to_purge.begin(),
snapshot.metahandles_to_purge.end());
// Restore delete journals.
delete_journal_->AddJournalBatch(&trans, snapshot.delete_journals);
delete_journal_->PurgeDeleteJournals(&trans,
snapshot.delete_journals_to_purge);
}
void Directory::GetDownloadProgress(
ModelType model_type,
sync_pb::DataTypeProgressMarker* value_out) const {
ScopedKernelLock lock(this);
return value_out->CopyFrom(
kernel_->persisted_info.download_progress[model_type]);
}
void Directory::GetDownloadProgressAsString(
ModelType model_type,
std::string* value_out) const {
ScopedKernelLock lock(this);
kernel_->persisted_info.download_progress[model_type].SerializeToString(
value_out);
}
size_t Directory::GetEntriesCount() const {
ScopedKernelLock lock(this);
return kernel_->metahandles_map.size();
}
void Directory::SetDownloadProgress(
ModelType model_type,
const sync_pb::DataTypeProgressMarker& new_progress) {
ScopedKernelLock lock(this);
kernel_->persisted_info.download_progress[model_type].CopyFrom(new_progress);
kernel_->info_status = KERNEL_SHARE_INFO_DIRTY;
}
bool Directory::HasEmptyDownloadProgress(ModelType type) const {
ScopedKernelLock lock(this);
return kernel_->persisted_info.HasEmptyDownloadProgress(type);
}
int64 Directory::GetTransactionVersion(ModelType type) const {
kernel_->transaction_mutex.AssertAcquired();
return kernel_->persisted_info.transaction_version[type];
}
void Directory::IncrementTransactionVersion(ModelType type) {
kernel_->transaction_mutex.AssertAcquired();
kernel_->persisted_info.transaction_version[type]++;
kernel_->info_status = KERNEL_SHARE_INFO_DIRTY;
}
void Directory::GetDataTypeContext(BaseTransaction* trans,
ModelType type,
sync_pb::DataTypeContext* context) const {
ScopedKernelLock lock(this);
context->CopyFrom(kernel_->persisted_info.datatype_context[type]);
}
void Directory::SetDataTypeContext(
BaseWriteTransaction* trans,
ModelType type,
const sync_pb::DataTypeContext& context) {
ScopedKernelLock lock(this);
kernel_->persisted_info.datatype_context[type].CopyFrom(context);
kernel_->info_status = KERNEL_SHARE_INFO_DIRTY;
}
// TODO(stanisc): crbug.com/438313: change these to not rely on the folders.
ModelTypeSet Directory::InitialSyncEndedTypes() {
syncable::ReadTransaction trans(FROM_HERE, this);
ModelTypeSet protocol_types = ProtocolTypes();
ModelTypeSet initial_sync_ended_types;
for (ModelTypeSet::Iterator i = protocol_types.First(); i.Good(); i.Inc()) {
if (InitialSyncEndedForType(&trans, i.Get())) {
initial_sync_ended_types.Put(i.Get());
}
}
return initial_sync_ended_types;
}
bool Directory::InitialSyncEndedForType(ModelType type) {
syncable::ReadTransaction trans(FROM_HERE, this);
return InitialSyncEndedForType(&trans, type);
}
bool Directory::InitialSyncEndedForType(
BaseTransaction* trans, ModelType type) {
// True iff the type's root node has been created.
syncable::Entry entry(trans, syncable::GET_TYPE_ROOT, type);
return entry.good();
}
string Directory::store_birthday() const {
ScopedKernelLock lock(this);
return kernel_->persisted_info.store_birthday;
}
void Directory::set_store_birthday(const string& store_birthday) {
ScopedKernelLock lock(this);
if (kernel_->persisted_info.store_birthday == store_birthday)