forked from zerotier/ZeroTierOne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PostgreSQL.cpp
1883 lines (1691 loc) · 55.9 KB
/
PostgreSQL.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 (c)2019 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "PostgreSQL.hpp"
#ifdef ZT_CONTROLLER_USE_LIBPQ
#include "../node/Constants.hpp"
#include "EmbeddedNetworkController.hpp"
#include "../version.h"
#include "Redis.hpp"
#include <libpq-fe.h>
#include <sstream>
#include <climits>
using json = nlohmann::json;
namespace {
static const int DB_MINIMUM_VERSION = 5;
static const char *_timestr()
{
time_t t = time(0);
char *ts = ctime(&t);
char *p = ts;
if (!p)
return "";
while (*p) {
if (*p == '\n') {
*p = (char)0;
break;
}
++p;
}
return ts;
}
/*
std::string join(const std::vector<std::string> &elements, const char * const separator)
{
switch(elements.size()) {
case 0:
return "";
case 1:
return elements[0];
default:
std::ostringstream os;
std::copy(elements.begin(), elements.end()-1, std::ostream_iterator<std::string>(os, separator));
os << *elements.rbegin();
return os.str();
}
}
*/
} // anonymous namespace
using namespace ZeroTier;
using Attrs = std::vector<std::pair<std::string, std::string>>;
using Item = std::pair<std::string, Attrs>;
using ItemStream = std::vector<Item>;
PostgreSQL::PostgreSQL(const Identity &myId, const char *path, int listenPort, RedisConfig *rc)
: DB()
, _myId(myId)
, _myAddress(myId.address())
, _ready(0)
, _connected(1)
, _run(1)
, _waitNoticePrinted(false)
, _listenPort(listenPort)
, _rc(rc)
, _redis(NULL)
, _cluster(NULL)
{
char myAddress[64];
_myAddressStr = myId.address().toString(myAddress);
_connString = std::string(path) + " application_name=controller_" + _myAddressStr;
// Database Schema Version Check
PGconn *conn = getPgConn();
if (PQstatus(conn) != CONNECTION_OK) {
fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
exit(1);
}
PGresult *res = PQexec(conn, "SELECT version FROM ztc_database");
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
fprintf(stderr, "Error determining database version");
exit(1);
}
if (PQntuples(res) != 1) {
fprintf(stderr, "Invalid number of db version tuples returned.");
exit(1);
}
int dbVersion = std::stoi(PQgetvalue(res, 0, 0));
if (dbVersion < DB_MINIMUM_VERSION) {
fprintf(stderr, "Central database schema version too low. This controller version requires a minimum schema version of %d. Please upgrade your Central instance", DB_MINIMUM_VERSION);
exit(1);
}
PQclear(res);
res = NULL;
if (_rc != NULL) {
sw::redis::ConnectionOptions opts;
sw::redis::ConnectionPoolOptions poolOpts;
opts.host = _rc->hostname;
opts.port = _rc->port;
opts.password = _rc->password;
opts.db = 0;
poolOpts.size = 10;
if (_rc->clusterMode) {
fprintf(stderr, "Using Redis in Cluster Mode\n");
_cluster = std::make_shared<sw::redis::RedisCluster>(opts, poolOpts);
} else {
fprintf(stderr, "Using Redis in Standalone Mode\n");
_redis = std::make_shared<sw::redis::Redis>(opts, poolOpts);
}
}
_readyLock.lock();
fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S, ::_timestr(), (unsigned long long)_myAddress.toInt());
_waitNoticePrinted = true;
initializeNetworks(conn);
initializeMembers(conn);
PQfinish(conn);
conn = NULL;
_heartbeatThread = std::thread(&PostgreSQL::heartbeat, this);
_membersDbWatcher = std::thread(&PostgreSQL::membersDbWatcher, this);
_networksDbWatcher = std::thread(&PostgreSQL::networksDbWatcher, this);
for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
_commitThread[i] = std::thread(&PostgreSQL::commitThread, this);
}
_onlineNotificationThread = std::thread(&PostgreSQL::onlineNotificationThread, this);
}
PostgreSQL::~PostgreSQL()
{
_run = 0;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
_heartbeatThread.join();
_membersDbWatcher.join();
_networksDbWatcher.join();
_commitQueue.stop();
for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
_commitThread[i].join();
}
_onlineNotificationThread.join();
}
bool PostgreSQL::waitForReady()
{
while (_ready < 2) {
_readyLock.lock();
_readyLock.unlock();
}
return true;
}
bool PostgreSQL::isReady()
{
return ((_ready == 2)&&(_connected));
}
bool PostgreSQL::save(nlohmann::json &record,bool notifyListeners)
{
bool modified = false;
try {
if (!record.is_object())
return false;
const std::string objtype = record["objtype"];
if (objtype == "network") {
const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
if (nwid) {
nlohmann::json old;
get(nwid,old);
if ((!old.is_object())||(!_compareRecords(old,record))) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
_commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
modified = true;
}
}
} else if (objtype == "member") {
const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
if ((id)&&(nwid)) {
nlohmann::json network,old;
get(nwid,network,id,old);
if ((!old.is_object())||(!_compareRecords(old,record))) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
_commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
modified = true;
}
}
}
} catch (std::exception &e) {
fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what());
} catch (...) {
fprintf(stderr, "Unknown error on PostgreSQL::save\n");
}
return modified;
}
void PostgreSQL::eraseNetwork(const uint64_t networkId)
{
char tmp2[24];
waitForReady();
Utils::hex(networkId, tmp2);
std::pair<nlohmann::json,bool> tmp;
tmp.first["id"] = tmp2;
tmp.first["objtype"] = "_delete_network";
tmp.second = true;
_commitQueue.post(tmp);
nlohmann::json nullJson;
_networkChanged(tmp.first, nullJson, true);
}
void PostgreSQL::eraseMember(const uint64_t networkId, const uint64_t memberId)
{
char tmp2[24];
waitForReady();
std::pair<nlohmann::json,bool> tmp, nw;
Utils::hex(networkId, tmp2);
tmp.first["nwid"] = tmp2;
Utils::hex(memberId, tmp2);
tmp.first["id"] = tmp2;
tmp.first["objtype"] = "_delete_member";
tmp.second = true;
_commitQueue.post(tmp);
nlohmann::json nullJson;
_memberChanged(tmp.first, nullJson, true);
}
void PostgreSQL::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress)
{
std::lock_guard<std::mutex> l(_lastOnline_l);
std::pair<int64_t, InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId, memberId)];
i.first = OSUtils::now();
if (physicalAddress) {
i.second = physicalAddress;
}
}
void PostgreSQL::initializeNetworks(PGconn *conn)
{
try {
if (PQstatus(conn) != CONNECTION_OK) {
fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
exit(1);
}
std::string setKey = "networks:{" + _myAddressStr + "}";
// if (_rc != NULL) {
// try {
// if (_rc->clusterMode) {
// _cluster->del(setKey);
// } else {
// _redis->del(setKey);
// }
// } catch (sw::redis::Error &e) {
// // del can throw an error if the key doesn't exist
// // swallow it and move along
// }
// }
std::unordered_set<std::string> networkSet;
const char *params[1] = {
_myAddressStr.c_str()
};
fprintf(stderr, "Initializing Networks...\n");
PGresult *res = PQexecParams(conn, "SELECT id, EXTRACT(EPOCH FROM creation_time AT TIME ZONE 'UTC')*1000, capabilities, "
"enable_broadcast, EXTRACT(EPOCH FROM last_modified AT TIME ZONE 'UTC')*1000, mtu, multicast_limit, name, private, remote_trace_level, "
"remote_trace_target, revision, rules, tags, v4_assign_mode, v6_assign_mode FROM ztc_network "
"WHERE deleted = false AND controller_id = $1",
1,
NULL,
params,
NULL,
NULL,
0);
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
fprintf(stderr, "Networks Initialization Failed: %s", PQerrorMessage(conn));
PQclear(res);
exit(1);
}
int numRows = PQntuples(res);
for (int i = 0; i < numRows; ++i) {
json empty;
json config;
const char *nwidparam[1] = {
PQgetvalue(res, i, 0)
};
std::string nwid = PQgetvalue(res, i, 0);
networkSet.insert(nwid);
config["id"] = nwid;
config["nwid"] = nwid;
try {
config["creationTime"] = std::stoull(PQgetvalue(res, i, 1));
} catch (std::exception &e) {
config["creationTime"] = 0ULL;
//fprintf(stderr, "Error converting creation time: %s\n", PQgetvalue(res, i, 1));
}
config["capabilities"] = json::parse(PQgetvalue(res, i, 2));
config["enableBroadcast"] = (strcmp(PQgetvalue(res, i, 3),"t")==0);
try {
config["lastModified"] = std::stoull(PQgetvalue(res, i, 4));
} catch (std::exception &e) {
config["lastModified"] = 0ULL;
//fprintf(stderr, "Error converting last modified: %s\n", PQgetvalue(res, i, 4));
}
try {
config["mtu"] = std::stoi(PQgetvalue(res, i, 5));
} catch (std::exception &e) {
config["mtu"] = 2800;
}
try {
config["multicastLimit"] = std::stoi(PQgetvalue(res, i, 6));
} catch (std::exception &e) {
config["multicastLimit"] = 64;
}
config["name"] = PQgetvalue(res, i, 7);
config["private"] = (strcmp(PQgetvalue(res, i, 8),"t")==0);
try {
config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
} catch (std::exception &e) {
config["remoteTraceLevel"] = 0;
}
config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
try {
config["revision"] = std::stoull(PQgetvalue(res, i, 11));
} catch (std::exception &e) {
config["revision"] = 0ULL;
//fprintf(stderr, "Error converting revision: %s\n", PQgetvalue(res, i, 11));
}
config["rules"] = json::parse(PQgetvalue(res, i, 12));
config["tags"] = json::parse(PQgetvalue(res, i, 13));
config["v4AssignMode"] = json::parse(PQgetvalue(res, i, 14));
config["v6AssignMode"] = json::parse(PQgetvalue(res, i, 15));
config["objtype"] = "network";
config["ipAssignmentPools"] = json::array();
config["routes"] = json::array();
PGresult *r2 = PQexecParams(conn,
"SELECT host(ip_range_start), host(ip_range_end) FROM ztc_network_assignment_pool WHERE network_id = $1",
1,
NULL,
nwidparam,
NULL,
NULL,
0);
if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
fprintf(stderr, "ERROR: Error retreiving IP pools for network: %s\n", PQresultErrorMessage(r2));
PQclear(r2);
PQclear(res);
exit(1);
}
int n = PQntuples(r2);
for (int j = 0; j < n; ++j) {
json ip;
ip["ipRangeStart"] = PQgetvalue(r2, j, 0);
ip["ipRangeEnd"] = PQgetvalue(r2, j, 1);
config["ipAssignmentPools"].push_back(ip);
}
PQclear(r2);
r2 = PQexecParams(conn,
"SELECT host(address), bits, host(via) FROM ztc_network_route WHERE network_id = $1",
1,
NULL,
nwidparam,
NULL,
NULL,
0);
if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
fprintf(stderr, "ERROR: Error retreiving routes for network: %s\n", PQresultErrorMessage(r2));
PQclear(r2);
PQclear(res);
exit(1);
}
n = PQntuples(r2);
for (int j = 0; j < n; ++j) {
std::string addr = PQgetvalue(r2, j, 0);
std::string bits = PQgetvalue(r2, j, 1);
std::string via = PQgetvalue(r2, j, 2);
json route;
route["target"] = addr + "/" + bits;
if (via == "NULL") {
route["via"] = nullptr;
} else {
route["via"] = via;
}
config["routes"].push_back(route);
}
r2 = PQexecParams(conn,
"SELECT domain, servers FROM ztc_network_dns WHERE network_id = $1",
1,
NULL,
nwidparam,
NULL,
NULL,
0);
if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
fprintf(stderr, "ERROR: Error retrieving DNS settings for network: %s\n", PQresultErrorMessage(r2));
PQclear(r2);
PQclear(res);
exit(1);
}
n = PQntuples(r2);
if (n > 1) {
fprintf(stderr, "ERROR: invalid number of DNS configurations for network %s. Must be 0 or 1\n", nwid.c_str());
} else if (n == 1) {
json obj;
std::string domain = PQgetvalue(r2, 0, 0);
std::string serverList = PQgetvalue(r2, 0, 1);
auto servers = json::array();
if (serverList.rfind("{",0) != std::string::npos) {
serverList = serverList.substr(1, serverList.size()-2);
std::stringstream ss(serverList);
while(ss.good()) {
std::string server;
std::getline(ss, server, ',');
servers.push_back(server);
}
}
obj["domain"] = domain;
obj["servers"] = servers;
config["dns"] = obj;
}
PQclear(r2);
_networkChanged(empty, config, false);
}
PQclear(res);
// if(!networkSet.empty()) {
// if (_rc && _rc->clusterMode) {
// auto tx = _cluster->transaction(_myAddressStr, true);
// tx.sadd(setKey, networkSet.begin(), networkSet.end());
// tx.exec();
// } else if (_rc && !_rc->clusterMode) {
// auto tx = _redis->transaction(true);
// tx.sadd(setKey, networkSet.begin(), networkSet.end());
// tx.exec();
// }
// }
if (++this->_ready == 2) {
if (_waitNoticePrinted) {
fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
}
_readyLock.unlock();
}
} catch (sw::redis::Error &e) {
fprintf(stderr, "ERROR: Error initializing networks in Redis: %s\n", e.what());
exit(-1);
} catch (std::exception &e) {
fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
exit(-1);
}
}
void PostgreSQL::initializeMembers(PGconn *conn)
{
try {
if (PQstatus(conn) != CONNECTION_OK) {
fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
exit(1);
}
// std::string setKeyBase = "network-nodes-all:{" + _myAddressStr + "}:";
// if (_rc != NULL) {
// std::lock_guard<std::mutex> l(_networks_l);
// std::unordered_set<std::string> deletes;
// for ( auto it : _networks) {
// uint64_t nwid_i = it.first;
// char nwidTmp[64] = {0};
// OSUtils::ztsnprintf(nwidTmp, sizeof(nwidTmp), "%.16llx", nwid_i);
// std::string nwid(nwidTmp);
// std::string key = setKeyBase + nwid;
// deletes.insert(key);
// }
// if (!deletes.empty()) {
// if (_rc->clusterMode) {
// auto tx = _cluster->transaction(_myAddressStr, true);
// for (std::string k : deletes) {
// tx.del(k);
// }
// tx.exec();
// } else {
// auto tx = _redis->transaction(true);
// for (std::string k : deletes) {
// tx.del(k);
// }
// tx.exec();
// }
// }
// }
const char *params[1] = {
_myAddressStr.c_str()
};
std::unordered_map<std::string, std::string> networkMembers;
fprintf(stderr, "Initializing Members...\n");
PGresult *res = PQexecParams(conn,
"SELECT m.id, m.network_id, m.active_bridge, m.authorized, m.capabilities, EXTRACT(EPOCH FROM m.creation_time AT TIME ZONE 'UTC')*1000, m.identity, "
" EXTRACT(EPOCH FROM m.last_authorized_time AT TIME ZONE 'UTC')*1000, "
" EXTRACT(EPOCH FROM m.last_deauthorized_time AT TIME ZONE 'UTC')*1000, "
" m.remote_trace_level, m.remote_trace_target, m.tags, m.v_major, m.v_minor, m.v_rev, m.v_proto, "
" m.no_auto_assign_ips, m.revision "
"FROM ztc_member m "
"INNER JOIN ztc_network n "
" ON n.id = m.network_id "
"WHERE n.controller_id = $1 AND m.deleted = false",
1,
NULL,
params,
NULL,
NULL,
0);
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
PQclear(res);
exit(1);
}
int numRows = PQntuples(res);
for (int i = 0; i < numRows; ++i) {
json empty;
json config;
std::string memberId(PQgetvalue(res, i, 0));
std::string networkId(PQgetvalue(res, i, 1));
// networkMembers.insert(std::pair<std::string, std::string>(setKeyBase+networkId, memberId));
std::string ctime = PQgetvalue(res, i, 5);
config["id"] = memberId;
config["nwid"] = networkId;
config["activeBridge"] = (strcmp(PQgetvalue(res, i, 2), "t") == 0);
config["authorized"] = (strcmp(PQgetvalue(res, i, 3), "t") == 0);
try {
config["capabilities"] = json::parse(PQgetvalue(res, i, 4));
} catch (std::exception &e) {
config["capabilities"] = json::array();
}
try {
config["creationTime"] = std::stoull(PQgetvalue(res, i, 5));
} catch (std::exception &e) {
config["creationTime"] = 0ULL;
//fprintf(stderr, "Error upding creation time (member): %s\n", PQgetvalue(res, i, 5));
}
config["identity"] = PQgetvalue(res, i, 6);
try {
config["lastAuthorizedTime"] = std::stoull(PQgetvalue(res, i, 7));
} catch(std::exception &e) {
config["lastAuthorizedTime"] = 0ULL;
//fprintf(stderr, "Error updating last auth time (member): %s\n", PQgetvalue(res, i, 7));
}
try {
config["lastDeauthorizedTime"] = std::stoull(PQgetvalue(res, i, 8));
} catch( std::exception &e) {
config["lastDeauthorizedTime"] = 0ULL;
//fprintf(stderr, "Error updating last deauth time (member): %s\n", PQgetvalue(res, i, 8));
}
try {
config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
} catch (std::exception &e) {
config["remoteTraceLevel"] = 0;
}
config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
try {
config["tags"] = json::parse(PQgetvalue(res, i, 11));
} catch (std::exception &e) {
config["tags"] = json::array();
}
try {
config["vMajor"] = std::stoi(PQgetvalue(res, i, 12));
} catch(std::exception &e) {
config["vMajor"] = -1;
}
try {
config["vMinor"] = std::stoi(PQgetvalue(res, i, 13));
} catch (std::exception &e) {
config["vMinor"] = -1;
}
try {
config["vRev"] = std::stoi(PQgetvalue(res, i, 14));
} catch (std::exception &e) {
config["vRev"] = -1;
}
try {
config["vProto"] = std::stoi(PQgetvalue(res, i, 15));
} catch (std::exception &e) {
config["vProto"] = -1;
}
config["noAutoAssignIps"] = (strcmp(PQgetvalue(res, i, 16), "t") == 0);
try {
config["revision"] = std::stoull(PQgetvalue(res, i, 17));
} catch (std::exception &e) {
config["revision"] = 0ULL;
//fprintf(stderr, "Error updating revision (member): %s\n", PQgetvalue(res, i, 17));
}
config["objtype"] = "member";
config["ipAssignments"] = json::array();
const char *p2[2] = {
memberId.c_str(),
networkId.c_str()
};
PGresult *r2 = PQexecParams(conn,
"SELECT DISTINCT address FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
2,
NULL,
p2,
NULL,
NULL,
0);
if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
PQclear(r2);
PQclear(res);
exit(1);
}
int n = PQntuples(r2);
for (int j = 0; j < n; ++j) {
std::string ipaddr = PQgetvalue(r2, j, 0);
std::size_t pos = ipaddr.find('/');
if (pos != std::string::npos) {
ipaddr = ipaddr.substr(0, pos);
}
config["ipAssignments"].push_back(ipaddr);
}
_memberChanged(empty, config, false);
}
PQclear(res);
// if (!networkMembers.empty()) {
// if (_rc != NULL) {
// if (_rc->clusterMode) {
// auto tx = _cluster->transaction(_myAddressStr, true);
// for (auto it : networkMembers) {
// tx.sadd(it.first, it.second);
// }
// tx.exec();
// } else {
// auto tx = _redis->transaction(true);
// for (auto it : networkMembers) {
// tx.sadd(it.first, it.second);
// }
// tx.exec();
// }
// }
// }
if (++this->_ready == 2) {
if (_waitNoticePrinted) {
fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
}
_readyLock.unlock();
}
} catch (sw::redis::Error &e) {
fprintf(stderr, "ERROR: Error initializing members (redis): %s\n", e.what());
} catch (std::exception &e) {
fprintf(stderr, "ERROR: Error initializing members: %s\n", e.what());
exit(-1);
}
}
void PostgreSQL::heartbeat()
{
char publicId[1024];
char hostnameTmp[1024];
_myId.toString(false,publicId);
if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
hostnameTmp[0] = (char)0;
} else {
for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
hostnameTmp[i] = (char)0;
break;
}
}
}
const char *controllerId = _myAddressStr.c_str();
const char *publicIdentity = publicId;
const char *hostname = hostnameTmp;
PGconn *conn = getPgConn();
if (PQstatus(conn) == CONNECTION_BAD) {
fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
PQfinish(conn);
exit(1);
}
while (_run == 1) {
if(PQstatus(conn) != CONNECTION_OK) {
fprintf(stderr, "%s heartbeat thread lost connection to Database\n", _myAddressStr.c_str());
PQfinish(conn);
exit(6);
}
int64_t ts = OSUtils::now();
if (conn) {
std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
std::string build = std::to_string(ZEROTIER_ONE_VERSION_BUILD);
std::string now = std::to_string(ts);
std::string host_port = std::to_string(_listenPort);
std::string use_redis = "false"; // (_rc != NULL) ? "true" : "false";
const char *values[10] = {
controllerId,
hostname,
now.c_str(),
publicIdentity,
major.c_str(),
minor.c_str(),
rev.c_str(),
build.c_str(),
host_port.c_str(),
use_redis.c_str()
};
PGresult *res = PQexecParams(conn,
"INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build, host_port, use_redis) "
"VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8, $9, $10) "
"ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
"public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
"v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev, host_port = EXCLUDED.host_port, "
"use_redis = EXCLUDED.use_redis",
10, // number of parameters
NULL, // oid field. ignore
values, // values for substitution
NULL, // lengths in bytes of each value
NULL, // binary?
0);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "Heartbeat Update Failed: %s\n", PQresultErrorMessage(res));
}
PQclear(res);
}
// if (_rc != NULL) {
// if (_rc->clusterMode) {
// _cluster->zadd("controllers", controllerId, ts);
// } else {
// _redis->zadd("controllers", controllerId, ts);
// }
// }
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
PQfinish(conn);
conn = NULL;
fprintf(stderr, "Exited heartbeat thread\n");
}
void PostgreSQL::membersDbWatcher()
{
PGconn *conn = getPgConn(NO_OVERRIDE);
if (PQstatus(conn) == CONNECTION_BAD) {
fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
PQfinish(conn);
exit(1);
}
if (_rc) {
PQfinish(conn);
conn = NULL;
_membersWatcher_Redis();
} else {
_membersWatcher_Postgres(conn);
PQfinish(conn);
conn = NULL;
}
if (_run == 1) {
fprintf(stderr, "ERROR: %s membersDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
exit(9);
}
fprintf(stderr, "Exited membersDbWatcher\n");
}
void PostgreSQL::_membersWatcher_Postgres(PGconn *conn) {
char buf[11] = {0};
std::string cmd = "LISTEN member_" + std::string(_myAddress.toString(buf));
fprintf(stderr, "Listening to member stream: %s\n", cmd.c_str());
PGresult *res = PQexec(conn, cmd.c_str());
if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
PQclear(res);
PQfinish(conn);
exit(1);
}
PQclear(res); res = NULL;
while(_run == 1) {
if (PQstatus(conn) != CONNECTION_OK) {
fprintf(stderr, "ERROR: Member Watcher lost connection to Postgres.");
exit(-1);
}
PGnotify *notify = NULL;
PQconsumeInput(conn);
while ((notify = PQnotifies(conn)) != NULL) {
//fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
try {
json tmp(json::parse(notify->extra));
json &ov = tmp["old_val"];
json &nv = tmp["new_val"];
json oldConfig, newConfig;
if (ov.is_object()) oldConfig = ov;
if (nv.is_object()) newConfig = nv;
if (oldConfig.is_object() || newConfig.is_object()) {
_memberChanged(oldConfig,newConfig,(this->_ready>=2));
}
} catch (...) {} // ignore bad records
free(notify);
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void PostgreSQL::_membersWatcher_Redis() {
char buf[11] = {0};
std::string key = "member-stream:{" + std::string(_myAddress.toString(buf)) + "}";
fprintf(stderr, "Listening to member stream: %s\n", key.c_str());
while (_run == 1) {
try {
json tmp;
std::unordered_map<std::string, ItemStream> result;
if (_rc->clusterMode) {
_cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
} else {
_redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
}
if (!result.empty()) {
for (auto element : result) {
#ifdef ZT_TRACE
fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
#endif
for (auto rec : element.second) {
std::string id = rec.first;
auto attrs = rec.second;
#ifdef ZT_TRACE
fprintf(stdout, "Record ID: %s\n", id.c_str());
fprintf(stdout, "attrs len: %lu\n", attrs.size());
#endif
for (auto a : attrs) {
#ifdef ZT_TRACE
fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
#endif
try {
tmp = json::parse(a.second);
json &ov = tmp["old_val"];
json &nv = tmp["new_val"];
json oldConfig, newConfig;
if (ov.is_object()) oldConfig = ov;
if (nv.is_object()) newConfig = nv;
if (oldConfig.is_object()||newConfig.is_object()) {
_memberChanged(oldConfig,newConfig,(this->_ready >= 2));
}
} catch (...) {
fprintf(stderr, "json parse error in networkWatcher_Redis\n");
}
}
if (_rc->clusterMode) {
_cluster->xdel(key, id);
} else {
_redis->xdel(key, id);
}
}
}
}
} catch (sw::redis::Error &e) {
fprintf(stderr, "Error in Redis members watcher: %s\n", e.what());
}
}
fprintf(stderr, "membersWatcher ended\n");
}
void PostgreSQL::networksDbWatcher()
{
PGconn *conn = getPgConn(NO_OVERRIDE);
if (PQstatus(conn) == CONNECTION_BAD) {
fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
PQfinish(conn);
exit(1);
}
if (_rc) {
PQfinish(conn);
conn = NULL;
_networksWatcher_Redis();
} else {
_networksWatcher_Postgres(conn);
PQfinish(conn);
conn = NULL;
}
if (_run == 1) {
fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
exit(8);
}
fprintf(stderr, "Exited networksDbWatcher\n");
}
void PostgreSQL::_networksWatcher_Postgres(PGconn *conn) {
char buf[11] = {0};
std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
PGresult *res = PQexec(conn, cmd.c_str());
if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
PQclear(res);
PQfinish(conn);
exit(1);
}
PQclear(res); res = NULL;
while(_run == 1) {
if (PQstatus(conn) != CONNECTION_OK) {
fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
exit(-1);
}
PGnotify *notify = NULL;
PQconsumeInput(conn);
while ((notify = PQnotifies(conn)) != NULL) {
//fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
try {
json tmp(json::parse(notify->extra));
json &ov = tmp["old_val"];
json &nv = tmp["new_val"];
json oldConfig, newConfig;
if (ov.is_object()) oldConfig = ov;
if (nv.is_object()) newConfig = nv;
if (oldConfig.is_object()||newConfig.is_object()) {
_networkChanged(oldConfig,newConfig,(this->_ready >= 2));
}
} catch (...) {} // ignore bad records
free(notify);
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void PostgreSQL::_networksWatcher_Redis() {
char buf[11] = {0};
std::string key = "network-stream:{" + std::string(_myAddress.toString(buf)) + "}";