-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstorage.cpp
2935 lines (2610 loc) · 115 KB
/
storage.cpp
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 2022 Memgraph Ltd.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source
// License, and you may not use this file except in compliance with the Business Source License.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
#include "storage/v2/storage.hpp"
#include <algorithm>
#include <atomic>
#include <memory>
#include <mutex>
#include <variant>
#include <fstream>
#include <iostream>
#include "storage/v2/history_delta.hpp"
#include <gflags/gflags.h>
#include "io/network/endpoint.hpp"
#include "storage/v2/durability/durability.hpp"
#include "storage/v2/durability/metadata.hpp"
#include "storage/v2/durability/paths.hpp"
#include "storage/v2/durability/snapshot.hpp"
#include "storage/v2/durability/wal.hpp"
#include "storage/v2/edge_accessor.hpp"
#include "storage/v2/indices.hpp"
#include "storage/v2/mvcc.hpp"
#include "storage/v2/replication/config.hpp"
#include "storage/v2/transaction.hpp"
#include "storage/v2/vertex_accessor.hpp"
#include "utils/file.hpp"
#include "utils/logging.hpp"
#include "utils/memory_tracker.hpp"
#include "utils/message.hpp"
#include "utils/rw_lock.hpp"
#include "utils/spin_lock.hpp"
#include "utils/stat.hpp"
#include "utils/uuid.hpp"
/// REPLICATION ///
#include "storage/v2/replication/replication_client.hpp"
#include "storage/v2/replication/replication_server.hpp"
#include "storage/v2/replication/rpc.hpp"
#include "query/serialization/property_value.hpp"
#include "storage/v2/history_vertex.hpp"
namespace storage {
namespace {
enum class ObjectType : uint8_t { MAP, TEMPORAL_DATA };
} // namespace
std::vector<storage::PropertyValue> DeserializePropertyValueList(const nlohmann::json::array_t &data);
std::map<std::string, storage::PropertyValue> DeserializePropertyValueMap(const nlohmann::json::object_t &data);
storage::PropertyValue DeserializePropertyValue(const nlohmann::json &data) {
if (data.is_null()) {
return storage::PropertyValue();
}
if (data.is_boolean()) {
return storage::PropertyValue(data.get<bool>());
}
if (data.is_number_integer()) {
return storage::PropertyValue(data.get<int64_t>());
}
if (data.is_number_float()) {
return storage::PropertyValue(data.get<double>());
}
if (data.is_string()) {
return storage::PropertyValue(data.get<std::string>());
}
if (data.is_array()) {
return storage::PropertyValue(DeserializePropertyValueList(data));
}
MG_ASSERT(data.is_object(), "Unknown type found in the trigger storage");
switch (data["type"].get<ObjectType>()) {
case ObjectType::MAP:
return storage::PropertyValue(DeserializePropertyValueMap(data));
case ObjectType::TEMPORAL_DATA:
return storage::PropertyValue(storage::TemporalData{data["value"]["type"].get<storage::TemporalType>(),
data["value"]["microseconds"].get<int64_t>()});
}
}
std::vector<storage::PropertyValue> DeserializePropertyValueList(const nlohmann::json::array_t &data) {
std::vector<storage::PropertyValue> property_values;
property_values.reserve(data.size());
for (const auto &value : data) {
property_values.emplace_back(DeserializePropertyValue(value));
}
return property_values;
}
std::map<std::string, storage::PropertyValue> DeserializePropertyValueMap(const nlohmann::json::object_t &data) {
MG_ASSERT(data.at("type").get<ObjectType>() == ObjectType::MAP, "Invalid map serialization");
std::map<std::string, storage::PropertyValue> property_values;
const nlohmann::json::object_t &values = data.at("value");
for (const auto &[key, value] : values) {
property_values.emplace(key, DeserializePropertyValue(value));
}
return property_values;
}
nlohmann::json SerializePropertyValueVector(const std::vector<storage::PropertyValue> &values);
nlohmann::json SerializePropertyValueMap(const std::map<std::string, storage::PropertyValue> ¶meters);
nlohmann::json SerializePropertyValue(const storage::PropertyValue &property_value) {
using Type = storage::PropertyValue::Type;
switch (property_value.type()) {
case Type::Null:
return {};
case Type::Bool:
return property_value.ValueBool();
case Type::Int:
return property_value.ValueInt();
case Type::Double:
return property_value.ValueDouble();
case Type::String:
return property_value.ValueString();
case Type::List:
return SerializePropertyValueVector(property_value.ValueList());
case Type::Map:
return SerializePropertyValueMap(property_value.ValueMap());
case Type::TemporalData:
const auto temporal_data = property_value.ValueTemporalData();
auto data = nlohmann::json::object();
data.emplace("type", static_cast<uint64_t>(ObjectType::TEMPORAL_DATA));
data.emplace("value", nlohmann::json::object({{"type", static_cast<uint64_t>(temporal_data.type)},
{"microseconds", temporal_data.microseconds}}));
return data;
}
}
nlohmann::json SerializePropertyValueVector(const std::vector<storage::PropertyValue> &values) {
nlohmann::json array = nlohmann::json::array();
for (const auto &value : values) {
array.push_back(SerializePropertyValue(value));
}
return array;
}
nlohmann::json SerializePropertyValueMap(const std::map<std::string, storage::PropertyValue> ¶meters) {
nlohmann::json data = nlohmann::json::object();
data.emplace("type", static_cast<uint64_t>(ObjectType::MAP));
data.emplace("value", nlohmann::json::object());
for (const auto &[key, value] : parameters) {
data["value"][key] = SerializePropertyValue(value);
}
return data;
};
using OOMExceptionEnabler = utils::MemoryTracker::OutOfMemoryExceptionEnabler;
namespace {
[[maybe_unused]] constexpr uint16_t kEpochHistoryRetention = 1000;
} // namespace
auto AdvanceToVisibleVertex(utils::SkipList<Vertex>::Iterator it, utils::SkipList<Vertex>::Iterator end,
std::optional<VertexAccessor> *vertex, Transaction *tx, View view, Indices *indices,
Constraints *constraints, Config::Items config) {
while (it != end) {
*vertex = VertexAccessor::Create(&*it, tx, indices, constraints, config, view);
if (!*vertex) {
++it;
continue;
}
break;
}
return it;
}
AllVerticesIterable::Iterator::Iterator(AllVerticesIterable *self, utils::SkipList<Vertex>::Iterator it)
: self_(self),
it_(AdvanceToVisibleVertex(it, self->vertices_accessor_.end(), &self->vertex_, self->transaction_, self->view_,
self->indices_, self_->constraints_, self->config_)) {}
VertexAccessor AllVerticesIterable::Iterator::operator*() const { return *self_->vertex_; }
AllVerticesIterable::Iterator &AllVerticesIterable::Iterator::operator++() {
++it_;
it_ = AdvanceToVisibleVertex(it_, self_->vertices_accessor_.end(), &self_->vertex_, self_->transaction_, self_->view_,
self_->indices_, self_->constraints_, self_->config_);
return *this;
}
VerticesIterable::VerticesIterable(AllVerticesIterable vertices) : type_(Type::ALL) {
new (&all_vertices_) AllVerticesIterable(std::move(vertices));
}
VerticesIterable::VerticesIterable(LabelIndex::Iterable vertices) : type_(Type::BY_LABEL) {
new (&vertices_by_label_) LabelIndex::Iterable(std::move(vertices));
}
VerticesIterable::VerticesIterable(LabelPropertyIndex::Iterable vertices) : type_(Type::BY_LABEL_PROPERTY) {
new (&vertices_by_label_property_) LabelPropertyIndex::Iterable(std::move(vertices));
}
VerticesIterable::VerticesIterable(VerticesIterable &&other) noexcept : type_(other.type_) {
switch (other.type_) {
case Type::ALL:
new (&all_vertices_) AllVerticesIterable(std::move(other.all_vertices_));
break;
case Type::BY_LABEL:
new (&vertices_by_label_) LabelIndex::Iterable(std::move(other.vertices_by_label_));
break;
case Type::BY_LABEL_PROPERTY:
new (&vertices_by_label_property_) LabelPropertyIndex::Iterable(std::move(other.vertices_by_label_property_));
break;
}
}
VerticesIterable &VerticesIterable::operator=(VerticesIterable &&other) noexcept {
switch (type_) {
case Type::ALL:
all_vertices_.AllVerticesIterable::~AllVerticesIterable();
break;
case Type::BY_LABEL:
vertices_by_label_.LabelIndex::Iterable::~Iterable();
break;
case Type::BY_LABEL_PROPERTY:
vertices_by_label_property_.LabelPropertyIndex::Iterable::~Iterable();
break;
}
type_ = other.type_;
switch (other.type_) {
case Type::ALL:
new (&all_vertices_) AllVerticesIterable(std::move(other.all_vertices_));
break;
case Type::BY_LABEL:
new (&vertices_by_label_) LabelIndex::Iterable(std::move(other.vertices_by_label_));
break;
case Type::BY_LABEL_PROPERTY:
new (&vertices_by_label_property_) LabelPropertyIndex::Iterable(std::move(other.vertices_by_label_property_));
break;
}
return *this;
}
VerticesIterable::~VerticesIterable() {
switch (type_) {
case Type::ALL:
all_vertices_.AllVerticesIterable::~AllVerticesIterable();
break;
case Type::BY_LABEL:
vertices_by_label_.LabelIndex::Iterable::~Iterable();
break;
case Type::BY_LABEL_PROPERTY:
vertices_by_label_property_.LabelPropertyIndex::Iterable::~Iterable();
break;
}
}
VerticesIterable::Iterator VerticesIterable::begin() {
switch (type_) {
case Type::ALL:
return Iterator(all_vertices_.begin());
case Type::BY_LABEL:
return Iterator(vertices_by_label_.begin());
case Type::BY_LABEL_PROPERTY:
return Iterator(vertices_by_label_property_.begin());
}
}
VerticesIterable::Iterator VerticesIterable::end() {
switch (type_) {
case Type::ALL:
return Iterator(all_vertices_.end());
case Type::BY_LABEL:
return Iterator(vertices_by_label_.end());
case Type::BY_LABEL_PROPERTY:
return Iterator(vertices_by_label_property_.end());
}
}
VerticesIterable::Iterator::Iterator(AllVerticesIterable::Iterator it) : type_(Type::ALL) {
new (&all_it_) AllVerticesIterable::Iterator(std::move(it));
}
VerticesIterable::Iterator::Iterator(LabelIndex::Iterable::Iterator it) : type_(Type::BY_LABEL) {
new (&by_label_it_) LabelIndex::Iterable::Iterator(std::move(it));
}
VerticesIterable::Iterator::Iterator(LabelPropertyIndex::Iterable::Iterator it) : type_(Type::BY_LABEL_PROPERTY) {
new (&by_label_property_it_) LabelPropertyIndex::Iterable::Iterator(std::move(it));
}
VerticesIterable::Iterator::Iterator(const VerticesIterable::Iterator &other) : type_(other.type_) {
switch (other.type_) {
case Type::ALL:
new (&all_it_) AllVerticesIterable::Iterator(other.all_it_);
break;
case Type::BY_LABEL:
new (&by_label_it_) LabelIndex::Iterable::Iterator(other.by_label_it_);
break;
case Type::BY_LABEL_PROPERTY:
new (&by_label_property_it_) LabelPropertyIndex::Iterable::Iterator(other.by_label_property_it_);
break;
}
}
VerticesIterable::Iterator &VerticesIterable::Iterator::operator=(const VerticesIterable::Iterator &other) {
Destroy();
type_ = other.type_;
switch (other.type_) {
case Type::ALL:
new (&all_it_) AllVerticesIterable::Iterator(other.all_it_);
break;
case Type::BY_LABEL:
new (&by_label_it_) LabelIndex::Iterable::Iterator(other.by_label_it_);
break;
case Type::BY_LABEL_PROPERTY:
new (&by_label_property_it_) LabelPropertyIndex::Iterable::Iterator(other.by_label_property_it_);
break;
}
return *this;
}
VerticesIterable::Iterator::Iterator(VerticesIterable::Iterator &&other) noexcept : type_(other.type_) {
switch (other.type_) {
case Type::ALL:
new (&all_it_) AllVerticesIterable::Iterator(std::move(other.all_it_));
break;
case Type::BY_LABEL:
new (&by_label_it_) LabelIndex::Iterable::Iterator(std::move(other.by_label_it_));
break;
case Type::BY_LABEL_PROPERTY:
new (&by_label_property_it_) LabelPropertyIndex::Iterable::Iterator(std::move(other.by_label_property_it_));
break;
}
}
VerticesIterable::Iterator &VerticesIterable::Iterator::operator=(VerticesIterable::Iterator &&other) noexcept {
Destroy();
type_ = other.type_;
switch (other.type_) {
case Type::ALL:
new (&all_it_) AllVerticesIterable::Iterator(std::move(other.all_it_));
break;
case Type::BY_LABEL:
new (&by_label_it_) LabelIndex::Iterable::Iterator(std::move(other.by_label_it_));
break;
case Type::BY_LABEL_PROPERTY:
new (&by_label_property_it_) LabelPropertyIndex::Iterable::Iterator(std::move(other.by_label_property_it_));
break;
}
return *this;
}
VerticesIterable::Iterator::~Iterator() { Destroy(); }
void VerticesIterable::Iterator::Destroy() noexcept {
switch (type_) {
case Type::ALL:
all_it_.AllVerticesIterable::Iterator::~Iterator();
break;
case Type::BY_LABEL:
by_label_it_.LabelIndex::Iterable::Iterator::~Iterator();
break;
case Type::BY_LABEL_PROPERTY:
by_label_property_it_.LabelPropertyIndex::Iterable::Iterator::~Iterator();
break;
}
}
VertexAccessor VerticesIterable::Iterator::operator*() const {
switch (type_) {
case Type::ALL:
return *all_it_;
case Type::BY_LABEL:
return *by_label_it_;
case Type::BY_LABEL_PROPERTY:
return *by_label_property_it_;
}
}
VerticesIterable::Iterator &VerticesIterable::Iterator::operator++() {
switch (type_) {
case Type::ALL:
++all_it_;
break;
case Type::BY_LABEL:
++by_label_it_;
break;
case Type::BY_LABEL_PROPERTY:
++by_label_property_it_;
break;
}
return *this;
}
bool VerticesIterable::Iterator::operator==(const Iterator &other) const {
switch (type_) {
case Type::ALL:
return all_it_ == other.all_it_;
case Type::BY_LABEL:
return by_label_it_ == other.by_label_it_;
case Type::BY_LABEL_PROPERTY:
return by_label_property_it_ == other.by_label_property_it_;
}
}
Storage::Storage(Config config)
: indices_(&constraints_, config.items),
isolation_level_(config.transaction.isolation_level),
config_(config),
snapshot_directory_(config_.durability.storage_directory / durability::kSnapshotDirectory),
wal_directory_(config_.durability.storage_directory / durability::kWalDirectory),
lock_file_path_(config_.durability.storage_directory / durability::kLockFile),
uuid_(utils::GenerateUUID()),
epoch_id_(utils::GenerateUUID()),
global_locker_(file_retainer_.AddLocker()) {
//hjm begin
// saved_history_deltas_.init(config_.durability.storage_directory/"history_deltas");
saved_history_deltas_.emplace(config_.durability.storage_directory/"history_deltas",config_.items.realTimeFlag);
//recover kv's time_table index
// saved_history_deltas_->GetTimeTableAll(); //hjm begin timetable
//hjm end
if (config_.durability.snapshot_wal_mode != Config::Durability::SnapshotWalMode::DISABLED ||
config_.durability.snapshot_on_exit || config_.durability.recover_on_startup) {
// Create the directory initially to crash the database in case of
// permission errors. This is done early to crash the database on startup
// instead of crashing the database for the first time during runtime (which
// could be an unpleasant surprise).
utils::EnsureDirOrDie(snapshot_directory_);
// Same reasoning as above.
utils::EnsureDirOrDie(wal_directory_);
// Verify that the user that started the process is the same user that is
// the owner of the storage directory.
durability::VerifyStorageDirectoryOwnerAndProcessUserOrDie(config_.durability.storage_directory);
// Create the lock file and open a handle to it. This will crash the
// database if it can't open the file for writing or if any other process is
// holding the file opened.
lock_file_handle_.Open(lock_file_path_, utils::OutputFile::Mode::OVERWRITE_EXISTING);
MG_ASSERT(lock_file_handle_.AcquireLock(),
"Couldn't acquire lock on the storage directory {}"
"!\nAnother Memgraph process is currently running with the same "
"storage directory, please stop it first before starting this "
"process!",
config_.durability.storage_directory);
}
if (config_.durability.recover_on_startup) {
auto info = durability::RecoverData(snapshot_directory_, wal_directory_, &uuid_, &epoch_id_, &epoch_history_,
&vertices_, &edges_, &edge_count_, &name_id_mapper_, &indices_, &constraints_,
config_.items, &wal_seq_num_);
if (info) {
vertex_id_ = info->next_vertex_id;
edge_id_ = info->next_edge_id;
timestamp_ = std::max(timestamp_, info->next_timestamp);
if (info->last_commit_timestamp) {
last_commit_timestamp_ = *info->last_commit_timestamp;
}
}
} else if (config_.durability.snapshot_wal_mode != Config::Durability::SnapshotWalMode::DISABLED ||
config_.durability.snapshot_on_exit) {
bool files_moved = false;
auto backup_root = config_.durability.storage_directory / durability::kBackupDirectory;
for (const auto &[path, dirname, what] :
{std::make_tuple(snapshot_directory_, durability::kSnapshotDirectory, "snapshot"),
std::make_tuple(wal_directory_, durability::kWalDirectory, "WAL")}) {
if (!utils::DirExists(path)) continue;
auto backup_curr = backup_root / dirname;
std::error_code error_code;
for (const auto &item : std::filesystem::directory_iterator(path, error_code)) {
utils::EnsureDirOrDie(backup_root);
utils::EnsureDirOrDie(backup_curr);
std::error_code item_error_code;
std::filesystem::rename(item.path(), backup_curr / item.path().filename(), item_error_code);
MG_ASSERT(!item_error_code, "Couldn't move {} file {} because of: {}", what, item.path(),
item_error_code.message());
files_moved = true;
}
MG_ASSERT(!error_code, "Couldn't backup {} files because of: {}", what, error_code.message());
}
if (files_moved) {
spdlog::warn(
"Since Memgraph was not supposed to recover on startup and "
"durability is enabled, your current durability files will likely "
"be overridden. To prevent important data loss, Memgraph has stored "
"those files into a .backup directory inside the storage directory.");
}
}
//hjm begin rocksdb retention
if (config_.rocksdb_retention.retention_on_startup){
reclaim_rocksdb_runner_.Run("Rocksdb GC", config_.rocksdb_retention.retention_interval, [this] { this->ReclaimHistoryRentention(config_.rocksdb_retention.retention_period); });
}
//hjm end
if (config_.durability.snapshot_wal_mode != Config::Durability::SnapshotWalMode::DISABLED) {
snapshot_runner_.Run("Snapshot", config_.durability.snapshot_interval, [this] {
if (auto maybe_error = this->CreateSnapshot(); maybe_error.HasError()) {
switch (maybe_error.GetError()) {
case CreateSnapshotError::DisabledForReplica:
spdlog::warn(
utils::MessageWithLink("Snapshots are disabled for replicas.", "https://memgr.ph/replication"));
break;
}
}
});
}
if (config_.gc.type == Config::Gc::Type::PERIODIC) {
gc_runner_.Run("Storage GC", config_.gc.interval, [this] { this->CollectGarbage<false>(); });
}
if (timestamp_ == kTimestampInitialId) {
commit_log_.emplace();
} else {
commit_log_.emplace(timestamp_);
}
}
Storage::~Storage() {
if (config_.gc.type == Config::Gc::Type::PERIODIC) {
gc_runner_.Stop();
}
{
// Clear replication data
replication_server_.reset();
replication_clients_.WithLock([&](auto &clients) { clients.clear(); });
}
if (wal_file_) {
wal_file_->FinalizeWal();
wal_file_ = std::nullopt;
}
if (config_.durability.snapshot_wal_mode != Config::Durability::SnapshotWalMode::DISABLED) {
snapshot_runner_.Stop();
}
if (config_.durability.snapshot_on_exit) {
if (auto maybe_error = this->CreateSnapshot(); maybe_error.HasError()) {
switch (maybe_error.GetError()) {
case CreateSnapshotError::DisabledForReplica:
spdlog::warn(utils::MessageWithLink("Snapshots are disabled for replicas.", "https://memgr.ph/replication"));
break;
}
}
}
}
Storage::Accessor::Accessor(Storage *storage, IsolationLevel isolation_level)
: storage_(storage),
// The lock must be acquired before creating the transaction object to
// prevent freshly created transactions from dangling in an active state
// during exclusive operations.
storage_guard_(storage_->main_lock_),
transaction_(storage->CreateTransaction(isolation_level)),
is_transaction_active_(true),
config_(storage->config_.items) {}
Storage::Accessor::Accessor(Accessor &&other) noexcept
: storage_(other.storage_),
storage_guard_(std::move(other.storage_guard_)),
transaction_(std::move(other.transaction_)),
commit_timestamp_(other.commit_timestamp_),
is_transaction_active_(other.is_transaction_active_),
config_(other.config_) {
// Don't allow the other accessor to abort our transaction in destructor.
other.is_transaction_active_ = false;
other.commit_timestamp_.reset();
}
Storage::Accessor::~Accessor() {
if (is_transaction_active_) {
Abort();
}
FinalizeTransaction();
}
bool Storage::ReclaimHistoryRentention(const std::chrono::milliseconds &retention_period){
return saved_history_deltas_->RemoveOldHistory(retention_period);
}
storage::HistoryVertex Storage::Accessor::CreateHistoryVertexFromKV(const storage::HistoryVertex vertex_,nlohmann::json gid_delta_,history_delta::historyContext &historyContext_){
//properties
auto maybe_labels= vertex_.labels;
auto maybe_properties=vertex_.properties;
//deleted info
auto property_ids = PropertyId::FromUint(storage_->name_id_mapper_.NameToId("delete_info"));
auto property_values = storage::PropertyValue(gid_delta_.dump());
maybe_properties[property_ids]=property_values;
auto tt_ts=gid_delta_["TT_TS"].get<uint64_t>();
auto tt_te=gid_delta_["TT_TE"].get<uint64_t>();
//TODO edges
auto new_vertex=HistoryVertex(vertex_.gid,tt_ts,tt_te);
new_vertex.labels=maybe_labels;
new_vertex.properties=maybe_properties;
new_vertex.in_edges=vertex_.in_edges;
new_vertex.out_edges=vertex_.out_edges;
return new_vertex;
}
storage::HistoryVertex Storage::Accessor::CreateHistoryVertexFromKV(const VertexAccessor &another,nlohmann::json gid_delta_,history_delta::historyContext &historyContext_){
//properties
auto deltas=another.vertex_->delta;
auto maybe_properties=another.vertex_->properties.Properties();
auto maybe_labels=another.vertex_->labels;
//deleted info
auto property_ids = PropertyId::FromUint(storage_->name_id_mapper_.NameToId("delete_info"));
auto property_values = storage::PropertyValue(gid_delta_.dump());
maybe_properties[property_ids]=property_values;
auto tt_ts=gid_delta_["TT_TS"].get<uint64_t>();
auto tt_te=gid_delta_["TT_TE"].get<uint64_t>();
//TODO edges
auto new_vertex=HistoryVertex(another.vertex_->gid,tt_ts,tt_te);
new_vertex.labels=maybe_labels;
new_vertex.properties=maybe_properties;
//边
new_vertex.in_edges=another.vertex_->in_edges;
new_vertex.out_edges=another.vertex_->out_edges;
return new_vertex;
}
storage::HistoryVertex Storage::Accessor::CreateHistoryVertexFromDelta(const VertexAccessor &another,std::tuple< std::map<storage::PropertyId,storage::PropertyValue>,uint64_t,uint64_t> & maybe_props,history_delta::historyContext& historyContext_){
auto deltas=another.vertex_->delta;
//Current info
auto maybe_labels=another.vertex_->labels;
auto tt_ts=std::get<1>(maybe_props);
auto tt_te=std::get<2>(maybe_props);
auto maybe_properties=std::get<0>(maybe_props);
auto property_id = PropertyId::FromUint(storage_->name_id_mapper_.NameToId("transaction_ts"));
auto property_id2 = PropertyId::FromUint(storage_->name_id_mapper_.NameToId("transaction_te"));
auto property_value = storage::PropertyValue((int64_t)tt_ts);
maybe_properties[property_id]=property_value;
auto property_value2 = storage::PropertyValue((int64_t)tt_te);
maybe_properties[property_id2]=property_value2;
auto new_vertex=HistoryVertex(another.vertex_->gid,tt_ts,tt_te);
new_vertex.labels=maybe_labels;
new_vertex.properties=maybe_properties;
//edges
new_vertex.in_edges=another.vertex_->in_edges;
new_vertex.out_edges=another.vertex_->out_edges;
return new_vertex;
}
storage::HistoryEdge Storage::Accessor::CreateHistoryEdgeFromKV(const EdgeAccessor &another,nlohmann::json gid_delta_){
auto maybe_properties=another.edge_.ptr->properties.Properties();
auto from_gid=another.FromVertex().Gid();
auto to_gid=another.ToVertex().Gid();
//还原到最近的dead info
auto deltas=another.edge_.ptr->delta;
while (deltas != nullptr) {
switch (deltas->action) {
case storage::Delta::Action::SET_PROPERTY: {
auto property_value =deltas->property.value;
if(property_value.type()!=storage::PropertyValue::Type::Null) maybe_properties[deltas->property.key]=property_value;
else{
maybe_properties[deltas->property.key]=storage::PropertyValue("NULL");;
}
break;
}
default:break;
}
// Move to the next delta.
deltas = deltas->next.load(std::memory_order_acquire);
}
//TT_TS TT_TE
auto property_id = PropertyId::FromUint(storage_->name_id_mapper_.NameToId("transaction_ts"));
auto property_value = storage::PropertyValue(gid_delta_["TT_TS"].get<int64_t>());
maybe_properties[property_id]=property_value;
auto property_id2 = PropertyId::FromUint(storage_->name_id_mapper_.NameToId("transaction_te"));
auto property_value2 = storage::PropertyValue(gid_delta_["TT_TE"].get<int64_t>());
maybe_properties[property_id2]=property_value2;
auto tt_ts=gid_delta_["TT_TS"].get<uint64_t>();
auto tt_te=gid_delta_["TT_TE"].get<uint64_t>();
// std::cout<<"CreateHistoryEdgeFromKV1:"<<tt_ts<<" "<<tt_te<<" "<<from_gid.AsUint()<<" "<<to_gid.AsUint()<<" ""\n";
//TODO edges
auto history_edge=HistoryEdge(another.edge_.ptr->gid,tt_ts,tt_te,from_gid,to_gid,another.EdgeType(),nullptr);
history_edge.properties=maybe_properties;
return history_edge;
}
storage::HistoryEdge Storage::Accessor::CreateHistoryEdgeFromKV(storage::HistoryEdge edge_,nlohmann::json gid_delta_){
auto maybe_properties=edge_.properties;
//properties
// wzy begin no-edge-version
// if(gid_delta_.find("SP")!=gid_delta_.end()){
// auto history_props_=gid_delta_["SP"];
// for(auto it_iter= history_props_.begin(); it_iter != history_props_.end(); ++it_iter){
// auto key = it_iter.key();
// auto value=it_iter.value();
// auto property_id = PropertyId::FromUint(storage_->name_id_mapper_.NameToId(key));
// auto property_value = DeserializePropertyValue(value);//query::serialization::
// if(property_value.type()!=storage::PropertyValue::Type::Null) maybe_properties[property_id]=property_value;
// else{
// maybe_properties[property_id]=storage::PropertyValue("NULL");;
// }
// }
// }
// wzy end
//TT_TS TT_TE
auto property_id = PropertyId::FromUint(storage_->name_id_mapper_.NameToId("transaction_ts"));
auto property_value = storage::PropertyValue(gid_delta_["TT_TS"].get<int64_t>());
maybe_properties[property_id]=property_value;
auto property_id2 = PropertyId::FromUint(storage_->name_id_mapper_.NameToId("transaction_te"));
auto property_value2 = storage::PropertyValue(gid_delta_["TT_TE"].get<int64_t>());
maybe_properties[property_id2]=property_value2;
auto tt_ts=gid_delta_["TT_TS"].get<uint64_t>();
auto tt_te=gid_delta_["TT_TE"].get<uint64_t>();
// std::cout<<"CreateHistoryEdgeFromKV2:"<<tt_ts<<" "<<tt_te<<" "<<edge_.from_gid.AsUint()<<" "<<edge_.to_gid.AsUint()<<"\n";
//TODO edges
auto history_edge=HistoryEdge(edge_.gid,tt_ts,tt_te,edge_.from_gid,edge_.to_gid,edge_.type,nullptr);
history_edge.properties=maybe_properties;
return history_edge;
}
Result<std::vector<EdgeAccessor>> Storage::Accessor::Edges(std::vector<std::tuple<EdgeTypeId, Vertex *, EdgeRef>> &edges_,const std::vector<EdgeTypeId> &edge_types,storage::Gid gid,bool from,std::optional<storage::Gid> existing_gid){
std::vector<std::tuple<EdgeTypeId, Vertex *, EdgeRef>> edges;
{
if (edge_types.empty() & !existing_gid) {
edges = edges_;
} else {
for (const auto &item : edges_) {
const auto &[edge_type, expand_vertex, edge] = item;
if (existing_gid && expand_vertex->gid != *existing_gid) continue;
if (!edge_types.empty() && std::find(edge_types.begin(), edge_types.end(), edge_type) == edge_types.end())
continue;
edges.push_back(item);
}
}
}
std::vector<EdgeAccessor> ret;
ret.reserve(edges.size());
for (const auto &item : edges) {
const auto &[edge_type, expand_vertex, edge] = item;
storage::Gid from_gid=from?expand_vertex->gid:gid;
storage::Gid to_gid=from?gid:expand_vertex->gid;
ret.emplace_back(edge, edge_type, expand_vertex,expand_vertex, &transaction_, &storage_->indices_,
&storage_->constraints_, from_gid,to_gid,config_);
}
return std::move(ret);
}
std::optional<VertexAccessor> Storage::Accessor::FindDeleteVertex(Gid gid, View view){
auto acc = storage_->vertices_.access();
auto it = acc.find(gid);
if (it == acc.end()) return std::nullopt;
return VertexAccessor::Creates(&*it, &transaction_, &storage_->indices_, &storage_->constraints_, config_, view);
}
Gid Storage::Accessor::IdToGid(const uint64_t key) { return Gid::FromUint(key); }
VertexAccessor Storage::Accessor::CreateVertex() {
OOMExceptionEnabler oom_exception;
auto gid = storage_->vertex_id_.fetch_add(1, std::memory_order_acq_rel);
auto acc = storage_->vertices_.access();
auto delta = CreateDeleteObjectDelta(&transaction_);
auto [it, inserted] = acc.insert(Vertex{storage::Gid::FromUint(gid), delta});
MG_ASSERT(inserted, "The vertex must be inserted here!");
MG_ASSERT(it != acc.end(), "Invalid Vertex accessor!");
delta->prev.Set(&*it);
return VertexAccessor(&*it, &transaction_, &storage_->indices_, &storage_->constraints_, config_);
}
VertexAccessor Storage::Accessor::CreateVertex(storage::Gid gid) {
OOMExceptionEnabler oom_exception;
// NOTE: When we update the next `vertex_id_` here we perform a RMW
// (read-modify-write) operation that ISN'T atomic! But, that isn't an issue
// because this function is only called from the replication delta applier
// that runs single-threadedly and while this instance is set-up to apply
// threads (it is the replica), it is guaranteed that no other writes are
// possible.
storage_->vertex_id_.store(std::max(storage_->vertex_id_.load(std::memory_order_acquire), gid.AsUint() + 1),
std::memory_order_release);
auto acc = storage_->vertices_.access();
auto delta = CreateDeleteObjectDelta(&transaction_);
auto [it, inserted] = acc.insert(Vertex{gid, delta});
MG_ASSERT(inserted, "The vertex must be inserted here!");
MG_ASSERT(it != acc.end(), "Invalid Vertex accessor!");
delta->prev.Set(&*it);
return VertexAccessor(&*it, &transaction_, &storage_->indices_, &storage_->constraints_, config_);
}
std::optional<VertexAccessor> Storage::Accessor::FindVertex(Gid gid, View view) {
auto acc = storage_->vertices_.access();
auto it = acc.find(gid);
if (it == acc.end()) return std::nullopt;
return VertexAccessor::Create(&*it, &transaction_, &storage_->indices_, &storage_->constraints_, config_, view);
}
Result<std::optional<VertexAccessor>> Storage::Accessor::DeleteVertex(VertexAccessor *vertex) {
MG_ASSERT(vertex->transaction_ == &transaction_,
"VertexAccessor must be from the same transaction as the storage "
"accessor when deleting a vertex!");
auto *vertex_ptr = vertex->vertex_;
std::lock_guard<utils::SpinLock> guard(vertex_ptr->lock);
if (!PrepareForWrite(&transaction_, vertex_ptr)) return Error::SERIALIZATION_ERROR;
if (vertex_ptr->deleted) {
return std::optional<VertexAccessor>{};
}
if (!vertex_ptr->in_edges.empty() || !vertex_ptr->out_edges.empty()) return Error::VERTEX_HAS_EDGES;
//hjm begin set transaction st
auto ts=vertex_ptr->transaction_st;
auto before_delta=vertex_ptr->delta;
while (before_delta != nullptr){
bool delta_is_edge=false;
switch (before_delta->action) {
case storage::Delta::Action::ADD_OUT_EDGE:
case storage::Delta::Action::REMOVE_OUT_EDGE:
case storage::Delta::Action::ADD_IN_EDGE:
case storage::Delta::Action::REMOVE_IN_EDGE:{
delta_is_edge=true;
break;
}
default:break;
}
if(delta_is_edge){
before_delta = before_delta->next.load(std::memory_order_acquire);
continue;
}
ts = before_delta->timestamp->load(std::memory_order_acquire);
if(ts >= kTransactionInitialId){
if(ts==transaction_.transaction_id){//ts >= kTransactionInitialId &
ts=before_delta->transaction_st;
}else{
std::cout<<"SERIALIZATION_ERROR"<<ts<<" "<<transaction_.transaction_id<<"\n";
return Error::SERIALIZATION_ERROR;
}
}
break;
}
//hjm end
auto delta=CreateAndLinkDelta(&transaction_, vertex_ptr, Delta::RecreateObjectTag());
vertex_ptr->deleted = true;
//hjm begin
delta->transaction_st=ts;
//save vertex to restore
nlohmann::json data = nlohmann::json::object();
//labels
auto maybe_labels = vertex_ptr->labels;
auto add_labels=std::vector<std::pair<std::string,std::string>>();
for (const auto &label : maybe_labels) {
add_labels.emplace_back("AL",storage_->name_id_mapper_.IdToName(label.AsUint()));//name_id_mapper_.IdToName(label.AsUint())
}
data["L"] =add_labels;
//properties
auto maybe_properties = vertex_ptr->properties.Properties();;
nlohmann::json data2 = nlohmann::json::object();
for (const auto &prop : maybe_properties) {
auto property_name = storage_->name_id_mapper_.IdToName(prop.first.AsUint());//delta.property.key.AsUint();//
auto property_value = SerializePropertyValue(prop.second);//query::serialization::
data2[property_name] = property_value;
}
data["SP"]=data2;
delta->add_info=data;
if(prinfFlag){
auto print=prinfVertex(vertex_ptr->gid.AsUint(),ts,maybe_properties,maybe_labels);
transaction_.prinfVertex_.emplace_back(print);
}
//hjm end
return std::make_optional<VertexAccessor>(vertex_ptr, &transaction_, &storage_->indices_, &storage_->constraints_,
config_, true);
}
Result<std::optional<std::pair<VertexAccessor, std::vector<EdgeAccessor>>>> Storage::Accessor::DetachDeleteVertex(
VertexAccessor *vertex) {
using ReturnType = std::pair<VertexAccessor, std::vector<EdgeAccessor>>;
MG_ASSERT(vertex->transaction_ == &transaction_,
"VertexAccessor must be from the same transaction as the storage "
"accessor when deleting a vertex!");
auto *vertex_ptr = vertex->vertex_;
std::vector<std::tuple<EdgeTypeId, Vertex *, EdgeRef>> in_edges;
std::vector<std::tuple<EdgeTypeId, Vertex *, EdgeRef>> out_edges;
{
std::lock_guard<utils::SpinLock> guard(vertex_ptr->lock);
if (!PrepareForWrite(&transaction_, vertex_ptr)) return Error::SERIALIZATION_ERROR;
if (vertex_ptr->deleted) return std::optional<ReturnType>{};
in_edges = vertex_ptr->in_edges;
out_edges = vertex_ptr->out_edges;
}
std::vector<EdgeAccessor> deleted_edges;
for (const auto &item : in_edges) {
auto [edge_type, from_vertex, edge] = item;
EdgeAccessor e(edge, edge_type, from_vertex, vertex_ptr, &transaction_, &storage_->indices_,
&storage_->constraints_, config_);
auto ret = DeleteEdge(&e);
if (ret.HasError()) {
MG_ASSERT(ret.GetError() == Error::SERIALIZATION_ERROR, "Invalid database state!");
return ret.GetError();
}
if (ret.GetValue()) {
deleted_edges.push_back(*ret.GetValue());
}
}
for (const auto &item : out_edges) {
auto [edge_type, to_vertex, edge] = item;
EdgeAccessor e(edge, edge_type, vertex_ptr, to_vertex, &transaction_, &storage_->indices_, &storage_->constraints_,
config_);
auto ret = DeleteEdge(&e);
if (ret.HasError()) {
MG_ASSERT(ret.GetError() == Error::SERIALIZATION_ERROR, "Invalid database state!");
return ret.GetError();
}
if (ret.GetValue()) {
deleted_edges.push_back(*ret.GetValue());
}
}
std::lock_guard<utils::SpinLock> guard(vertex_ptr->lock);
// We need to check again for serialization errors because we unlocked the
// vertex. Some other transaction could have modified the vertex in the
// meantime if we didn't have any edges to delete.
if (!PrepareForWrite(&transaction_, vertex_ptr)) return Error::SERIALIZATION_ERROR;
MG_ASSERT(!vertex_ptr->deleted, "Invalid database state!");
auto ts=vertex_ptr->transaction_st;
auto before_delta=vertex_ptr->delta;
while (before_delta != nullptr){
bool delta_is_edge=false;
switch (before_delta->action) {
case storage::Delta::Action::ADD_OUT_EDGE:
case storage::Delta::Action::REMOVE_OUT_EDGE:
case storage::Delta::Action::ADD_IN_EDGE:
case storage::Delta::Action::REMOVE_IN_EDGE:{
delta_is_edge=true;
break;
}
default:break;
}
if(delta_is_edge){
before_delta = before_delta->next.load(std::memory_order_acquire);
continue;
}
ts = before_delta->timestamp->load(std::memory_order_acquire);
if(ts >= kTransactionInitialId){
if(ts==transaction_.transaction_id){//ts >= kTransactionInitialId &
ts=before_delta->transaction_st;
}else{
return Error::SERIALIZATION_ERROR;
}
}
break;
}
auto delta=CreateAndLinkDelta(&transaction_, vertex_ptr, Delta::RecreateObjectTag());
vertex_ptr->deleted = true;