-
Notifications
You must be signed in to change notification settings - Fork 996
Expand file tree
/
Copy pathlmdbbackend.cc
More file actions
3806 lines (3234 loc) · 116 KB
/
lmdbbackend.cc
File metadata and controls
3806 lines (3234 loc) · 116 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
/*
* This file is part of PowerDNS or dnsdist.
* Copyright -- PowerDNS.COM B.V. and its contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* In addition, for the avoidance of any doubt, permission is granted to
* link this program with OpenSSL and to (re)distribute the binaries
* produced as the result of such linking.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "lmdbbackend.hh"
#include "config.h"
#include "ext/lmdb-safe/lmdb-safe.hh"
#include "pdns/arguments.hh"
#include "pdns/base32.hh"
#include "pdns/dns.hh"
#include "pdns/dnsbackend.hh"
#include "pdns/dnsname.hh"
#include "pdns/dnspacket.hh"
#include "pdns/dnssecinfra.hh"
#include "pdns/logger.hh"
#include "pdns/misc.hh"
#include "pdns/pdnsexception.hh"
#include "pdns/sha.hh"
#include "pdns/uuid-utils.hh"
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/uuid/uuid_serialize.hpp>
#include <protozero/pbf_reader.hpp>
#include <protozero/pbf_writer.hpp>
#include <cstdio>
#include <cstring>
#include <lmdb.h>
#include <memory>
#include <stdexcept>
#include <unistd.h>
#include <utility>
#ifdef HAVE_SYSTEMD
#include <systemd/sd-daemon.h>
#endif
constexpr unsigned int SCHEMAVERSION{6};
// List the class version here. Default is 0
BOOST_CLASS_VERSION(LMDBBackend::KeyDataDB, 1)
BOOST_CLASS_VERSION(ZoneName, 1)
BOOST_CLASS_VERSION(DomainInfo, 2)
static bool s_first = true;
static uint32_t s_shards = 0;
static std::mutex s_lmdbStartupLock;
std::pair<uint32_t, uint32_t> LMDBBackend::getSchemaVersionAndShards(std::string& filename)
{
// cerr << "getting schema version for path " << filename << endl;
uint32_t schemaversion = 0;
MDB_env* tmpEnv = nullptr;
if (int retCode = mdb_env_create(&tmpEnv); retCode != 0) {
throw std::runtime_error("mdb_env_create failed: " + MDBError(retCode));
}
std::unique_ptr<MDB_env, decltype(&mdb_env_close)> env{tmpEnv, mdb_env_close};
if (int retCode = mdb_env_set_mapsize(tmpEnv, 0); retCode != 0) {
throw std::runtime_error("mdb_env_set_mapsize failed: " + MDBError(retCode));
}
if (int retCode = mdb_env_set_maxdbs(tmpEnv, 20); retCode != 0) { // we need 17: 1 {"pdns"} + 4 {"domains", "keydata", "tsig", "metadata"} * 2 {v4, v5} * 2 {main, index in _0}
throw std::runtime_error("mdb_env_set_maxdbs failed: " + MDBError(retCode));
}
{
int retCode = mdb_env_open(tmpEnv, filename.c_str(), MDB_NOSUBDIR | MDB_RDONLY, 0600);
if (retCode != 0) {
if (retCode == ENOENT) {
// we don't have a database yet! report schema 0, with 0 shards
return {0U, 0U};
}
throw std::runtime_error("mdb_env_open failed: " + MDBError(retCode));
}
}
MDB_txn* txn = nullptr;
if (int retCode = mdb_txn_begin(tmpEnv, nullptr, MDB_RDONLY, &txn); retCode != 0) {
throw std::runtime_error("mdb_txn_begin failed: " + MDBError(retCode));
}
MDB_dbi dbi;
{
int retCode = MDBDbi::mdb_dbi_open(txn, "pdns", 0, &dbi);
if (retCode != 0) {
if (retCode == MDB_NOTFOUND) {
// this means nothing has been inited yet
// we pretend this means the latest schema
mdb_txn_abort(txn);
return {SCHEMAVERSION, 0U};
}
mdb_txn_abort(txn);
throw std::runtime_error("mdb_dbi_open failed: " + MDBError(retCode));
}
}
MDB_val key, data;
key.mv_data = (char*)"schemaversion";
key.mv_size = strlen((char*)key.mv_data);
{
int retCode = mdb_get(txn, dbi, &key, &data);
if (retCode != 0) {
if (retCode == MDB_NOTFOUND) {
// this means nothing has been inited yet
// we pretend this means the latest schema
mdb_txn_abort(txn);
return {SCHEMAVERSION, 0U};
}
throw std::runtime_error("mdb_get pdns.schemaversion failed: " + MDBError(retCode));
}
}
if (data.mv_size == 4) {
// schemaversion is < 5 and is stored in 32 bits, in host order
memcpy(&schemaversion, data.mv_data, data.mv_size);
}
else if (data.mv_size >= LMDBLS::LS_MIN_HEADER_SIZE + sizeof(schemaversion)) {
// schemaversion is >= 5, stored in 32 bits, network order, after the LS header
// FIXME: get actual header size (including extension blocks) instead of just reading from the back
// FIXME: add a test for reading schemaversion and shards (and actual data, later) when there are variably sized headers
memcpy(&schemaversion, (char*)data.mv_data + data.mv_size - sizeof(schemaversion), sizeof(schemaversion));
schemaversion = ntohl(schemaversion);
}
else {
throw std::runtime_error("pdns.schemaversion had unexpected size");
}
uint32_t shards = 0;
key.mv_data = (char*)"shards";
key.mv_size = strlen((char*)key.mv_data);
{
int retCode = mdb_get(txn, dbi, &key, &data);
if (retCode != 0) {
if (retCode == MDB_NOTFOUND) {
cerr << "schemaversion was set, but shards was not. Dazed and confused, trying to exit." << endl;
mdb_txn_abort(txn);
// NOLINTNEXTLINE(concurrency-mt-unsafe)
exit(1);
}
throw std::runtime_error("mdb_get pdns.shards failed: " + MDBError(retCode));
}
}
if (data.mv_size == 4) {
// 'shards' is stored in 32 bits, in host order
memcpy(&shards, data.mv_data, data.mv_size);
}
else if (data.mv_size >= LMDBLS::LS_MIN_HEADER_SIZE + sizeof(shards)) {
// FIXME: get actual header size (including extension blocks) instead of just reading from the back
memcpy(&shards, (char*)data.mv_data + data.mv_size - sizeof(shards), sizeof(shards));
shards = ntohl(shards);
}
else {
throw std::runtime_error("pdns.shards had unexpected size");
}
mdb_txn_abort(txn);
return {schemaversion, shards};
}
namespace
{
// copy sdbi to tdbi, prepending an empty LS header (24 bytes of '\0') to all values
void copyDBIAndAddLSHeader(MDB_txn* txn, MDB_dbi sdbi, MDB_dbi tdbi)
{
// FIXME: clear out target dbi first
std::string header(LMDBLS::LS_MIN_HEADER_SIZE, '\0');
int rc;
MDB_cursor* cur;
if ((rc = mdb_cursor_open(txn, sdbi, &cur)) != 0) {
throw std::runtime_error("mdb_cursor_open failed: " + MDBError(rc));
}
MDB_val key, data;
rc = mdb_cursor_get(cur, &key, &data, MDB_FIRST);
while (rc == 0) {
std::string skey(reinterpret_cast<const char*>(key.mv_data), key.mv_size);
std::string sdata(reinterpret_cast<const char*>(data.mv_data), data.mv_size);
std::string stdata = header + sdata;
// cerr<<"got key="<<makeHexDump(skey)<<", data="<<makeHexDump(sdata)<<", sdata="<<makeHexDump(stdata)<<endl;
MDB_val tkey;
MDB_val tdata;
tkey.mv_data = const_cast<char*>(skey.c_str());
tkey.mv_size = skey.size();
tdata.mv_data = const_cast<char*>(stdata.c_str());
tdata.mv_size = stdata.size();
if ((rc = mdb_put(txn, tdbi, &tkey, &tdata, 0)) != 0) {
throw std::runtime_error("mdb_put failed: " + MDBError(rc));
}
rc = mdb_cursor_get(cur, &key, &data, MDB_NEXT);
}
if (rc != MDB_NOTFOUND) {
throw std::runtime_error("error while iterating dbi: " + MDBError(rc));
}
}
// migrated a typed DBI:
// 1. change keys (uint32_t) from host to network order
// 2. prepend empty LS header to values
void copyTypedDBI(MDB_txn* txn, MDB_dbi sdbi, MDB_dbi tdbi)
{
// FIXME: clear out target dbi first
std::string header(LMDBLS::LS_MIN_HEADER_SIZE, '\0');
int rc;
MDB_cursor* cur;
if ((rc = mdb_cursor_open(txn, sdbi, &cur)) != 0) {
throw std::runtime_error("mdb_cursor_open failed: " + MDBError(rc));
}
MDB_val key, data;
rc = mdb_cursor_get(cur, &key, &data, MDB_FIRST);
while (rc == 0) {
// std::string skey((char*) key.mv_data, key.mv_size);
std::string sdata(reinterpret_cast<const char*>(data.mv_data), data.mv_size);
std::string stdata = header + sdata;
uint32_t id;
if (key.mv_size != sizeof(uint32_t)) {
throw std::runtime_error("got non-uint32_t key in TypedDBI");
}
memcpy(&id, key.mv_data, sizeof(uint32_t));
id = htonl(id);
// cerr<<"got key="<<makeHexDump(skey)<<", data="<<makeHexDump(sdata)<<", sdata="<<makeHexDump(stdata)<<endl;
MDB_val tkey;
MDB_val tdata;
tkey.mv_data = reinterpret_cast<char*>(&id);
tkey.mv_size = sizeof(uint32_t);
tdata.mv_data = const_cast<char*>(stdata.c_str());
tdata.mv_size = stdata.size();
if ((rc = mdb_put(txn, tdbi, &tkey, &tdata, 0)) != 0) {
throw std::runtime_error("mdb_put failed: " + MDBError(rc));
}
rc = mdb_cursor_get(cur, &key, &data, MDB_NEXT);
}
if (rc != MDB_NOTFOUND) {
throw std::runtime_error("error while iterating dbi: " + MDBError(rc));
}
}
// migrating an index DBI:
// newkey = oldkey.len(), oldkey, htonl(oldvalue)
// newvalue = empty lsheader
void copyIndexDBI(MDB_txn* txn, MDB_dbi sdbi, MDB_dbi tdbi)
{
// FIXME: clear out target dbi first
std::string header(LMDBLS::LS_MIN_HEADER_SIZE, '\0');
int rc;
MDB_cursor* cur;
if ((rc = mdb_cursor_open(txn, sdbi, &cur)) != 0) {
throw std::runtime_error("mdb_cursor_open failed: " + MDBError(rc));
}
MDB_val key, data;
rc = mdb_cursor_get(cur, &key, &data, MDB_FIRST);
while (rc == 0) {
std::string lenprefix(sizeof(uint16_t), '\0');
std::string skey((char*)key.mv_data, key.mv_size);
uint32_t id;
if (data.mv_size != sizeof(uint32_t)) {
throw std::runtime_error("got non-uint32_t ID value in IndexDBI");
}
memcpy((void*)&id, data.mv_data, sizeof(uint32_t));
id = htonl(id);
uint16_t len = htons(skey.size());
memcpy((void*)lenprefix.data(), &len, sizeof(len));
std::string stkey = lenprefix + skey + std::string((char*)&id, sizeof(uint32_t));
MDB_val tkey;
MDB_val tdata;
tkey.mv_data = (char*)stkey.c_str();
tkey.mv_size = stkey.size();
tdata.mv_data = (char*)header.c_str();
tdata.mv_size = header.size();
if ((rc = mdb_put(txn, tdbi, &tkey, &tdata, 0)) != 0) {
throw std::runtime_error("mdb_put failed: " + MDBError(rc));
}
rc = mdb_cursor_get(cur, &key, &data, MDB_NEXT);
}
if (rc != MDB_NOTFOUND) {
throw std::runtime_error("error while iterating dbi: " + MDBError(rc));
}
}
}
bool LMDBBackend::upgradeToSchemav5(std::string& filename)
{
auto currentSchemaVersionAndShards = getSchemaVersionAndShards(filename);
uint32_t currentSchemaVersion = currentSchemaVersionAndShards.first;
uint32_t shards = currentSchemaVersionAndShards.second;
if (currentSchemaVersion != 3 && currentSchemaVersion != 4) {
throw std::runtime_error("upgrade to v5 requested but current schema is not v3 or v4, stopping");
}
MDB_env* env = nullptr;
if (int retCode = mdb_env_create(&env); retCode != 0) {
throw std::runtime_error("mdb_env_create failed: " + MDBError(retCode));
}
std::unique_ptr<MDB_env, decltype(&mdb_env_close)> envGuard{env, mdb_env_close};
if (int retCode = mdb_env_set_maxdbs(env, 20); retCode != 0) {
throw std::runtime_error("mdb_env_set_maxdbs failed: " + MDBError(retCode));
}
if (int retCode = mdb_env_open(env, filename.c_str(), MDB_NOSUBDIR, 0600); retCode != 0) {
throw std::runtime_error("mdb_env_open failed: " + MDBError(retCode));
}
MDB_txn* txn = nullptr;
if (int retCode = mdb_txn_begin(env, nullptr, 0, &txn); retCode != 0) {
throw std::runtime_error("mdb_txn_begin failed: " + MDBError(retCode));
}
#ifdef HAVE_SYSTEMD
/* A schema migration may take a long time. Extend the startup service timeout to 1 day,
* but only if this is beyond the original maximum time of TimeoutStartSec=.
*/
sd_notify(0, "EXTEND_TIMEOUT_USEC=86400000000");
#endif
std::cerr << "migrating shards" << std::endl;
for (uint32_t i = 0; i < shards; i++) {
string shardfile = filename + "-" + std::to_string(i);
if (access(shardfile.c_str(), F_OK) < 0) {
if (errno == ENOENT) {
// apparently this shard doesn't exist yet, moving on
std::cerr << "shard " << shardfile << " not found, continuing" << std::endl;
continue;
}
}
std::cerr << "migrating shard " << shardfile << std::endl;
MDB_env* shenv = nullptr;
if (int retCode = mdb_env_create(&shenv); retCode != 0) {
throw std::runtime_error("mdb_env_create failed: " + MDBError(retCode));
}
std::unique_ptr<MDB_env, decltype(&mdb_env_close)> shenvGuard{shenv, mdb_env_close};
if (int retCode = mdb_env_set_maxdbs(shenv, 8); retCode != 0) {
throw std::runtime_error("mdb_env_set_maxdbs failed: " + MDBError(retCode));
}
if (int retCode = mdb_env_open(shenv, shardfile.c_str(), MDB_NOSUBDIR, 0600); retCode != 0) {
throw std::runtime_error("mdb_env_open failed: " + MDBError(retCode));
}
MDB_txn* shtxn = nullptr;
if (int retCode = mdb_txn_begin(shenv, nullptr, 0, &shtxn); retCode != 0) {
throw std::runtime_error("mdb_txn_begin failed: " + MDBError(retCode));
}
MDB_dbi shdbi = 0;
const auto dbiOpenRc = MDBDbi::mdb_dbi_open(shtxn, "records", 0, &shdbi);
if (dbiOpenRc != 0) {
if (dbiOpenRc == MDB_NOTFOUND) {
mdb_txn_abort(shtxn);
continue;
}
mdb_txn_abort(shtxn);
throw std::runtime_error("mdb_dbi_open shard records failed: " + MDBError(dbiOpenRc));
}
MDB_dbi shdbi2 = 0;
if (int retCode = MDBDbi::mdb_dbi_open(shtxn, "records_v5", MDB_CREATE, &shdbi2); retCode != 0) {
mdb_dbi_close(shenv, shdbi);
mdb_txn_abort(shtxn);
throw std::runtime_error("mdb_dbi_open shard records_v5 failed: " + MDBError(retCode));
}
try {
copyDBIAndAddLSHeader(shtxn, shdbi, shdbi2);
}
catch (std::exception& e) {
mdb_dbi_close(shenv, shdbi2);
mdb_dbi_close(shenv, shdbi);
mdb_txn_abort(shtxn);
throw std::runtime_error("copyDBIAndAddLSHeader failed");
}
cerr << "shard mbd_drop=" << mdb_drop(shtxn, shdbi, 1) << endl;
mdb_txn_commit(shtxn);
mdb_dbi_close(shenv, shdbi2);
}
std::array<MDB_dbi, 4> fromtypeddbi{};
std::array<MDB_dbi, 4> totypeddbi{};
int index = 0;
for (const std::string dbname : {"domains", "keydata", "tsig", "metadata"}) {
std::cerr << "migrating " << dbname << std::endl;
std::string tdbname = dbname + "_v5";
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
if (int retCode = MDBDbi::mdb_dbi_open(txn, dbname.c_str(), 0, &fromtypeddbi[index]); retCode != 0) {
mdb_txn_abort(txn);
throw std::runtime_error("MDBDbi::mdb_dbi_open typeddbi failed: " + MDBError(retCode));
}
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
if (int retCode = MDBDbi::mdb_dbi_open(txn, tdbname.c_str(), MDB_CREATE, &totypeddbi[index]); retCode != 0) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
mdb_dbi_close(env, fromtypeddbi[index]);
mdb_txn_abort(txn);
throw std::runtime_error("mdb_dbi_open typeddbi target failed: " + MDBError(retCode));
}
try {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
copyTypedDBI(txn, fromtypeddbi[index], totypeddbi[index]);
}
catch (std::exception& e) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
mdb_dbi_close(env, totypeddbi[index]);
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
mdb_dbi_close(env, fromtypeddbi[index]);
mdb_txn_abort(txn);
throw std::runtime_error("copyTypedDBI failed");
}
// mdb_dbi_close(env, dbi2);
// mdb_dbi_close(env, dbi);
std::cerr << "migrated " << dbname << std::endl;
index++;
}
std::array<MDB_dbi, 4> fromindexdbi{};
std::array<MDB_dbi, 4> toindexdbi{};
index = 0;
for (const std::string dbname : {"domains", "keydata", "tsig", "metadata"}) {
std::string fdbname = dbname + "_0";
std::cerr << "migrating " << dbname << std::endl;
std::string tdbname = dbname + "_v5_0";
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
if (int retCode = MDBDbi::mdb_dbi_open(txn, fdbname.c_str(), 0, &fromindexdbi[index]); retCode != 0) {
mdb_txn_abort(txn);
throw std::runtime_error("mdb_dbi_open indexdbi failed: " + MDBError(retCode));
}
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
if (int retCode = MDBDbi::mdb_dbi_open(txn, tdbname.c_str(), MDB_CREATE, &toindexdbi[index]); retCode != 0) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
mdb_dbi_close(env, fromindexdbi[index]);
mdb_txn_abort(txn);
throw std::runtime_error("mdb_dbi_open indexdbi target failed: " + MDBError(retCode));
}
try {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
copyIndexDBI(txn, fromindexdbi[index], toindexdbi[index]);
}
catch (std::exception& e) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
mdb_dbi_close(env, toindexdbi[index]);
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
mdb_dbi_close(env, fromindexdbi[index]);
mdb_txn_abort(txn);
throw std::runtime_error("copyIndexDBI failed");
}
// mdb_dbi_close(env, dbi2);
// mdb_dbi_close(env, dbi);
std::cerr << "migrated " << dbname << std::endl;
index++;
}
MDB_dbi dbi = 0;
// finally, migrate the pdns db
if (int retCode = MDBDbi::mdb_dbi_open(txn, "pdns", 0, &dbi); retCode != 0) {
mdb_txn_abort(txn);
throw std::runtime_error("mdb_dbi_open pdns failed: " + MDBError(retCode));
}
MDB_val key;
MDB_val data;
std::string header(LMDBLS::LS_MIN_HEADER_SIZE, '\0');
for (const std::string keyname : {"schemaversion", "shards"}) {
cerr << "migrating pdns." << keyname << endl;
key.mv_data = (char*)keyname.c_str();
key.mv_size = keyname.size();
if (int retCode = mdb_get(txn, dbi, &key, &data); retCode != 0) {
throw std::runtime_error("mdb_get pdns.shards failed: " + MDBError(retCode));
}
if (data.mv_size != sizeof(uint32_t)) {
throw std::runtime_error("got non-uint32_t key");
}
uint32_t value = 0;
memcpy((void*)&value, data.mv_data, sizeof(uint32_t));
value = htonl(value);
if (keyname == "schemaversion") {
value = htonl(5);
}
std::string sdata(static_cast<char*>(data.mv_data), data.mv_size);
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
std::string stdata = header + std::string((char*)&value, sizeof(uint32_t));
MDB_val tdata;
tdata.mv_data = (char*)stdata.c_str();
tdata.mv_size = stdata.size();
if (int retCode = mdb_put(txn, dbi, &key, &tdata, 0); retCode != 0) {
throw std::runtime_error("mdb_put failed: " + MDBError(retCode));
}
}
for (const std::string keyname : {"uuid"}) {
cerr << "migrating pdns." << keyname << endl;
key.mv_data = (char*)keyname.c_str();
key.mv_size = keyname.size();
if (int retCode = mdb_get(txn, dbi, &key, &data); retCode != 0) {
throw std::runtime_error("mdb_get pdns.shards failed: " + MDBError(retCode));
}
std::string sdata((char*)data.mv_data, data.mv_size);
std::string stdata = header + sdata;
MDB_val tdata;
tdata.mv_data = (char*)stdata.c_str();
tdata.mv_size = stdata.size();
if (int retCode = mdb_put(txn, dbi, &key, &tdata, 0); retCode != 0) {
throw std::runtime_error("mdb_put failed: " + MDBError(retCode));
}
}
for (int i = 0; i < 4; i++) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
mdb_drop(txn, fromtypeddbi[i], 1);
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
mdb_drop(txn, fromindexdbi[i], 1);
}
cerr << "txn commit=" << mdb_txn_commit(txn) << endl;
for (int i = 0; i < 4; i++) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
mdb_dbi_close(env, totypeddbi[i]);
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
mdb_dbi_close(env, toindexdbi[i]);
}
cerr << "migration done" << endl;
return true;
}
bool LMDBBackend::upgradeToSchemav6(std::string& /* filename */)
{
// a v6 reader can read v5 databases just fine
// so this function currently does nothing
// - except rely on the caller to write '6' to pdns.schemaversion,
// as a v5 reader will be unable to handle domain objects once we've touched them
return true;
}
// Serial number cache
// Retrieve the transient domain info for the given domain, if any
bool LMDBBackend::TransientDomainInfoCache::get(domainid_t domainid, TransientDomainInfo& data) const
{
if (auto iter = d_data.find(domainid); iter != d_data.end()) {
data = iter->second;
return true;
}
return false;
}
// Remove the transient domain info for the given domain
void LMDBBackend::TransientDomainInfoCache::remove(domainid_t domainid)
{
if (auto iter = d_data.find(domainid); iter != d_data.end()) {
d_data.erase(iter);
}
}
// Create or update the transient domain info for the given domain
void LMDBBackend::TransientDomainInfoCache::update(domainid_t domainid, const TransientDomainInfo& data)
{
d_data.insert_or_assign(domainid, data);
}
// Return the contents of the first element and remove it
bool LMDBBackend::TransientDomainInfoCache::pop(domainid_t& domainid, TransientDomainInfo& data)
{
auto iter = d_data.begin();
if (iter == d_data.end()) {
return false;
}
domainid = iter->first;
data = iter->second;
(void)d_data.erase(iter);
return true;
}
SharedLockGuarded<LMDBBackend::TransientDomainInfoCache> LMDBBackend::s_transient_domain_info;
LMDBBackend::LMDBBackend(const std::string& suffix)
{
// overlapping domain ids in combination with relative names are a recipe for disaster
if (!suffix.empty()) {
throw std::runtime_error("LMDB backend does not support multiple instances");
}
if (g_slogStructured) {
d_slog = g_slog->withName("lmdb" + suffix);
}
d_views = ::arg().mustDo("views"); // This is a global setting
setArgPrefix("lmdb" + suffix);
string syncMode = toLower(getArg("sync-mode"));
if (syncMode == "nosync")
d_asyncFlag = MDB_NOSYNC;
else if (syncMode == "nometasync")
d_asyncFlag = MDB_NOMETASYNC;
else if (syncMode.empty() || syncMode == "sync")
d_asyncFlag = 0;
else
throw std::runtime_error("Unknown sync mode " + syncMode + " requested for LMDB backend");
d_mapsize_main = d_mapsize_shards = 0;
try {
d_mapsize_main = std::stoll(getArg("map-size"));
}
catch (const std::exception& e) {
throw std::runtime_error(std::string("Unable to parse the 'map-size' LMDB value: ") + e.what());
}
try {
d_mapsize_shards = std::stoll(getArg("shards-map-size"));
}
catch (const std::exception& e) {
throw std::runtime_error(std::string("Unable to parse the 'shards-map-size' LMDB value: ") + e.what());
}
if (d_mapsize_shards == 0) {
// Old configuration with only one settings for main and shards.
d_mapsize_shards = d_mapsize_main;
}
d_write_notification_update = mustDo("write-notification-update");
d_split_domains_table = mustDo("split-domains-table");
if (mustDo("lightning-stream")) {
d_random_ids = true;
d_handle_dups = true;
LMDBLS::s_flag_deleted = true;
if (atoi(getArg("shards").c_str()) != 1) {
throw std::runtime_error(std::string("running with Lightning Stream support requires shards=1"));
}
}
else {
d_random_ids = mustDo("random-ids");
d_handle_dups = false;
LMDBLS::s_flag_deleted = mustDo("flag-deleted");
}
bool opened = false;
if (s_first) {
auto lock = std::scoped_lock(s_lmdbStartupLock);
if (s_first) {
auto filename = getArg("filename");
auto currentSchemaVersionAndShards = getSchemaVersionAndShards(filename);
uint32_t currentSchemaVersion = currentSchemaVersionAndShards.first;
// std::cerr<<"current schema version: "<<currentSchemaVersion<<", shards="<<currentSchemaVersionAndShards.second<<std::endl;
if (getArgAsNum("schema-version") != SCHEMAVERSION) {
throw std::runtime_error("This version of the lmdbbackend only supports schema version 6. Configuration demands a lower version. Not starting up.");
}
if (currentSchemaVersion > 0 && currentSchemaVersion < 3) {
throw std::runtime_error("this version of the lmdbbackend can only upgrade from schema v3 and up. Upgrading from older schemas is not supported.");
}
if (currentSchemaVersion == 0) {
// no database is present yet, we can just create them
currentSchemaVersion = 6;
}
if (currentSchemaVersion == 3 || currentSchemaVersion == 4) {
if (!upgradeToSchemav5(filename)) {
throw std::runtime_error("Failed to perform LMDB schema version upgrade from v4 to v5");
}
currentSchemaVersion = 5;
}
if (currentSchemaVersion == 5) {
if (!upgradeToSchemav6(filename)) {
throw std::runtime_error("Failed to perform LMDB schema version upgrade from v5 to v6");
}
currentSchemaVersion = 6;
}
if (currentSchemaVersion != 6) {
throw std::runtime_error("Somehow, we are not at schema version 6. Giving up");
}
openAllTheDatabases();
opened = true;
auto pdnsdbi = d_tdomains->getEnv()->openDB("pdns", MDB_CREATE);
auto txn = d_tdomains->getEnv()->getRWTransaction();
const auto configShardsTemp = atoi(getArg("shards").c_str());
if (configShardsTemp < 0) {
throw std::runtime_error("a negative shards value is not supported");
}
if (configShardsTemp == 0) {
throw std::runtime_error("a shards value of 0 is not supported");
}
const auto configShards = static_cast<uint32_t>(configShardsTemp);
MDBOutVal shards{};
if (txn->get(pdnsdbi, "shards", shards) == 0) {
s_shards = shards.get<uint32_t>();
if (mustDo("lightning-stream") && s_shards != 1) {
throw std::runtime_error("running with Lightning Stream support enabled requires a database with exactly 1 shard");
}
if (s_shards != configShards) {
SLOG(g_log << Logger::Warning
<< "Note: configured number of lmdb shards ("
<< configShards
<< ") is different from on-disk ("
<< s_shards
<< "). Using on-disk shard number"
<< endl,
d_slog->info(Logr::Warning, "Note: configured number of lmdb shards differs from on-disk; using the on-disk value", "configured", Logging::Loggable(configShards), "on-disk", Logging::Loggable(s_shards)));
}
}
else {
s_shards = configShards;
txn->put(pdnsdbi, "shards", s_shards);
}
MDBOutVal gotuuid{};
if (txn->get(pdnsdbi, "uuid", gotuuid) != 0) {
const auto uuid = getUniqueID();
const string uuids(uuid.begin(), uuid.end());
txn->put(pdnsdbi, "uuid", uuids);
}
MDBOutVal _schemaversion{};
if (txn->get(pdnsdbi, "schemaversion", _schemaversion) != 0 || _schemaversion.get<uint32_t>() != currentSchemaVersion) {
txn->put(pdnsdbi, "schemaversion", currentSchemaVersion);
}
txn->commit();
s_first = false;
}
}
if (!opened) {
openAllTheDatabases();
}
d_trecords.resize(s_shards);
d_dolog = ::arg().mustDo("query-logging");
}
LMDBBackend::~LMDBBackend()
{
// LMDB internals require that, if we have multiple transactions active,
// we destroy them in the reverse order of their creation, thus we can't
// let the default destructor take care of d_rotxn and d_rwtxn.
if (d_txnorder) {
// RO transaction more recent than RW transaction
d_rotxn.reset();
d_rwtxn.reset();
}
else {
// RW transaction more recent than RO transaction
d_rwtxn.reset();
d_rotxn.reset();
}
}
void LMDBBackend::openAllTheDatabases()
{
auto filename = getArg("filename");
d_tdomains = std::make_shared<tdomains_t>(getMDBEnv(filename.c_str(), MDB_NOSUBDIR | MDB_NORDAHEAD | d_asyncFlag, 0600, d_mapsize_main), "domains_v5");
d_tmeta = std::make_shared<tmeta_t>(d_tdomains->getEnv(), "metadata_v5");
d_tkdb = std::make_shared<tkdb_t>(d_tdomains->getEnv(), "keydata_v5");
d_ttsig = std::make_shared<ttsig_t>(d_tdomains->getEnv(), "tsig_v5");
d_tnetworks = d_tdomains->getEnv()->openDB("networks_v6", MDB_CREATE);
d_tviews = d_tdomains->getEnv()->openDB("views_v6", MDB_CREATE);
if (d_split_domains_table) {
d_tdomains_extra = std::make_shared<tdomain_extra_t>(d_tdomains->getEnv(), "domains_extra_v6");
}
}
unsigned int LMDBBackend::getCapabilities()
{
unsigned int caps = CAP_DNSSEC | CAP_DIRECT | CAP_LIST | CAP_CREATE | CAP_SEARCH | CAP_COMMENTS;
if (d_views) {
caps |= CAP_VIEWS;
}
return caps;
}
namespace boost
{
namespace serialization
{
template <class Archive>
void save(Archive& ar, const DNSName& g, const unsigned int /* version */)
{
if (g.empty()) {
ar& std::string();
}
else {
ar & g.toDNSStringLC();
}
}
template <class Archive>
void load(Archive& ar, DNSName& g, const unsigned int /* version */)
{
string tmp;
ar & tmp;
if (tmp.empty()) {
g = DNSName();
}
else {
g = DNSName(tmp.c_str(), tmp.size(), 0, false);
}
}
template <class Archive>
void save(Archive& arc, const ZoneName& zone, const unsigned int /* version */)
{
arc & zone.operator const DNSName&();
arc & zone.getVariant();
}
template <class Archive>
void load(Archive& arc, ZoneName& zone, const unsigned int version)
{
if (version == 0) { // for schemas up to 5, ZoneName serialized as DNSName
std::string tmp{};
arc & tmp;
if (tmp.empty()) {
zone = ZoneName();
}
else {
zone = ZoneName(DNSName(tmp.c_str(), tmp.size(), 0, false));
}
return;
}
DNSName tmp;
std::string variant{};
arc & tmp;
arc & variant;
zone = ZoneName(tmp, variant);
}
template <class Archive>
void save(Archive& ar, const DomainInfo& g, const unsigned int /* version */)
{
ar & g.zone;
ar & g.last_check;
ar & g.account;
ar & g.primaries;
ar& static_cast<uint32_t>(g.id);
ar & g.notified_serial;
ar & g.kind;
ar & g.options;
ar & g.catalog;
}
template <class Archive>
void load(Archive& ar, DomainInfo& g, const unsigned int version)
{
if (version >= 2) {
ar & g.zone;
}
else {
DNSName tmp;
ar & tmp;
new (&g.zone) ZoneName(tmp);
}
ar & g.last_check;
ar & g.account;
ar & g.primaries;
uint32_t domainId{0};
ar & domainId;
g.id = static_cast<domainid_t>(domainId);
ar & g.notified_serial;
ar & g.kind;
switch (version) {
case 0:
// These fields did not exist.
g.options.clear();