This repository was archived by the owner on Nov 6, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathstorage2.cpp
More file actions
1724 lines (1588 loc) · 67.9 KB
/
storage2.cpp
File metadata and controls
1724 lines (1588 loc) · 67.9 KB
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 (c) 2013 Eugene Lazin <4lazin@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "storage2.h"
#include "util.h"
#include "queryprocessor.h"
#include "query_processing/queryparser.h"
#include "query_processing/queryplan.h"
#include "log_iface.h"
#include "status_util.h"
#include "datetime.h"
#include "akumuli_version.h"
#include <algorithm>
#include <atomic>
#include <sstream>
#include <cassert>
#include <functional>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread/barrier.hpp>
#include "fcntl_compat.h"
#include <cstdlib>
#if defined(__APPLE__)
#include <stack>
#endif
namespace Akumuli {
// Utility functions & classes //
// Standalone functions //
/** This function creates metadata file - root of the storage system.
* This page contains creation date and time, number of pages,
* all the page file names and they order.
* @return APR_EINIT on DB error.
*/
static apr_status_t create_metadata_page(const char* db_name
, const char* file_name
, std::vector<std::string> const& page_file_names
, std::vector<u32> const& capacities
, const char* bstore_type )
{
using namespace std;
try {
auto storage = std::make_shared<MetadataStorage>(file_name);
auto now = apr_time_now();
char date_time[0x100];
apr_rfc822_date(date_time, now);
storage->init_config(db_name, date_time, bstore_type);
std::vector<MetadataStorage::VolumeDesc> desc;
u32 ix = 0;
for(auto str: page_file_names) {
MetadataStorage::VolumeDesc volume;
volume.path = str;
volume.generation = ix;
volume.capacity = capacities[ix];
volume.id = ix;
volume.nblocks = 0;
volume.version = AKUMULI_VERSION;
desc.push_back(volume);
ix++;
}
storage->init_volumes(desc);
} catch (std::exception const& err) {
std::stringstream fmt;
fmt << "Can't create metadata file " << file_name << ", the error is: " << err.what();
Logger::msg(AKU_LOG_ERROR, fmt.str().c_str());
return APR_EGENERAL;
}
return APR_SUCCESS;
}
//--------- StorageSession ----------
static InputLog* get_input_log(ShardedInputLog* log) {
static size_t s_known_hashes[AKU_MAX_THREADS];
static std::atomic<int> s_hash_counter = {0};
if (log != nullptr) {
std::hash<std::thread::id> thash;
size_t hash = thash(std::this_thread::get_id());
// Check if the hash was seen previously
int nhashes = s_hash_counter.load();
for (int i = 0; i < nhashes; i++) {
if (s_known_hashes[i] == hash) {
return &log->get_shard(i);
}
}
// Insert new value
int ixnew = s_hash_counter++;
s_known_hashes[ixnew] = hash;
return &log->get_shard(ixnew);
}
return nullptr;
}
StorageSession::StorageSession(std::shared_ptr<Storage> storage,
std::shared_ptr<StorageEngine::CStoreSession> session,
ShardedInputLog* log)
: storage_(storage)
, session_(session)
, matcher_substitute_(nullptr)
, slog_(log)
, ilog_(nullptr)
{
}
StorageSession::~StorageSession() {
Logger::msg(AKU_LOG_TRACE, "StorageSession is being closed");
if (ilog_) {
std::vector<u64> staleids;
auto res = ilog_->flush(&staleids);
if (res == AKU_EOVERFLOW) {
Logger::msg(AKU_LOG_TRACE, "StorageSession input log overflow, " +
std::to_string(staleids.size()) +
" stale ids is about to be closed");
storage_->close_specific_columns(staleids);
}
}
}
aku_Status StorageSession::write(aku_Sample const& sample) {
using namespace StorageEngine;
std::vector<u64> rpoints;
auto status = session_->write(sample, &rpoints);
switch (status) {
case NBTreeAppendResult::OK:
break;
case NBTreeAppendResult::OK_FLUSH_NEEDED:
if (slog_ != nullptr) {
if (ilog_ == nullptr) {
ilog_ = get_input_log(slog_);
}
// Copy rpoints here because it will be needed later to add new entry
// into the input-log.
auto rpoints_copy = rpoints;
storage_-> _update_rescue_points(sample.paramid, std::move(rpoints_copy));
} else {
storage_-> _update_rescue_points(sample.paramid, std::move(rpoints));
}
break;
case NBTreeAppendResult::FAIL_BAD_ID:
Logger::msg(AKU_LOG_ERROR, "Invalid session cache, id = " + std::to_string(sample.paramid));
return AKU_ENOT_FOUND;
case NBTreeAppendResult::FAIL_LATE_WRITE:
return AKU_ELATE_WRITE;
case NBTreeAppendResult::FAIL_BAD_VALUE:
return AKU_EBAD_ARG;
};
if (slog_ != nullptr) {
if (ilog_ == nullptr) {
ilog_ = get_input_log(slog_);
}
std::vector<u64> staleids;
auto res = ilog_->append(sample.paramid, sample.timestamp, sample.payload.float64, &staleids);
if (res == AKU_EOVERFLOW) {
if (!staleids.empty()) {
std::promise<void> barrier;
std::future<void> future = barrier.get_future();
storage_->add_metadata_sync_barrier(std::move(barrier));
storage_->close_specific_columns(staleids);
staleids.clear();
future.wait();
}
ilog_->rotate();
}
if (status == NBTreeAppendResult::OK_FLUSH_NEEDED) {
auto res = ilog_->append(sample.paramid, rpoints.data(), static_cast<u32>(rpoints.size()), &staleids);
if (res == AKU_EOVERFLOW) {
if (!staleids.empty()) {
std::promise<void> barrier;
std::future<void> future = barrier.get_future();
storage_->add_metadata_sync_barrier(std::move(barrier));
storage_->close_specific_columns(staleids);
future.wait();
}
ilog_->rotate();
}
}
}
return AKU_SUCCESS;
}
aku_Status StorageSession::init_series_id(const char* begin, const char* end, aku_Sample *sample) {
// Series name normalization procedure. Most likeley a bottleneck but
// can be easily parallelized.
const char* ksbegin = nullptr;
const char* ksend = nullptr;
char buf[AKU_LIMITS_MAX_SNAME];
char* ob = static_cast<char*>(buf);
char* oe = static_cast<char*>(buf) + AKU_LIMITS_MAX_SNAME;
aku_Status status = SeriesParser::to_canonical_form(begin, end, ob, oe, &ksbegin, &ksend);
if (status != AKU_SUCCESS) {
return status;
}
// Match series name locally (on success use local information)
// Otherwise - match using global registry. On success - add global information to
// the local matcher. On error - add series name to global registry and then to
// the local matcher.
u64 id = local_matcher_.match(ob, ksend);
if (!id) {
// go to global registery
bool create_new = false;
std::tie(status, create_new) = storage_->init_series_id(ob, ksend, sample, &local_matcher_);
if (status != AKU_SUCCESS) {
return status;
}
if (create_new) {
// Add record to input log
if (slog_ != nullptr) {
if (ilog_ == nullptr) {
ilog_ = get_input_log(slog_);
}
std::vector<aku_ParamId> staleids;
auto res = ilog_->append(sample->paramid, ob, static_cast<u32>(ksend - ob), &staleids);
if (res == AKU_EOVERFLOW) {
if (!staleids.empty()) {
std::promise<void> barrier;
std::future<void> future = barrier.get_future();
storage_->add_metadata_sync_barrier(std::move(barrier));
storage_->close_specific_columns(staleids);
future.wait();
}
ilog_->rotate();
}
}
}
} else {
// initialize using local info
sample->paramid = id;
}
return status;
}
int StorageSession::get_series_ids(const char* begin, const char* end, aku_ParamId* ids, size_t ids_size) {
// Series name normalization procedure. Most likeley a bottleneck but
// can be easily parallelized.
const char* ksbegin = nullptr;
const char* ksend = nullptr;
char buf[AKU_LIMITS_MAX_SNAME];
char* ob = static_cast<char*>(buf);
char* oe = static_cast<char*>(buf) + AKU_LIMITS_MAX_SNAME;
aku_Status status = SeriesParser::to_canonical_form(begin, end, ob, oe, &ksbegin, &ksend);
if (status != AKU_SUCCESS) {
return -1*status;
}
// String in buf should contain normal metric "cpu.user" or compound metric like
// "cpu.user|cpu.system". The later means that we should find ids for two series:
// "cpu.user ..." and "cpu.system ..." (tags should be the same in both cases).
// At first we should determain numer of metrics.
long nmetric = std::count(const_cast<const char*>(ob), ksbegin, '|') + 1;
if (nmetric > static_cast<int>(ids_size)) {
return -1*AKU_EBAD_ARG;
}
if (nmetric == 1) {
// Match series name locally (on success use local information)
// Otherwise - match using global registry. On success - add global information to
// the local matcher. On error - add series name to global registry and then to
// the local matcher.
u64 id = local_matcher_.match(ob, ksend);
if (!id) {
// go to global registery
aku_Sample sample;
bool new_name = false;
std::tie(status, new_name) = storage_->init_series_id(ob, ksend, &sample, &local_matcher_);
ids[0] = sample.paramid;
if (new_name) {
// Add record to input log
if (slog_ != nullptr) {
if (ilog_ == nullptr) {
ilog_ = get_input_log(slog_);
}
std::vector<aku_ParamId> staleids;
auto res = ilog_->append(ids[0], ob, static_cast<u32>(ksend - ob), &staleids);
if (res == AKU_EOVERFLOW) {
if (!staleids.empty()) {
std::promise<void> barrier;
std::future<void> future = barrier.get_future();
storage_->add_metadata_sync_barrier(std::move(barrier));
storage_->close_specific_columns(staleids);
future.wait();
}
ilog_->rotate();
}
}
}
} else {
// initialize using local info
ids[0] = id;
}
} else {
char series[AKU_LIMITS_MAX_SNAME];
// Copy tags without metrics to the end of the `series` array
int tagline_len = static_cast<int>(ksend - ksbegin + 1); // +1 for space, cast is safe because ksend-ksbegin < AKU_LIMITS_MAX_SNAME
const char* metric_end = ksbegin - 1; // -1 for space
char* tagline = series + AKU_LIMITS_MAX_SNAME - tagline_len;
// TODO: remove
if (tagline_len < 0) {
AKU_PANIC("Invalid tagline length");
}
// end
memcpy(tagline, metric_end, static_cast<size_t>(tagline_len));
char* send = series + AKU_LIMITS_MAX_SNAME;
const char* it_begin = ob;
const char* it_end = ob;
for (int i = 0; i < nmetric; i++) {
// copy i'th metric to the `series` array
while(*it_end != '|' && it_end < metric_end) {
it_end++;
}
// Copy metric name to `series` array
auto metric_len = it_end - it_begin;
char* sbegin = tagline - metric_len;
// TODO: remove
if (metric_len < 0) {
AKU_PANIC("Invalid metric length");
}
// end
memcpy(sbegin, it_begin, static_cast<size_t>(metric_len));
// Move to next metric (if any)
it_end++;
it_begin = it_end;
// Match series name locally (on success use local information)
// Otherwise - match using global registry. On success - add global information to
// the local matcher. On error - add series name to global registry and then to
// the local matcher.
u64 id = local_matcher_.match(sbegin, send);
if (!id) {
// go to global registery
aku_Sample tmp;
bool newname;
std::tie(status, newname) = storage_->init_series_id(sbegin, send, &tmp, &local_matcher_);
ids[i] = tmp.paramid;
if (newname) {
// Add record to input log
if (slog_ != nullptr) {
if (ilog_ == nullptr) {
ilog_ = get_input_log(slog_);
}
std::vector<aku_ParamId> staleids;
auto res = ilog_->append(ids[i], sbegin, static_cast<u32>(send - sbegin), &staleids);
if (res == AKU_EOVERFLOW) {
if (!staleids.empty()) {
std::promise<void> barrier;
std::future<void> future = barrier.get_future();
storage_->add_metadata_sync_barrier(std::move(barrier));
storage_->close_specific_columns(staleids);
future.wait();
}
ilog_->rotate();
}
}
}
} else {
// initialize using local info
ids[i] = id;
}
}
}
return static_cast<int>(nmetric);
}
int StorageSession::get_series_name(aku_ParamId id, char* buffer, size_t buffer_size) {
StringT name;
if (matcher_substitute_) {
// Use temporary matcher
name = matcher_substitute_->id2str(id);
if (name.first == nullptr) {
// no such id, user error
return 0;
}
} else {
name = local_matcher_.id2str(id);
if (name.first == nullptr) {
// not yet cached!
return storage_->get_series_name(id, buffer, buffer_size, &local_matcher_);
}
}
memcpy(buffer, name.first, static_cast<size_t>(name.second));
return static_cast<int>(name.second);
}
void StorageSession::query(InternalCursor* cur, const char* query) const {
storage_->query(this, cur, query);
}
void StorageSession::suggest(InternalCursor* cur, const char* query) const {
storage_->suggest(this, cur, query);
}
void StorageSession::search(InternalCursor* cur, const char* query) const {
storage_->search(this, cur, query);
}
void StorageSession::set_series_matcher(std::shared_ptr<PlainSeriesMatcher> matcher) const {
matcher_substitute_ = matcher;
}
void StorageSession::clear_series_matcher() const {
matcher_substitute_ = nullptr;
}
//----------- Storage ----------
Storage::Storage()
: done_{0}
, close_barrier_(2)
{
//! In-memory SQLite database
metadata_.reset(new MetadataStorage(":memory:"));
bstore_ = StorageEngine::BlockStoreBuilder::create_memstore();
cstore_ = std::make_shared<StorageEngine::ColumnStore>(bstore_);
start_sync_worker();
}
Storage::Storage(const char* path, const aku_FineTuneParams ¶ms)
: done_{0}
, close_barrier_(2)
{
metadata_.reset(new MetadataStorage(path));
std::vector<std::string> volpaths;
// first volume is a metavolume
auto volumes = metadata_->get_volumes();
for (auto vol: volumes) {
volpaths.push_back(vol.path);
}
std::string bstore_type = "FixedSizeFileStorage";
std::string db_name = "db";
metadata_->get_config_param("blockstore_type", &bstore_type);
metadata_->get_config_param("db_name", &db_name);
if (bstore_type == "FixedSizeFileStorage") {
Logger::msg(AKU_LOG_INFO, "Open as fxied size storage");
bstore_ = StorageEngine::FixedSizeFileStorage::open(metadata_);
} else if (bstore_type == "ExpandableFileStorage") {
Logger::msg(AKU_LOG_INFO, "Open as expandable storage");
bstore_ = StorageEngine::ExpandableFileStorage::open(metadata_);
} else {
Logger::msg(AKU_LOG_ERROR, "Unknown blockstore type (" + bstore_type + ")");
AKU_PANIC("Unknown blockstore type (" + bstore_type + ")");
}
cstore_ = std::make_shared<StorageEngine::ColumnStore>(bstore_);
// Update series matcher
boost::optional<i64> baseline = metadata_->get_prev_largest_id();
if (baseline) {
global_matcher_.series_id = baseline.get() + 1;
}
auto status = metadata_->load_matcher_data(global_matcher_);
if (status != AKU_SUCCESS) {
Logger::msg(AKU_LOG_ERROR, "Can't read series names");
AKU_PANIC("Can't read series names");
}
// Update column store
std::unordered_map<aku_ParamId, std::vector<StorageEngine::LogicAddr>> mapping;
status = metadata_->load_rescue_points(mapping);
if (status != AKU_SUCCESS) {
Logger::msg(AKU_LOG_ERROR, "Can't read rescue points");
AKU_PANIC("Can't read rescue points");
}
// There are two possible configurations 1) WAL is disabled 2) WAL is enabled
// If WAL is disabled, Akumuli should work as usual. This means that we have
// to call 'force_init' for every tree. This will use maximum amount of memory
// but will increase performance in many cases, because we wan't need to read
// anything from disk before writing. In this mode every nbtree instance is
// always loaded into memory.
// If WAL is enabled we don't need to call 'force_init' because in this case
// every nbtree instance is not loaded into memory until something have to be
// written into it. In this case it gets loaded into memory. When the data that
// belongs to this nbtee instance gets evicted from WAL we will have to close
// the tree (and write it's content to disk). It can slow down things a bit
// but the data will be safe.
run_recovery(params, &mapping);
start_sync_worker();
}
void Storage::run_recovery(const aku_FineTuneParams ¶ms,
std::unordered_map<aku_ParamId, std::vector<StorageEngine::LogicAddr>>* mapping)
{
bool run_wal_recovery = false;
int ccr = 0;
if (params.input_log_path) {
aku_Status status;
std::tie(status, ccr) = ShardedInputLog::find_logs(params.input_log_path);
if (status == AKU_SUCCESS && ccr > 0) {
run_wal_recovery = true;
}
}
// Run metadata replay followed by the restore procedure (based on recovered
// metdata) followed by full log replay.
std::vector<aku_ParamId> new_ids;
if (run_wal_recovery) {
auto ilog = std::make_shared<ShardedInputLog>(ccr, params.input_log_path);
run_inputlog_metadata_recovery(ilog.get(), &new_ids, mapping);
}
aku_Status restore_status;
std::vector<aku_ParamId> restored_ids;
std::tie(restore_status, restored_ids) = cstore_->open_or_restore(*mapping, params.input_log_path == nullptr);
std::copy(new_ids.begin(), new_ids.end(), std::back_inserter(restored_ids));
if (run_wal_recovery) {
auto ilog = std::make_shared<ShardedInputLog>(ccr, params.input_log_path);
run_inputlog_recovery(ilog.get(), restored_ids);
// This step will delete log files
}
}
void Storage::initialize_input_log(const aku_FineTuneParams ¶ms) {
if (params.input_log_path) {
Logger::msg(AKU_LOG_INFO, std::string("WAL enabled, path: ") +
params.input_log_path + ", nvolumes: " +
std::to_string(params.input_log_volume_numb) + ", volume-size: " +
std::to_string(params.input_log_volume_size));
inputlog_.reset(new ShardedInputLog(static_cast<int>(params.input_log_concurrency),
params.input_log_path,
params.input_log_volume_numb,
params.input_log_volume_size));
input_log_path_ = params.input_log_path;
}
}
void Storage::run_inputlog_metadata_recovery(
ShardedInputLog* ilog,
std::vector<aku_ParamId>* restored_ids,
std::unordered_map<aku_ParamId, std::vector<StorageEngine::LogicAddr>>* mapping)
{
struct Visitor : boost::static_visitor<bool> {
Storage* storage;
aku_ParamId curr_id;
std::unordered_map<aku_ParamId, std::vector<StorageEngine::LogicAddr>>* mapping;
StorageEngine::LogicAddr top_addr;
std::vector<aku_ParamId>* restored_ids;
/** Should be called for each input-log record
* before using as a visitor
*/
void reset(aku_ParamId id) {
curr_id = id;
}
bool operator () (const InputLogDataPoint&) {
// Datapoints are ignored at this stage of the recovery.
return true;
}
bool operator () (const InputLogSeriesName& sname) {
auto strref = storage->global_matcher_.id2str(curr_id);
if (strref.second) {
// Fast path, name already added
return true;
}
bool create_new = false;
auto begin = sname.value.data();
auto end = begin + sname.value.length();
auto id = storage->global_matcher_.match(begin, end);
if (id == 0) {
// create new series
id = curr_id;
StringT prev = storage->global_matcher_.id2str(id);
if (prev.second != 0) {
// sample.paramid maps to some other series
Logger::msg(AKU_LOG_ERROR, "Series id conflict. Id " + std::to_string(id) + " is already taken by "
+ std::string(prev.first, prev.first + prev.second) + ". Series name "
+ sname.value + " is skipped.");
return true;
}
storage->global_matcher_._add(sname.value, id);
storage->metadata_->add_rescue_point(id, std::vector<u64>());
create_new = true;
}
if (create_new) {
// id guaranteed to be unique
Logger::msg(AKU_LOG_TRACE, "WAL-recovery create new column based on series name " + sname.value);
storage->cstore_->create_new_column(id);
restored_ids->push_back(id);
}
return true;
}
bool operator () (const InputLogRecoveryInfo& rinfo) {
// Check that series exists
auto strref = storage->global_matcher_.id2str(curr_id);
if (!strref.second) {
// Id is not taken
Logger::msg(AKU_LOG_ERROR, "Series id is not taken. Id " + std::to_string(curr_id) + ", recovery record will be skipped.");
return true;
}
std::vector<StorageEngine::LogicAddr> rpoints(rinfo.data);
auto it = mapping->find(curr_id);
if (it != mapping->end()) {
// Check if rescue points are of newer version.
// If *it is newer than rinfo.data then return. Otherwise,
// update rescue points list using rinfo.data.
const std::vector<StorageEngine::LogicAddr> ¤t = it->second;
if (rinfo.data.empty()) {
return true;
}
if (!current.empty()) {
if (current.size() > rinfo.data.size()) {
return true;
}
auto curr_max = std::max_element(current.begin(), current.end());
auto data_max = std::max_element(rinfo.data.begin(), rinfo.data.end());
if (*data_max >= top_addr || *curr_max > *data_max) {
return true;
}
}
}
(*mapping)[curr_id] = rpoints;
storage->_update_rescue_points(curr_id, std::move(rpoints));
return true;
}
};
Visitor visitor;
visitor.storage = this;
visitor.mapping = mapping;
visitor.top_addr = bstore_->get_top_address();
visitor.restored_ids = restored_ids;
bool proceed = true;
size_t nitems = 0x1000;
u64 nsegments = 0;
std::vector<InputLogRow> rows(nitems);
Logger::msg(AKU_LOG_INFO, "WAL metadata recovery started");
while (proceed) {
aku_Status status;
u32 outsize;
std::tie(status, outsize) = ilog->read_next(nitems, rows.data());
if (status == AKU_SUCCESS || (status == AKU_ENO_DATA && outsize > 0)) {
for (u32 ix = 0; ix < outsize; ix++) {
const InputLogRow& row = rows.at(ix);
visitor.reset(row.id);
proceed = row.payload.apply_visitor(visitor);
}
nsegments++;
}
else if (status == AKU_ENO_DATA) {
Logger::msg(AKU_LOG_INFO, "WAL metadata recovery completed");
Logger::msg(AKU_LOG_INFO, std::to_string(nsegments) + " segments scanned");
proceed = false;
}
else {
Logger::msg(AKU_LOG_ERROR, "WAL recovery error: " + StatusUtil::str(status));
proceed = false;
}
}
ilog->reopen();
}
void Storage::run_inputlog_recovery(ShardedInputLog* ilog, std::vector<aku_ParamId> ids2restore) {
struct Visitor : boost::static_visitor<bool> {
Storage* storage;
aku_Sample sample;
std::unordered_set<aku_ParamId> updated_ids;
u64 nsamples = 0;
u64 nlost = 0;
/** Should be called for each input-log record
* before using as a visitor
*/
void reset(aku_ParamId id) {
sample = {};
sample.paramid = id;
}
bool operator () (const InputLogDataPoint& point) {
sample.timestamp = point.timestamp;
sample.payload.float64 = point.value;
sample.payload.size = sizeof(aku_Sample);
sample.payload.type = AKU_PAYLOAD_FLOAT;
auto result = storage->cstore_->recovery_write(sample,
updated_ids.count(sample.paramid));
// In a normal situation, Akumuli allows duplicates (data-points
// with the same timestamp). But during recovery, this leads to
// the following problem. Recovery procedure will replay the log
// and try to add every value registered by it. The last value
// stored inside the NB+tree instance will be added second time
// by the replay. To prevent it this code disables the ability
// to add duplicates until the first value will be successfully
// added to the NB+tree instance. The progress is tracked
// per-series using the map (updated_ids).
switch(result) {
case StorageEngine::NBTreeAppendResult::FAIL_BAD_VALUE:
Logger::msg(AKU_LOG_INFO, "WAL recovery failed");
return false;
case StorageEngine::NBTreeAppendResult::FAIL_BAD_ID:
nlost++;
break;
case StorageEngine::NBTreeAppendResult::OK_FLUSH_NEEDED:
case StorageEngine::NBTreeAppendResult::OK:
updated_ids.insert(sample.paramid);
nsamples++;
break;
default:
break;
};
return true;
}
bool operator () (const InputLogSeriesName&) {
return true;
}
bool operator () (const InputLogRecoveryInfo&) {
return true;
}
};
Visitor visitor;
visitor.storage = this;
bool proceed = true;
size_t nitems = 0x1000;
u64 nsegments = 0;
std::vector<InputLogRow> rows(nitems);
Logger::msg(AKU_LOG_INFO, "WAL recovery started");
std::unordered_set<aku_ParamId> idfilter(ids2restore.begin(),
ids2restore.end());
while (proceed) {
aku_Status status;
u32 outsize;
std::tie(status, outsize) = ilog->read_next(nitems, rows.data());
if (status == AKU_SUCCESS || (status == AKU_ENO_DATA && outsize > 0)) {
for (u32 ix = 0; ix < outsize; ix++) {
const InputLogRow& row = rows.at(ix);
if (idfilter.count(row.id)) {
visitor.reset(row.id);
proceed = row.payload.apply_visitor(visitor);
}
}
nsegments++;
}
else if (status == AKU_ENO_DATA) {
Logger::msg(AKU_LOG_INFO, "WAL recovery completed");
Logger::msg(AKU_LOG_INFO, std::to_string(nsegments) + " segments scanned");
Logger::msg(AKU_LOG_INFO, std::to_string(visitor.nsamples) + " samples recovered");
Logger::msg(AKU_LOG_INFO, std::to_string(visitor.nlost) + " samples lost");
proceed = false;
}
else {
Logger::msg(AKU_LOG_ERROR, "WAL recovery error: " + StatusUtil::str(status));
proceed = false;
}
}
// Close column store.
// Some columns were restored using the NBTree crash recovery algorithm
// and WAL replay. To delete old WAL volumes we have to close these columns.
// Another problem that is solved here is memory usage. WAL has a mechanism that is
// used to offload columns that was opened and didn't received any updates for a while.
// If all columns will be opened at start, this will be meaningless.
auto mapping = cstore_->close();
if (!mapping.empty()) {
for (auto kv: mapping) {
u64 id;
std::vector<u64> vals;
std::tie(id, vals) = kv;
metadata_->add_rescue_point(id, std::move(vals));
}
if (done_.load() == 1) {
// Save finall mapping (should contain all affected columns)
metadata_->sync_with_metadata_storage(boost::bind(&SeriesMatcher::pull_new_names, &global_matcher_, _1));
}
}
bstore_->flush();
ilog->reopen();
ilog->delete_files();
}
static std::string to_isostring(aku_Timestamp ts) {
char buffer[0x100];
int len = DateTimeUtil::to_iso_string(ts, buffer, 0x100);
if (len < 1) {
AKU_PANIC("Can't convert timestamp to ISO string");
}
return std::string(buffer, buffer + len - 1);
}
// Run through mappings and dump contents
void dump_tree(std::ostream &stream,
std::shared_ptr<StorageEngine::BlockStore> bstore,
PlainSeriesMatcher const& matcher,
aku_ParamId id,
std::vector<StorageEngine::LogicAddr> rescue_points)
{
auto namekv = matcher.id2str(id);
std::string name(namekv.first, namekv.first + namekv.second);
stream << "\t<id>" << id << "</id>" << std::endl;
stream << "\t<name>" << name << "</name>" << std::endl;
stream << "\t<rescue_points>" << std::endl;
int tagix = 0;
for(auto rp: rescue_points) {
std::string tag = "addr_" + std::to_string(tagix++);
stream << "\t\t<" << tag << ">" << rp << "</" << tag << ">" << std::endl;
}
stream << "\t</rescue_points>" << std::endl;
// Repair status
using namespace StorageEngine;
auto treestate = NBTreeExtentsList::repair_status(rescue_points);
switch(treestate) {
case NBTreeExtentsList::RepairStatus::OK:
stream << "\t<repair_status>OK</repair_status>" << std::endl;
break;
case NBTreeExtentsList::RepairStatus::REPAIR:
stream << "\t<repair_status>Repair needed</repair_status>" << std::endl;
break;
case NBTreeExtentsList::RepairStatus::SKIP:
stream << "\t<repair_status>Skip</repair_status>" << std::endl;
break;
}
// Iterate tree in depth first order
enum class StackItemType {
// Flow control, this items should contain node addresses
NORMAL,
RECOVERY,
// Formatting control (should be used to maintain XML structure)
CLOSE_NODE,
OPEN_NODE,
CLOSE_CHILDREN,
OPEN_CHILDREN,
CLOSE_FANOUT,
OPEN_FANOUT,
};
typedef std::tuple<LogicAddr, int, StackItemType> StackItem; // (addr, indent, close)
std::stack<StackItem> stack;
for(auto it = rescue_points.rbegin(); it != rescue_points.rend(); it++) {
stack.push(std::make_tuple(EMPTY_ADDR, 1, StackItemType::CLOSE_NODE));
stack.push(std::make_tuple(*it, 2, treestate == NBTreeExtentsList::RepairStatus::OK
? StackItemType::NORMAL
: StackItemType::RECOVERY ));
stack.push(std::make_tuple(EMPTY_ADDR, 1, StackItemType::OPEN_NODE));
}
while(!stack.empty()) {
int indent;
LogicAddr curr;
StackItemType type;
std::tie(curr, indent, type) = stack.top();
stack.pop();
auto tag = [](int idnt, const char* tag_name, const char* token) {
std::stringstream str;
for (int i = 0; i < idnt; i++) {
str << '\t';
}
str << token << tag_name << '>';
return str.str();
};
auto _tag = [indent, tag](const char* tag_name) {
return tag(indent, tag_name, "<");
};
auto tag_ = [indent, tag](const char* tag_name) {
return tag(indent, tag_name, "</");
};
auto afmt = [](LogicAddr a) {
if (a == EMPTY_ADDR) {
return std::string("");
}
return std::to_string(a);
};
if (type == StackItemType::NORMAL || type == StackItemType::RECOVERY) {
std::unique_ptr<IOVecBlock> block;
aku_Status status;
std::tie(status, block) = bstore->read_iovec_block(curr);
if (status != AKU_SUCCESS) {
stream << _tag("addr") << afmt(curr) << "</addr>" << std::endl;
stream << _tag("fail") << StatusUtil::c_str(status) << "</fail>" << std::endl;
continue;
}
auto subtreeref = block->get_cheader<SubtreeRef>();
if (subtreeref->type == NBTreeBlockType::LEAF) {
// Dump leaf node's content
IOVecLeaf leaf(std::move(block));
SubtreeRef const* ref = leaf.get_leafmeta();
stream << _tag("type") << "Leaf" << "</type>\n";
stream << _tag("addr") << afmt(curr) << "</addr>\n";
stream << _tag("prev_addr") << afmt(leaf.get_prev_addr()) << "</prev_addr>\n";
stream << _tag("begin") << to_isostring(ref->begin) << "</begin>\n";
stream << _tag("end") << to_isostring(ref->end) << "</end>\n";
stream << _tag("count") << ref->count << "</count>\n";
stream << _tag("min") << ref->min << "</min>\n";
stream << _tag("min_time") << to_isostring(ref->min_time) << "</min_time>\n";
stream << _tag("max") << ref->max << "</max>\n";
stream << _tag("max_time") << to_isostring(ref->max_time) << "</max_time>\n";
stream << _tag("sum") << ref->sum << "</sum>\n";
stream << _tag("first") << ref->first << "</first>\n";
stream << _tag("last") << ref->last << "</last>\n";
stream << _tag("version") << ref->version << "</version>\n";
stream << _tag("level") << ref->level << "</level>\n";
stream << _tag("payload_size") << ref->payload_size << "</payload_size>\n";
stream << _tag("fanout_index") << ref->fanout_index << "</fanout_index>\n";
stream << _tag("checksum") << ref->checksum << "</checksum>\n";
if (type == StackItemType::RECOVERY) {
// type is RECOVERY, open fanout tag and dump all connected nodes
stack.push(std::make_tuple(EMPTY_ADDR, indent, StackItemType::CLOSE_FANOUT));
LogicAddr prev = leaf.get_prev_addr();
while(prev != EMPTY_ADDR) {
stack.push(std::make_tuple(EMPTY_ADDR, indent + 1, StackItemType::CLOSE_NODE));
stack.push(std::make_tuple(prev, indent + 2, StackItemType::NORMAL));
stack.push(std::make_tuple(EMPTY_ADDR, indent + 1, StackItemType::OPEN_NODE));
std::tie(status, block) = bstore->read_iovec_block(prev);
if (status != AKU_SUCCESS) {
// Block was deleted but it should be on the stack anyway
break;
}
IOVecLeaf lnext(std::move(block));
prev = lnext.get_prev_addr();
}
stack.push(std::make_tuple(EMPTY_ADDR, indent, StackItemType::OPEN_FANOUT));
}
} else {
// Dump inner node's content and children
IOVecSuperblock sblock(std::move(block));
SubtreeRef const* ref = sblock.get_sblockmeta();
stream << _tag("addr") << afmt(curr) << "</addr>\n";
stream << _tag("type") << "Superblock" << "</type>\n";
stream << _tag("prev_addr") << afmt(sblock.get_prev_addr()) << "</prev_addr>\n";
stream << _tag("begin") << to_isostring(ref->begin) << "</begin>\n";
stream << _tag("end") << to_isostring(ref->end) << "</end>\n";
stream << _tag("count") << ref->count << "</count>\n";
stream << _tag("min") << ref->min << "</min>\n";
stream << _tag("min_time") << to_isostring(ref->min_time) << "</min_time>\n";
stream << _tag("max") << ref->max << "</max>\n";
stream << _tag("max_time") << to_isostring(ref->max_time) << "</max_time>\n";
stream << _tag("sum") << ref->sum << "</sum>\n";
stream << _tag("first") << ref->first << "</first>\n";
stream << _tag("last") << ref->last << "</last>\n";
stream << _tag("version") << ref->version << "</version>\n";
stream << _tag("level") << ref->level << "</level>\n";
stream << _tag("payload_size") << ref->payload_size << "</payload_size>\n";
stream << _tag("fanout_index") << ref->fanout_index << "</fanout_index>\n";
stream << _tag("checksum") << ref->checksum << "</checksum>\n";
if (type == StackItemType::RECOVERY) {
// type is RECOVERY, open fanout tag and dump all connected nodes (if any)
stack.push(std::make_tuple(EMPTY_ADDR, indent, StackItemType::CLOSE_FANOUT));
LogicAddr prev = sblock.get_prev_addr();
while(prev != EMPTY_ADDR) {
stack.push(std::make_tuple(EMPTY_ADDR, indent + 1, StackItemType::CLOSE_NODE));
stack.push(std::make_tuple(prev, indent + 2, StackItemType::NORMAL));
stack.push(std::make_tuple(EMPTY_ADDR, indent + 1, StackItemType::OPEN_NODE));
std::tie(status, block) = bstore->read_iovec_block(prev);
if (status != AKU_SUCCESS) {
// Block was deleted but it should be on the stack anyway
break;
}
IOVecSuperblock sbnext(std::move(block));
prev = sbnext.get_prev_addr();
}
stack.push(std::make_tuple(EMPTY_ADDR, indent, StackItemType::OPEN_FANOUT));
}
std::vector<SubtreeRef> children;
status = sblock.read_all(&children);