PostgreSQL.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "PostgreSQL.hpp"
  14. #ifdef ZT_CONTROLLER_USE_LIBPQ
  15. #include "../node/Constants.hpp"
  16. #include "EmbeddedNetworkController.hpp"
  17. #include "../version.h"
  18. #include "Redis.hpp"
  19. #include <libpq-fe.h>
  20. #include <sstream>
  21. #include <climits>
  22. using json = nlohmann::json;
  23. namespace {
  24. static const int DB_MINIMUM_VERSION = 5;
  25. static const char *_timestr()
  26. {
  27. time_t t = time(0);
  28. char *ts = ctime(&t);
  29. char *p = ts;
  30. if (!p)
  31. return "";
  32. while (*p) {
  33. if (*p == '\n') {
  34. *p = (char)0;
  35. break;
  36. }
  37. ++p;
  38. }
  39. return ts;
  40. }
  41. /*
  42. std::string join(const std::vector<std::string> &elements, const char * const separator)
  43. {
  44. switch(elements.size()) {
  45. case 0:
  46. return "";
  47. case 1:
  48. return elements[0];
  49. default:
  50. std::ostringstream os;
  51. std::copy(elements.begin(), elements.end()-1, std::ostream_iterator<std::string>(os, separator));
  52. os << *elements.rbegin();
  53. return os.str();
  54. }
  55. }
  56. */
  57. } // anonymous namespace
  58. using namespace ZeroTier;
  59. using Attrs = std::vector<std::pair<std::string, std::string>>;
  60. using Item = std::pair<std::string, Attrs>;
  61. using ItemStream = std::vector<Item>;
  62. PostgreSQL::PostgreSQL(const Identity &myId, const char *path, int listenPort, RedisConfig *rc)
  63. : DB()
  64. , _myId(myId)
  65. , _myAddress(myId.address())
  66. , _ready(0)
  67. , _connected(1)
  68. , _run(1)
  69. , _waitNoticePrinted(false)
  70. , _listenPort(listenPort)
  71. , _rc(rc)
  72. , _redis(NULL)
  73. , _cluster(NULL)
  74. {
  75. char myAddress[64];
  76. _myAddressStr = myId.address().toString(myAddress);
  77. _connString = std::string(path) + " application_name=controller_" + _myAddressStr;
  78. // Database Schema Version Check
  79. PGconn *conn = getPgConn();
  80. if (PQstatus(conn) != CONNECTION_OK) {
  81. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  82. exit(1);
  83. }
  84. PGresult *res = PQexec(conn, "SELECT version FROM ztc_database");
  85. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  86. fprintf(stderr, "Error determining database version");
  87. exit(1);
  88. }
  89. if (PQntuples(res) != 1) {
  90. fprintf(stderr, "Invalid number of db version tuples returned.");
  91. exit(1);
  92. }
  93. int dbVersion = std::stoi(PQgetvalue(res, 0, 0));
  94. if (dbVersion < DB_MINIMUM_VERSION) {
  95. 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);
  96. exit(1);
  97. }
  98. PQclear(res);
  99. res = NULL;
  100. if (_rc != NULL) {
  101. sw::redis::ConnectionOptions opts;
  102. sw::redis::ConnectionPoolOptions poolOpts;
  103. opts.host = _rc->hostname;
  104. opts.port = _rc->port;
  105. opts.password = _rc->password;
  106. opts.db = 0;
  107. poolOpts.size = 10;
  108. if (_rc->clusterMode) {
  109. fprintf(stderr, "Using Redis in Cluster Mode\n");
  110. _cluster = std::make_shared<sw::redis::RedisCluster>(opts, poolOpts);
  111. } else {
  112. fprintf(stderr, "Using Redis in Standalone Mode\n");
  113. _redis = std::make_shared<sw::redis::Redis>(opts, poolOpts);
  114. }
  115. }
  116. _readyLock.lock();
  117. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S, ::_timestr(), (unsigned long long)_myAddress.toInt());
  118. _waitNoticePrinted = true;
  119. initializeNetworks(conn);
  120. initializeMembers(conn);
  121. PQfinish(conn);
  122. conn = NULL;
  123. _heartbeatThread = std::thread(&PostgreSQL::heartbeat, this);
  124. _membersDbWatcher = std::thread(&PostgreSQL::membersDbWatcher, this);
  125. _networksDbWatcher = std::thread(&PostgreSQL::networksDbWatcher, this);
  126. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  127. _commitThread[i] = std::thread(&PostgreSQL::commitThread, this);
  128. }
  129. _onlineNotificationThread = std::thread(&PostgreSQL::onlineNotificationThread, this);
  130. }
  131. PostgreSQL::~PostgreSQL()
  132. {
  133. _run = 0;
  134. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  135. _heartbeatThread.join();
  136. _membersDbWatcher.join();
  137. _networksDbWatcher.join();
  138. _commitQueue.stop();
  139. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  140. _commitThread[i].join();
  141. }
  142. _onlineNotificationThread.join();
  143. }
  144. bool PostgreSQL::waitForReady()
  145. {
  146. while (_ready < 2) {
  147. _readyLock.lock();
  148. _readyLock.unlock();
  149. }
  150. return true;
  151. }
  152. bool PostgreSQL::isReady()
  153. {
  154. return ((_ready == 2)&&(_connected));
  155. }
  156. bool PostgreSQL::save(nlohmann::json &record,bool notifyListeners)
  157. {
  158. bool modified = false;
  159. try {
  160. if (!record.is_object())
  161. return false;
  162. const std::string objtype = record["objtype"];
  163. if (objtype == "network") {
  164. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  165. if (nwid) {
  166. nlohmann::json old;
  167. get(nwid,old);
  168. if ((!old.is_object())||(!_compareRecords(old,record))) {
  169. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  170. _commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
  171. modified = true;
  172. }
  173. }
  174. } else if (objtype == "member") {
  175. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  176. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  177. if ((id)&&(nwid)) {
  178. nlohmann::json network,old;
  179. get(nwid,network,id,old);
  180. if ((!old.is_object())||(!_compareRecords(old,record))) {
  181. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  182. _commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
  183. modified = true;
  184. }
  185. }
  186. }
  187. } catch (std::exception &e) {
  188. fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what());
  189. } catch (...) {
  190. fprintf(stderr, "Unknown error on PostgreSQL::save\n");
  191. }
  192. return modified;
  193. }
  194. void PostgreSQL::eraseNetwork(const uint64_t networkId)
  195. {
  196. char tmp2[24];
  197. waitForReady();
  198. Utils::hex(networkId, tmp2);
  199. std::pair<nlohmann::json,bool> tmp;
  200. tmp.first["id"] = tmp2;
  201. tmp.first["objtype"] = "_delete_network";
  202. tmp.second = true;
  203. _commitQueue.post(tmp);
  204. nlohmann::json nullJson;
  205. _networkChanged(tmp.first, nullJson, true);
  206. }
  207. void PostgreSQL::eraseMember(const uint64_t networkId, const uint64_t memberId)
  208. {
  209. char tmp2[24];
  210. waitForReady();
  211. std::pair<nlohmann::json,bool> tmp, nw;
  212. Utils::hex(networkId, tmp2);
  213. tmp.first["nwid"] = tmp2;
  214. Utils::hex(memberId, tmp2);
  215. tmp.first["id"] = tmp2;
  216. tmp.first["objtype"] = "_delete_member";
  217. tmp.second = true;
  218. _commitQueue.post(tmp);
  219. nlohmann::json nullJson;
  220. _memberChanged(tmp.first, nullJson, true);
  221. }
  222. void PostgreSQL::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress)
  223. {
  224. std::lock_guard<std::mutex> l(_lastOnline_l);
  225. std::pair<int64_t, InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId, memberId)];
  226. i.first = OSUtils::now();
  227. if (physicalAddress) {
  228. i.second = physicalAddress;
  229. }
  230. }
  231. void PostgreSQL::initializeNetworks(PGconn *conn)
  232. {
  233. try {
  234. if (PQstatus(conn) != CONNECTION_OK) {
  235. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  236. exit(1);
  237. }
  238. std::string setKey = "networks:{" + std::string(_myAddressStr.c_str()) + "}";
  239. if (_rc != NULL) {
  240. try {
  241. if (_rc->clusterMode) {
  242. _cluster->del(setKey);
  243. } else {
  244. _redis->del(setKey);
  245. }
  246. } catch (sw::redis::Error &e) {
  247. // del can throw an error if the key doesn't exist
  248. // swallow it and move along
  249. }
  250. }
  251. const char *params[1] = {
  252. _myAddressStr.c_str()
  253. };
  254. fprintf(stderr, "Initializing Networks...\n");
  255. PGresult *res = PQexecParams(conn, "SELECT id, EXTRACT(EPOCH FROM creation_time AT TIME ZONE 'UTC')*1000, capabilities, "
  256. "enable_broadcast, EXTRACT(EPOCH FROM last_modified AT TIME ZONE 'UTC')*1000, mtu, multicast_limit, name, private, remote_trace_level, "
  257. "remote_trace_target, revision, rules, tags, v4_assign_mode, v6_assign_mode FROM ztc_network "
  258. "WHERE deleted = false AND controller_id = $1",
  259. 1,
  260. NULL,
  261. params,
  262. NULL,
  263. NULL,
  264. 0);
  265. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  266. fprintf(stderr, "Networks Initialization Failed: %s", PQerrorMessage(conn));
  267. PQclear(res);
  268. exit(1);
  269. }
  270. int numRows = PQntuples(res);
  271. for (int i = 0; i < numRows; ++i) {
  272. json empty;
  273. json config;
  274. const char *nwidparam[1] = {
  275. PQgetvalue(res, i, 0)
  276. };
  277. std::string nwid = PQgetvalue(res, i, 0);
  278. if (_rc != NULL) {
  279. if (_rc->clusterMode) {
  280. _cluster->sadd(setKey, nwid);
  281. } else {
  282. _redis->sadd(setKey, nwid);
  283. }
  284. }
  285. config["id"] = nwid;
  286. config["nwid"] = nwid;
  287. try {
  288. config["creationTime"] = std::stoull(PQgetvalue(res, i, 1));
  289. } catch (std::exception &e) {
  290. config["creationTime"] = 0ULL;
  291. //fprintf(stderr, "Error converting creation time: %s\n", PQgetvalue(res, i, 1));
  292. }
  293. config["capabilities"] = json::parse(PQgetvalue(res, i, 2));
  294. config["enableBroadcast"] = (strcmp(PQgetvalue(res, i, 3),"t")==0);
  295. try {
  296. config["lastModified"] = std::stoull(PQgetvalue(res, i, 4));
  297. } catch (std::exception &e) {
  298. config["lastModified"] = 0ULL;
  299. //fprintf(stderr, "Error converting last modified: %s\n", PQgetvalue(res, i, 4));
  300. }
  301. try {
  302. config["mtu"] = std::stoi(PQgetvalue(res, i, 5));
  303. } catch (std::exception &e) {
  304. config["mtu"] = 2800;
  305. }
  306. try {
  307. config["multicastLimit"] = std::stoi(PQgetvalue(res, i, 6));
  308. } catch (std::exception &e) {
  309. config["multicastLimit"] = 64;
  310. }
  311. config["name"] = PQgetvalue(res, i, 7);
  312. config["private"] = (strcmp(PQgetvalue(res, i, 8),"t")==0);
  313. try {
  314. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
  315. } catch (std::exception &e) {
  316. config["remoteTraceLevel"] = 0;
  317. }
  318. config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
  319. try {
  320. config["revision"] = std::stoull(PQgetvalue(res, i, 11));
  321. } catch (std::exception &e) {
  322. config["revision"] = 0ULL;
  323. //fprintf(stderr, "Error converting revision: %s\n", PQgetvalue(res, i, 11));
  324. }
  325. config["rules"] = json::parse(PQgetvalue(res, i, 12));
  326. config["tags"] = json::parse(PQgetvalue(res, i, 13));
  327. config["v4AssignMode"] = json::parse(PQgetvalue(res, i, 14));
  328. config["v6AssignMode"] = json::parse(PQgetvalue(res, i, 15));
  329. config["objtype"] = "network";
  330. config["ipAssignmentPools"] = json::array();
  331. config["routes"] = json::array();
  332. PGresult *r2 = PQexecParams(conn,
  333. "SELECT host(ip_range_start), host(ip_range_end) FROM ztc_network_assignment_pool WHERE network_id = $1",
  334. 1,
  335. NULL,
  336. nwidparam,
  337. NULL,
  338. NULL,
  339. 0);
  340. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  341. fprintf(stderr, "ERROR: Error retreiving IP pools for network: %s\n", PQresultErrorMessage(r2));
  342. PQclear(r2);
  343. PQclear(res);
  344. exit(1);
  345. }
  346. int n = PQntuples(r2);
  347. for (int j = 0; j < n; ++j) {
  348. json ip;
  349. ip["ipRangeStart"] = PQgetvalue(r2, j, 0);
  350. ip["ipRangeEnd"] = PQgetvalue(r2, j, 1);
  351. config["ipAssignmentPools"].push_back(ip);
  352. }
  353. PQclear(r2);
  354. r2 = PQexecParams(conn,
  355. "SELECT host(address), bits, host(via) FROM ztc_network_route WHERE network_id = $1",
  356. 1,
  357. NULL,
  358. nwidparam,
  359. NULL,
  360. NULL,
  361. 0);
  362. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  363. fprintf(stderr, "ERROR: Error retreiving routes for network: %s\n", PQresultErrorMessage(r2));
  364. PQclear(r2);
  365. PQclear(res);
  366. exit(1);
  367. }
  368. n = PQntuples(r2);
  369. for (int j = 0; j < n; ++j) {
  370. std::string addr = PQgetvalue(r2, j, 0);
  371. std::string bits = PQgetvalue(r2, j, 1);
  372. std::string via = PQgetvalue(r2, j, 2);
  373. json route;
  374. route["target"] = addr + "/" + bits;
  375. if (via == "NULL") {
  376. route["via"] = nullptr;
  377. } else {
  378. route["via"] = via;
  379. }
  380. config["routes"].push_back(route);
  381. }
  382. PQclear(r2);
  383. _networkChanged(empty, config, false);
  384. }
  385. PQclear(res);
  386. if (++this->_ready == 2) {
  387. if (_waitNoticePrinted) {
  388. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  389. }
  390. _readyLock.unlock();
  391. }
  392. } catch (sw::redis::Error &e) {
  393. fprintf(stderr, "ERROR: Error initializing networks in Redis: %s\n", e.what());
  394. exit(-1);
  395. } catch (std::exception &e) {
  396. fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
  397. exit(-1);
  398. }
  399. }
  400. void PostgreSQL::initializeMembers(PGconn *conn)
  401. {
  402. try {
  403. if (PQstatus(conn) != CONNECTION_OK) {
  404. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  405. exit(1);
  406. }
  407. std::string setKeyBase = "network-nodes-all:{" + std::string(_myAddressStr.c_str()) + "}:";
  408. if (_rc != NULL) {
  409. std::lock_guard<std::mutex> l(_networks_l);
  410. for ( auto it : _networks) {
  411. uint64_t nwid_i = it.first;
  412. char nwidTmp[64] = {0};
  413. OSUtils::ztsnprintf(nwidTmp, sizeof(nwidTmp), "%.16llx", nwid_i);
  414. std::string nwid(nwidTmp);
  415. std::string key = setKeyBase + nwid;
  416. if (_rc->clusterMode) {
  417. try {
  418. _cluster->del(key);
  419. } catch (...) {}
  420. } else {
  421. try {
  422. _redis->del(key);
  423. } catch (...) {}
  424. }
  425. }
  426. }
  427. const char *params[1] = {
  428. _myAddressStr.c_str()
  429. };
  430. fprintf(stderr, "Initializing Members...\n");
  431. PGresult *res = PQexecParams(conn,
  432. "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, "
  433. " EXTRACT(EPOCH FROM m.last_authorized_time AT TIME ZONE 'UTC')*1000, "
  434. " EXTRACT(EPOCH FROM m.last_deauthorized_time AT TIME ZONE 'UTC')*1000, "
  435. " m.remote_trace_level, m.remote_trace_target, m.tags, m.v_major, m.v_minor, m.v_rev, m.v_proto, "
  436. " m.no_auto_assign_ips, m.revision "
  437. "FROM ztc_member m "
  438. "INNER JOIN ztc_network n "
  439. " ON n.id = m.network_id "
  440. "WHERE n.controller_id = $1 AND m.deleted = false",
  441. 1,
  442. NULL,
  443. params,
  444. NULL,
  445. NULL,
  446. 0);
  447. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  448. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  449. PQclear(res);
  450. exit(1);
  451. }
  452. int numRows = PQntuples(res);
  453. for (int i = 0; i < numRows; ++i) {
  454. json empty;
  455. json config;
  456. std::string memberId(PQgetvalue(res, i, 0));
  457. std::string networkId(PQgetvalue(res, i, 1));
  458. if (_rc != NULL) {
  459. if (_rc->clusterMode) {
  460. _cluster->sadd(setKeyBase + networkId, memberId);
  461. } else {
  462. _redis->sadd(setKeyBase + networkId, memberId);
  463. }
  464. }
  465. std::string ctime = PQgetvalue(res, i, 5);
  466. config["id"] = memberId;
  467. config["nwid"] = networkId;
  468. config["activeBridge"] = (strcmp(PQgetvalue(res, i, 2), "t") == 0);
  469. config["authorized"] = (strcmp(PQgetvalue(res, i, 3), "t") == 0);
  470. try {
  471. config["capabilities"] = json::parse(PQgetvalue(res, i, 4));
  472. } catch (std::exception &e) {
  473. config["capabilities"] = json::array();
  474. }
  475. try {
  476. config["creationTime"] = std::stoull(PQgetvalue(res, i, 5));
  477. } catch (std::exception &e) {
  478. config["creationTime"] = 0ULL;
  479. //fprintf(stderr, "Error upding creation time (member): %s\n", PQgetvalue(res, i, 5));
  480. }
  481. config["identity"] = PQgetvalue(res, i, 6);
  482. try {
  483. config["lastAuthorizedTime"] = std::stoull(PQgetvalue(res, i, 7));
  484. } catch(std::exception &e) {
  485. config["lastAuthorizedTime"] = 0ULL;
  486. //fprintf(stderr, "Error updating last auth time (member): %s\n", PQgetvalue(res, i, 7));
  487. }
  488. try {
  489. config["lastDeauthorizedTime"] = std::stoull(PQgetvalue(res, i, 8));
  490. } catch( std::exception &e) {
  491. config["lastDeauthorizedTime"] = 0ULL;
  492. //fprintf(stderr, "Error updating last deauth time (member): %s\n", PQgetvalue(res, i, 8));
  493. }
  494. try {
  495. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
  496. } catch (std::exception &e) {
  497. config["remoteTraceLevel"] = 0;
  498. }
  499. config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
  500. try {
  501. config["tags"] = json::parse(PQgetvalue(res, i, 11));
  502. } catch (std::exception &e) {
  503. config["tags"] = json::array();
  504. }
  505. try {
  506. config["vMajor"] = std::stoi(PQgetvalue(res, i, 12));
  507. } catch(std::exception &e) {
  508. config["vMajor"] = -1;
  509. }
  510. try {
  511. config["vMinor"] = std::stoi(PQgetvalue(res, i, 13));
  512. } catch (std::exception &e) {
  513. config["vMinor"] = -1;
  514. }
  515. try {
  516. config["vRev"] = std::stoi(PQgetvalue(res, i, 14));
  517. } catch (std::exception &e) {
  518. config["vRev"] = -1;
  519. }
  520. try {
  521. config["vProto"] = std::stoi(PQgetvalue(res, i, 15));
  522. } catch (std::exception &e) {
  523. config["vProto"] = -1;
  524. }
  525. config["noAutoAssignIps"] = (strcmp(PQgetvalue(res, i, 16), "t") == 0);
  526. try {
  527. config["revision"] = std::stoull(PQgetvalue(res, i, 17));
  528. } catch (std::exception &e) {
  529. config["revision"] = 0ULL;
  530. //fprintf(stderr, "Error updating revision (member): %s\n", PQgetvalue(res, i, 17));
  531. }
  532. config["objtype"] = "member";
  533. config["ipAssignments"] = json::array();
  534. const char *p2[2] = {
  535. memberId.c_str(),
  536. networkId.c_str()
  537. };
  538. PGresult *r2 = PQexecParams(conn,
  539. "SELECT DISTINCT address FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  540. 2,
  541. NULL,
  542. p2,
  543. NULL,
  544. NULL,
  545. 0);
  546. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  547. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  548. PQclear(r2);
  549. PQclear(res);
  550. exit(1);
  551. }
  552. int n = PQntuples(r2);
  553. for (int j = 0; j < n; ++j) {
  554. std::string ipaddr = PQgetvalue(r2, j, 0);
  555. std::size_t pos = ipaddr.find('/');
  556. if (pos != std::string::npos) {
  557. ipaddr = ipaddr.substr(0, pos);
  558. }
  559. config["ipAssignments"].push_back(ipaddr);
  560. }
  561. if (_rc != NULL) {
  562. if (_rc->clusterMode) {
  563. _cluster->sadd(setKeyBase + networkId, memberId);
  564. } else {
  565. _redis->sadd(setKeyBase + networkId, memberId);
  566. }
  567. }
  568. _memberChanged(empty, config, false);
  569. }
  570. PQclear(res);
  571. if (++this->_ready == 2) {
  572. if (_waitNoticePrinted) {
  573. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  574. }
  575. _readyLock.unlock();
  576. }
  577. } catch (sw::redis::Error &e) {
  578. fprintf(stderr, "ERROR: Error initializing members (redis): %s\n", e.what());
  579. } catch (std::exception &e) {
  580. fprintf(stderr, "ERROR: Error initializing members: %s\n", e.what());
  581. exit(-1);
  582. }
  583. }
  584. void PostgreSQL::heartbeat()
  585. {
  586. char publicId[1024];
  587. char hostnameTmp[1024];
  588. _myId.toString(false,publicId);
  589. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  590. hostnameTmp[0] = (char)0;
  591. } else {
  592. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  593. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  594. hostnameTmp[i] = (char)0;
  595. break;
  596. }
  597. }
  598. }
  599. const char *controllerId = _myAddressStr.c_str();
  600. const char *publicIdentity = publicId;
  601. const char *hostname = hostnameTmp;
  602. PGconn *conn = getPgConn();
  603. if (PQstatus(conn) == CONNECTION_BAD) {
  604. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  605. PQfinish(conn);
  606. exit(1);
  607. }
  608. while (_run == 1) {
  609. if(PQstatus(conn) != CONNECTION_OK) {
  610. fprintf(stderr, "%s heartbeat thread lost connection to Database\n", _myAddressStr.c_str());
  611. PQfinish(conn);
  612. exit(6);
  613. }
  614. int64_t ts = OSUtils::now();
  615. if (conn) {
  616. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  617. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  618. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  619. std::string build = std::to_string(ZEROTIER_ONE_VERSION_BUILD);
  620. std::string now = std::to_string(ts);
  621. std::string host_port = std::to_string(_listenPort);
  622. std::string use_redis = (_rc != NULL) ? "true" : "false";
  623. const char *values[10] = {
  624. controllerId,
  625. hostname,
  626. now.c_str(),
  627. publicIdentity,
  628. major.c_str(),
  629. minor.c_str(),
  630. rev.c_str(),
  631. build.c_str(),
  632. host_port.c_str(),
  633. use_redis.c_str()
  634. };
  635. PGresult *res = PQexecParams(conn,
  636. "INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build, host_port, use_redis) "
  637. "VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8, $9, $10) "
  638. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  639. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  640. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev, host_port = EXCLUDED.host_port, "
  641. "use_redis = EXCLUDED.use_redis",
  642. 10, // number of parameters
  643. NULL, // oid field. ignore
  644. values, // values for substitution
  645. NULL, // lengths in bytes of each value
  646. NULL, // binary?
  647. 0);
  648. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  649. fprintf(stderr, "Heartbeat Update Failed: %s\n", PQresultErrorMessage(res));
  650. }
  651. PQclear(res);
  652. }
  653. if (_rc != NULL) {
  654. if (_rc->clusterMode) {
  655. _cluster->zadd("controllers", controllerId, ts);
  656. } else {
  657. _redis->zadd("controllers", controllerId, ts);
  658. }
  659. }
  660. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  661. }
  662. PQfinish(conn);
  663. conn = NULL;
  664. fprintf(stderr, "Exited heartbeat thread\n");
  665. }
  666. void PostgreSQL::membersDbWatcher()
  667. {
  668. PGconn *conn = getPgConn(NO_OVERRIDE);
  669. if (PQstatus(conn) == CONNECTION_BAD) {
  670. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  671. PQfinish(conn);
  672. exit(1);
  673. }
  674. if (_rc) {
  675. PQfinish(conn);
  676. conn = NULL;
  677. _membersWatcher_Redis();
  678. } else {
  679. _membersWatcher_Postgres(conn);
  680. PQfinish(conn);
  681. conn = NULL;
  682. }
  683. if (_run == 1) {
  684. fprintf(stderr, "ERROR: %s membersDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  685. exit(9);
  686. }
  687. fprintf(stderr, "Exited membersDbWatcher\n");
  688. }
  689. void PostgreSQL::_membersWatcher_Postgres(PGconn *conn) {
  690. char buf[11] = {0};
  691. std::string cmd = "LISTEN member_" + std::string(_myAddress.toString(buf));
  692. PGresult *res = PQexec(conn, cmd.c_str());
  693. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  694. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  695. PQclear(res);
  696. PQfinish(conn);
  697. exit(1);
  698. }
  699. PQclear(res); res = NULL;
  700. while(_run == 1) {
  701. if (PQstatus(conn) != CONNECTION_OK) {
  702. fprintf(stderr, "ERROR: Member Watcher lost connection to Postgres.");
  703. exit(-1);
  704. }
  705. PGnotify *notify = NULL;
  706. PQconsumeInput(conn);
  707. while ((notify = PQnotifies(conn)) != NULL) {
  708. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  709. try {
  710. json tmp(json::parse(notify->extra));
  711. json &ov = tmp["old_val"];
  712. json &nv = tmp["new_val"];
  713. json oldConfig, newConfig;
  714. if (ov.is_object()) oldConfig = ov;
  715. if (nv.is_object()) newConfig = nv;
  716. if (oldConfig.is_object() || newConfig.is_object()) {
  717. _memberChanged(oldConfig,newConfig,(this->_ready>=2));
  718. }
  719. } catch (...) {} // ignore bad records
  720. free(notify);
  721. }
  722. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  723. }
  724. }
  725. void PostgreSQL::_membersWatcher_Redis() {
  726. char buf[11] = {0};
  727. std::string key = "member-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  728. while (_run == 1) {
  729. try {
  730. json tmp;
  731. std::unordered_map<std::string, ItemStream> result;
  732. if (_rc->clusterMode) {
  733. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  734. } else {
  735. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  736. }
  737. if (!result.empty()) {
  738. for (auto element : result) {
  739. #ifdef ZT_TRACE
  740. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  741. #endif
  742. for (auto rec : element.second) {
  743. std::string id = rec.first;
  744. auto attrs = rec.second;
  745. #ifdef ZT_TRACE
  746. fprintf(stdout, "Record ID: %s\n", id.c_str());
  747. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  748. #endif
  749. for (auto a : attrs) {
  750. #ifdef ZT_TRACE
  751. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  752. #endif
  753. try {
  754. tmp = json::parse(a.second);
  755. json &ov = tmp["old_val"];
  756. json &nv = tmp["new_val"];
  757. json oldConfig, newConfig;
  758. if (ov.is_object()) oldConfig = ov;
  759. if (nv.is_object()) newConfig = nv;
  760. if (oldConfig.is_object()||newConfig.is_object()) {
  761. _memberChanged(oldConfig,newConfig,(this->_ready >= 2));
  762. }
  763. } catch (...) {
  764. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  765. }
  766. }
  767. if (_rc->clusterMode) {
  768. _cluster->xdel(key, id);
  769. } else {
  770. _redis->xdel(key, id);
  771. }
  772. }
  773. }
  774. }
  775. } catch (sw::redis::Error &e) {
  776. fprintf(stderr, "Error in Redis members watcher: %s\n", e.what());
  777. }
  778. }
  779. fprintf(stderr, "membersWatcher ended\n");
  780. }
  781. void PostgreSQL::networksDbWatcher()
  782. {
  783. PGconn *conn = getPgConn(NO_OVERRIDE);
  784. if (PQstatus(conn) == CONNECTION_BAD) {
  785. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  786. PQfinish(conn);
  787. exit(1);
  788. }
  789. if (_rc) {
  790. PQfinish(conn);
  791. conn = NULL;
  792. _networksWatcher_Redis();
  793. } else {
  794. _networksWatcher_Postgres(conn);
  795. PQfinish(conn);
  796. conn = NULL;
  797. }
  798. if (_run == 1) {
  799. fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  800. exit(8);
  801. }
  802. fprintf(stderr, "Exited networksDbWatcher\n");
  803. }
  804. void PostgreSQL::_networksWatcher_Postgres(PGconn *conn) {
  805. char buf[11] = {0};
  806. std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
  807. PGresult *res = PQexec(conn, cmd.c_str());
  808. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  809. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  810. PQclear(res);
  811. PQfinish(conn);
  812. exit(1);
  813. }
  814. PQclear(res); res = NULL;
  815. while(_run == 1) {
  816. if (PQstatus(conn) != CONNECTION_OK) {
  817. fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
  818. exit(-1);
  819. }
  820. PGnotify *notify = NULL;
  821. PQconsumeInput(conn);
  822. while ((notify = PQnotifies(conn)) != NULL) {
  823. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  824. try {
  825. json tmp(json::parse(notify->extra));
  826. json &ov = tmp["old_val"];
  827. json &nv = tmp["new_val"];
  828. json oldConfig, newConfig;
  829. if (ov.is_object()) oldConfig = ov;
  830. if (nv.is_object()) newConfig = nv;
  831. if (oldConfig.is_object()||newConfig.is_object()) {
  832. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  833. }
  834. } catch (...) {} // ignore bad records
  835. free(notify);
  836. }
  837. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  838. }
  839. }
  840. void PostgreSQL::_networksWatcher_Redis() {
  841. char buf[11] = {0};
  842. std::string key = "network-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  843. while (_run == 1) {
  844. try {
  845. json tmp;
  846. std::unordered_map<std::string, ItemStream> result;
  847. if (_rc->clusterMode) {
  848. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  849. } else {
  850. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  851. }
  852. if (!result.empty()) {
  853. for (auto element : result) {
  854. #ifdef ZT_TRACE
  855. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  856. #endif
  857. for (auto rec : element.second) {
  858. std::string id = rec.first;
  859. auto attrs = rec.second;
  860. #ifdef ZT_TRACE
  861. fprintf(stdout, "Record ID: %s\n", id.c_str());
  862. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  863. #endif
  864. for (auto a : attrs) {
  865. #ifdef ZT_TRACE
  866. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  867. #endif
  868. try {
  869. tmp = json::parse(a.second);
  870. json &ov = tmp["old_val"];
  871. json &nv = tmp["new_val"];
  872. json oldConfig, newConfig;
  873. if (ov.is_object()) oldConfig = ov;
  874. if (nv.is_object()) newConfig = nv;
  875. if (oldConfig.is_object()||newConfig.is_object()) {
  876. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  877. }
  878. } catch (...) {
  879. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  880. }
  881. }
  882. if (_rc->clusterMode) {
  883. _cluster->xdel(key, id);
  884. } else {
  885. _redis->xdel(key, id);
  886. }
  887. }
  888. }
  889. }
  890. } catch (sw::redis::Error &e) {
  891. fprintf(stderr, "Error in Redis networks watcher: %s\n", e.what());
  892. }
  893. }
  894. fprintf(stderr, "networksWatcher ended\n");
  895. }
  896. void PostgreSQL::commitThread()
  897. {
  898. PGconn *conn = getPgConn();
  899. if (PQstatus(conn) == CONNECTION_BAD) {
  900. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  901. PQfinish(conn);
  902. exit(1);
  903. }
  904. std::pair<nlohmann::json,bool> qitem;
  905. while(_commitQueue.get(qitem)&(_run == 1)) {
  906. if (!qitem.first.is_object()) {
  907. continue;
  908. }
  909. if (PQstatus(conn) == CONNECTION_BAD) {
  910. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  911. PQfinish(conn);
  912. exit(1);
  913. }
  914. try {
  915. nlohmann::json *config = &(qitem.first);
  916. const std::string objtype = (*config)["objtype"];
  917. if (objtype == "member") {
  918. try {
  919. std::string memberId = (*config)["id"];
  920. std::string networkId = (*config)["nwid"];
  921. std::string identity = (*config)["identity"];
  922. std::string target = "NULL";
  923. if (!(*config)["remoteTraceTarget"].is_null()) {
  924. target = (*config)["remoteTraceTarget"];
  925. }
  926. std::string caps = OSUtils::jsonDump((*config)["capabilities"], -1);
  927. std::string lastAuthTime = std::to_string((long long)(*config)["lastAuthorizedTime"]);
  928. std::string lastDeauthTime = std::to_string((long long)(*config)["lastDeauthorizedTime"]);
  929. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  930. std::string rev = std::to_string((unsigned long long)(*config)["revision"]);
  931. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  932. std::string vmajor = std::to_string((int)(*config)["vMajor"]);
  933. std::string vminor = std::to_string((int)(*config)["vMinor"]);
  934. std::string vrev = std::to_string((int)(*config)["vRev"]);
  935. std::string vproto = std::to_string((int)(*config)["vProto"]);
  936. const char *values[19] = {
  937. memberId.c_str(),
  938. networkId.c_str(),
  939. ((*config)["activeBridge"] ? "true" : "false"),
  940. ((*config)["authorized"] ? "true" : "false"),
  941. caps.c_str(),
  942. identity.c_str(),
  943. lastAuthTime.c_str(),
  944. lastDeauthTime.c_str(),
  945. ((*config)["noAutoAssignIps"] ? "true" : "false"),
  946. rtraceLevel.c_str(),
  947. (target == "NULL") ? NULL : target.c_str(),
  948. rev.c_str(),
  949. tags.c_str(),
  950. vmajor.c_str(),
  951. vminor.c_str(),
  952. vrev.c_str(),
  953. vproto.c_str()
  954. };
  955. PGresult *res = PQexecParams(conn,
  956. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  957. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  958. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  959. "VALUES ($1, $2, $3, $4, $5, $6, "
  960. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  961. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  962. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  963. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  964. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  965. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  966. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  967. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  968. 17,
  969. NULL,
  970. values,
  971. NULL,
  972. NULL,
  973. 0);
  974. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  975. fprintf(stderr, "ERROR: Error updating member: %s\n", PQresultErrorMessage(res));
  976. fprintf(stderr, "%s", OSUtils::jsonDump(*config, 2).c_str());
  977. PQclear(res);
  978. delete config;
  979. config = nullptr;
  980. continue;
  981. }
  982. PQclear(res);
  983. res = PQexec(conn, "BEGIN");
  984. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  985. fprintf(stderr, "ERROR: Error beginning transaction: %s\n", PQresultErrorMessage(res));
  986. PQclear(res);
  987. delete config;
  988. config = nullptr;
  989. continue;
  990. }
  991. PQclear(res);
  992. const char *v2[2] = {
  993. memberId.c_str(),
  994. networkId.c_str()
  995. };
  996. res = PQexecParams(conn,
  997. "DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  998. 2,
  999. NULL,
  1000. v2,
  1001. NULL,
  1002. NULL,
  1003. 0);
  1004. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1005. fprintf(stderr, "ERROR: Error updating IP address assignments: %s\n", PQresultErrorMessage(res));
  1006. PQclear(res);
  1007. PQclear(PQexec(conn, "ROLLBACK"));;
  1008. delete config;
  1009. config = nullptr;
  1010. continue;
  1011. }
  1012. PQclear(res);
  1013. std::vector<std::string> assignments;
  1014. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  1015. std::string addr = *i;
  1016. if (std::find(assignments.begin(), assignments.end(), addr) != assignments.end()) {
  1017. continue;
  1018. }
  1019. const char *v3[3] = {
  1020. memberId.c_str(),
  1021. networkId.c_str(),
  1022. addr.c_str()
  1023. };
  1024. res = PQexecParams(conn,
  1025. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3) ON CONFLICT (network_id, member_id, address) DO NOTHING",
  1026. 3,
  1027. NULL,
  1028. v3,
  1029. NULL,
  1030. NULL,
  1031. 0);
  1032. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1033. fprintf(stderr, "ERROR: Error setting IP addresses for member: %s\n", PQresultErrorMessage(res));
  1034. PQclear(res);
  1035. PQclear(PQexec(conn, "ROLLBACK"));
  1036. break;;
  1037. }
  1038. assignments.push_back(addr);
  1039. }
  1040. res = PQexec(conn, "COMMIT");
  1041. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1042. fprintf(stderr, "ERROR: Error committing ip address data: %s\n", PQresultErrorMessage(res));
  1043. }
  1044. PQclear(res);
  1045. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  1046. const uint64_t memberidInt = OSUtils::jsonIntHex((*config)["id"], 0ULL);
  1047. if (nwidInt && memberidInt) {
  1048. nlohmann::json nwOrig;
  1049. nlohmann::json memOrig;
  1050. nlohmann::json memNew(*config);
  1051. get(nwidInt, nwOrig, memberidInt, memOrig);
  1052. _memberChanged(memOrig, memNew, qitem.second);
  1053. } else {
  1054. fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %llu-%llu\n", (unsigned long long)nwidInt, (unsigned long long)memberidInt);
  1055. }
  1056. } catch (std::exception &e) {
  1057. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  1058. }
  1059. } else if (objtype == "network") {
  1060. try {
  1061. std::string id = (*config)["id"];
  1062. std::string controllerId = _myAddressStr.c_str();
  1063. std::string name = (*config)["name"];
  1064. std::string remoteTraceTarget("NULL");
  1065. if (!(*config)["remoteTraceTarget"].is_null()) {
  1066. remoteTraceTarget = (*config)["remoteTraceTarget"];
  1067. }
  1068. std::string rulesSource;
  1069. if ((*config)["rulesSource"].is_string()) {
  1070. rulesSource = (*config)["rulesSource"];
  1071. }
  1072. std::string caps = OSUtils::jsonDump((*config)["capabilitles"], -1);
  1073. std::string now = std::to_string(OSUtils::now());
  1074. std::string mtu = std::to_string((int)(*config)["mtu"]);
  1075. std::string mcastLimit = std::to_string((int)(*config)["multicastLimit"]);
  1076. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  1077. std::string rules = OSUtils::jsonDump((*config)["rules"], -1);
  1078. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  1079. std::string v4mode = OSUtils::jsonDump((*config)["v4AssignMode"],-1);
  1080. std::string v6mode = OSUtils::jsonDump((*config)["v6AssignMode"], -1);
  1081. bool enableBroadcast = (*config)["enableBroadcast"];
  1082. bool isPrivate = (*config)["private"];
  1083. const char *values[16] = {
  1084. id.c_str(),
  1085. controllerId.c_str(),
  1086. caps.c_str(),
  1087. enableBroadcast ? "true" : "false",
  1088. now.c_str(),
  1089. mtu.c_str(),
  1090. mcastLimit.c_str(),
  1091. name.c_str(),
  1092. isPrivate ? "true" : "false",
  1093. rtraceLevel.c_str(),
  1094. (remoteTraceTarget == "NULL" ? NULL : remoteTraceTarget.c_str()),
  1095. rules.c_str(),
  1096. rulesSource.c_str(),
  1097. tags.c_str(),
  1098. v4mode.c_str(),
  1099. v6mode.c_str(),
  1100. };
  1101. // This ugly query exists because when we want to mirror networks to/from
  1102. // another data store (e.g. FileDB or LFDB) it is possible to get a network
  1103. // that doesn't exist in Central's database. This does an upsert and sets
  1104. // the owner_id to the "first" global admin in the user DB if the record
  1105. // did not previously exist. If the record already exists owner_id is left
  1106. // unchanged, so owner_id should be left out of the update clause.
  1107. PGresult *res = PQexecParams(conn,
  1108. "INSERT INTO ztc_network (id, creation_time, owner_id, controller_id, capabilities, enable_broadcast, "
  1109. "last_modified, mtu, multicast_limit, name, private, "
  1110. "remote_trace_level, remote_trace_target, rules, rules_source, "
  1111. "tags, v4_assign_mode, v6_assign_mode) VALUES ("
  1112. "$1, TO_TIMESTAMP($5::double precision/1000), "
  1113. "(SELECT user_id AS owner_id FROM ztc_global_permissions WHERE authorize = true AND del = true AND modify = true AND read = true LIMIT 1),"
  1114. "$2, $3, $4, TO_TIMESTAMP($5::double precision/1000), "
  1115. "$6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) "
  1116. "ON CONFLICT (id) DO UPDATE set controller_id = EXCLUDED.controller_id, "
  1117. "capabilities = EXCLUDED.capabilities, enable_broadcast = EXCLUDED.enable_broadcast, "
  1118. "last_modified = EXCLUDED.last_modified, mtu = EXCLUDED.mtu, "
  1119. "multicast_limit = EXCLUDED.multicast_limit, name = EXCLUDED.name, "
  1120. "private = EXCLUDED.private, remote_trace_level = EXCLUDED.remote_trace_level, "
  1121. "remote_trace_target = EXCLUDED.remote_trace_target, rules = EXCLUDED.rules, "
  1122. "rules_source = EXCLUDED.rules_source, tags = EXCLUDED.tags, "
  1123. "v4_assign_mode = EXCLUDED.v4_assign_mode, v6_assign_mode = EXCLUDED.v6_assign_mode",
  1124. 16,
  1125. NULL,
  1126. values,
  1127. NULL,
  1128. NULL,
  1129. 0);
  1130. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1131. fprintf(stderr, "ERROR: Error updating network record: %s\n", PQresultErrorMessage(res));
  1132. PQclear(res);
  1133. delete config;
  1134. config = nullptr;
  1135. continue;
  1136. }
  1137. PQclear(res);
  1138. res = PQexec(conn, "BEGIN");
  1139. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1140. fprintf(stderr, "ERROR: Error beginnning transaction: %s\n", PQresultErrorMessage(res));
  1141. PQclear(res);
  1142. delete config;
  1143. config = nullptr;
  1144. continue;
  1145. }
  1146. PQclear(res);
  1147. const char *params[1] = {
  1148. id.c_str()
  1149. };
  1150. res = PQexecParams(conn,
  1151. "DELETE FROM ztc_network_assignment_pool WHERE network_id = $1",
  1152. 1,
  1153. NULL,
  1154. params,
  1155. NULL,
  1156. NULL,
  1157. 0);
  1158. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1159. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  1160. PQclear(res);
  1161. PQclear(PQexec(conn, "ROLLBACK"));
  1162. delete config;
  1163. config = nullptr;
  1164. continue;
  1165. }
  1166. PQclear(res);
  1167. auto pool = (*config)["ipAssignmentPools"];
  1168. bool err = false;
  1169. for (auto i = pool.begin(); i != pool.end(); ++i) {
  1170. std::string start = (*i)["ipRangeStart"];
  1171. std::string end = (*i)["ipRangeEnd"];
  1172. const char *p[3] = {
  1173. id.c_str(),
  1174. start.c_str(),
  1175. end.c_str()
  1176. };
  1177. res = PQexecParams(conn,
  1178. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  1179. "VALUES ($1, $2, $3)",
  1180. 3,
  1181. NULL,
  1182. p,
  1183. NULL,
  1184. NULL,
  1185. 0);
  1186. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1187. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  1188. PQclear(res);
  1189. err = true;
  1190. break;
  1191. }
  1192. PQclear(res);
  1193. }
  1194. if (err) {
  1195. PQclear(PQexec(conn, "ROLLBACK"));
  1196. delete config;
  1197. config = nullptr;
  1198. continue;
  1199. }
  1200. res = PQexecParams(conn,
  1201. "DELETE FROM ztc_network_route WHERE network_id = $1",
  1202. 1,
  1203. NULL,
  1204. params,
  1205. NULL,
  1206. NULL,
  1207. 0);
  1208. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1209. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  1210. PQclear(res);
  1211. PQclear(PQexec(conn, "ROLLBACK"));
  1212. delete config;
  1213. config = nullptr;
  1214. continue;
  1215. }
  1216. auto routes = (*config)["routes"];
  1217. err = false;
  1218. for (auto i = routes.begin(); i != routes.end(); ++i) {
  1219. std::string t = (*i)["target"];
  1220. std::vector<std::string> target;
  1221. std::istringstream f(t);
  1222. std::string s;
  1223. while(std::getline(f, s, '/')) {
  1224. target.push_back(s);
  1225. }
  1226. if (target.empty() || target.size() != 2) {
  1227. continue;
  1228. }
  1229. std::string targetAddr = target[0];
  1230. std::string targetBits = target[1];
  1231. std::string via = "NULL";
  1232. if (!(*i)["via"].is_null()) {
  1233. via = (*i)["via"];
  1234. }
  1235. const char *p[4] = {
  1236. id.c_str(),
  1237. targetAddr.c_str(),
  1238. targetBits.c_str(),
  1239. (via == "NULL" ? NULL : via.c_str()),
  1240. };
  1241. res = PQexecParams(conn,
  1242. "INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  1243. 4,
  1244. NULL,
  1245. p,
  1246. NULL,
  1247. NULL,
  1248. 0);
  1249. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1250. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  1251. PQclear(res);
  1252. err = true;
  1253. break;
  1254. }
  1255. PQclear(res);
  1256. }
  1257. if (err) {
  1258. PQclear(PQexec(conn, "ROLLBACK"));
  1259. delete config;
  1260. config = nullptr;
  1261. continue;
  1262. }
  1263. res = PQexec(conn, "COMMIT");
  1264. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1265. fprintf(stderr, "ERROR: Error committing network update: %s\n", PQresultErrorMessage(res));
  1266. }
  1267. PQclear(res);
  1268. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  1269. if (nwidInt) {
  1270. nlohmann::json nwOrig;
  1271. nlohmann::json nwNew(*config);
  1272. get(nwidInt, nwOrig);
  1273. _networkChanged(nwOrig, nwNew, qitem.second);
  1274. } else {
  1275. fprintf(stderr, "Can't notify network changed: %llu\n", (unsigned long long)nwidInt);
  1276. }
  1277. } catch (std::exception &e) {
  1278. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  1279. }
  1280. if (_rc != NULL) {
  1281. try {
  1282. std::string id = (*config)["id"];
  1283. std::string controllerId = _myAddressStr.c_str();
  1284. std::string key = "networks:{" + controllerId + "}";
  1285. if (_rc->clusterMode) {
  1286. _cluster->sadd(key, id);
  1287. } else {
  1288. _redis->sadd(key, id);
  1289. }
  1290. } catch (sw::redis::Error &e) {
  1291. fprintf(stderr, "ERROR: Error adding network to Redis: %s\n", e.what());
  1292. }
  1293. }
  1294. } else if (objtype == "_delete_network") {
  1295. try {
  1296. std::string networkId = (*config)["nwid"];
  1297. const char *values[1] = {
  1298. networkId.c_str()
  1299. };
  1300. PGresult * res = PQexecParams(conn,
  1301. "UPDATE ztc_network SET deleted = true WHERE id = $1",
  1302. 1,
  1303. NULL,
  1304. values,
  1305. NULL,
  1306. NULL,
  1307. 0);
  1308. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1309. fprintf(stderr, "ERROR: Error deleting network: %s\n", PQresultErrorMessage(res));
  1310. }
  1311. PQclear(res);
  1312. } catch (std::exception &e) {
  1313. fprintf(stderr, "ERROR: Error deleting network: %s\n", e.what());
  1314. }
  1315. if (_rc != NULL) {
  1316. try {
  1317. std::string id = (*config)["id"];
  1318. std::string controllerId = _myAddressStr.c_str();
  1319. std::string key = "networks:{" + controllerId + "}";
  1320. if (_rc->clusterMode) {
  1321. _cluster->srem(key, id);
  1322. } else {
  1323. _redis->srem(key, id);
  1324. }
  1325. } catch (sw::redis::Error &e) {
  1326. fprintf(stderr, "ERROR: Error adding network to Redis: %s\n", e.what());
  1327. }
  1328. }
  1329. } else if (objtype == "_delete_member") {
  1330. try {
  1331. std::string memberId = (*config)["id"];
  1332. std::string networkId = (*config)["nwid"];
  1333. const char *values[2] = {
  1334. memberId.c_str(),
  1335. networkId.c_str()
  1336. };
  1337. PGresult *res = PQexecParams(conn,
  1338. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  1339. 2,
  1340. NULL,
  1341. values,
  1342. NULL,
  1343. NULL,
  1344. 0);
  1345. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1346. fprintf(stderr, "ERROR: Error deleting member: %s\n", PQresultErrorMessage(res));
  1347. }
  1348. PQclear(res);
  1349. } catch (std::exception &e) {
  1350. fprintf(stderr, "ERROR: Error deleting member: %s\n", e.what());
  1351. }
  1352. if (_rc != NULL) {
  1353. try {
  1354. std::string memberId = (*config)["id"];
  1355. std::string networkId = (*config)["nwid"];
  1356. std::string controllerId = _myAddressStr.c_str();
  1357. std::string key = "network-nodes-all:{" + controllerId + "}:" + networkId;
  1358. if (_rc->clusterMode) {
  1359. _cluster->srem(key, memberId);
  1360. } else {
  1361. _redis->srem(key, memberId);
  1362. }
  1363. } catch (sw::redis::Error &e) {
  1364. fprintf(stderr, "ERROR: Error deleting member from Redis: %s\n", e.what());
  1365. }
  1366. }
  1367. } else {
  1368. fprintf(stderr, "ERROR: unknown objtype");
  1369. }
  1370. } catch (std::exception &e) {
  1371. fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
  1372. }
  1373. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1374. }
  1375. PQfinish(conn);
  1376. if (_run == 1) {
  1377. fprintf(stderr, "ERROR: %s commitThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1378. exit(7);
  1379. }
  1380. fprintf(stderr, "commitThread finished\n");
  1381. }
  1382. void PostgreSQL::onlineNotificationThread()
  1383. {
  1384. waitForReady();
  1385. if (_rc != NULL) {
  1386. onlineNotification_Redis();
  1387. } else {
  1388. onlineNotification_Postgres();
  1389. }
  1390. }
  1391. void PostgreSQL::onlineNotification_Postgres()
  1392. {
  1393. PGconn *conn = getPgConn();
  1394. if (PQstatus(conn) == CONNECTION_BAD) {
  1395. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  1396. PQfinish(conn);
  1397. exit(1);
  1398. }
  1399. _connected = 1;
  1400. nlohmann::json jtmp1, jtmp2;
  1401. while (_run == 1) {
  1402. if (PQstatus(conn) != CONNECTION_OK) {
  1403. fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres.");
  1404. PQfinish(conn);
  1405. exit(5);
  1406. }
  1407. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1408. {
  1409. std::lock_guard<std::mutex> l(_lastOnline_l);
  1410. lastOnline.swap(_lastOnline);
  1411. }
  1412. PGresult *res = NULL;
  1413. std::stringstream memberUpdate;
  1414. memberUpdate << "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ";
  1415. bool firstRun = true;
  1416. bool memberAdded = false;
  1417. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1418. uint64_t nwid_i = i->first.first;
  1419. char nwidTmp[64];
  1420. char memTmp[64];
  1421. char ipTmp[64];
  1422. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1423. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  1424. if(!get(nwid_i, jtmp1, i->first.second, jtmp2)) {
  1425. continue; // skip non existent networks/members
  1426. }
  1427. std::string networkId(nwidTmp);
  1428. std::string memberId(memTmp);
  1429. const char *qvals[2] = {
  1430. networkId.c_str(),
  1431. memberId.c_str()
  1432. };
  1433. res = PQexecParams(conn,
  1434. "SELECT id, network_id FROM ztc_member WHERE network_id = $1 AND id = $2",
  1435. 2,
  1436. NULL,
  1437. qvals,
  1438. NULL,
  1439. NULL,
  1440. 0);
  1441. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  1442. fprintf(stderr, "Member count failed: %s", PQerrorMessage(conn));
  1443. PQclear(res);
  1444. continue;
  1445. }
  1446. int nrows = PQntuples(res);
  1447. PQclear(res);
  1448. if (nrows == 1) {
  1449. int64_t ts = i->second.first;
  1450. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1451. std::string timestamp = std::to_string(ts);
  1452. if (firstRun) {
  1453. firstRun = false;
  1454. } else {
  1455. memberUpdate << ", ";
  1456. }
  1457. memberUpdate << "('" << networkId << "', '" << memberId << "', ";
  1458. if (ipAddr.empty()) {
  1459. memberUpdate << "NULL, ";
  1460. } else {
  1461. memberUpdate << "'" << ipAddr << "', ";
  1462. }
  1463. memberUpdate << "TO_TIMESTAMP(" << timestamp << "::double precision/1000))";
  1464. memberAdded = true;
  1465. } else if (nrows > 1) {
  1466. fprintf(stderr, "nrows > 1?!?");
  1467. continue;
  1468. } else {
  1469. continue;
  1470. }
  1471. }
  1472. memberUpdate << " ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated;";
  1473. if (memberAdded) {
  1474. res = PQexec(conn, memberUpdate.str().c_str());
  1475. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1476. fprintf(stderr, "Multiple insert failed: %s", PQerrorMessage(conn));
  1477. }
  1478. PQclear(res);
  1479. }
  1480. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1481. }
  1482. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  1483. PQfinish(conn);
  1484. if (_run == 1) {
  1485. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1486. exit(6);
  1487. }
  1488. }
  1489. void PostgreSQL::onlineNotification_Redis()
  1490. {
  1491. _connected = 1;
  1492. char buf[11] = {0};
  1493. std::string controllerId = std::string(_myAddress.toString(buf));
  1494. while (_run == 1) {
  1495. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1496. {
  1497. std::lock_guard<std::mutex> l(_lastOnline_l);
  1498. lastOnline.swap(_lastOnline);
  1499. }
  1500. try {
  1501. if (!lastOnline.empty()) {
  1502. if (_rc->clusterMode) {
  1503. auto tx = _cluster->transaction(controllerId, true);
  1504. _doRedisUpdate(tx, controllerId, lastOnline);
  1505. } else {
  1506. auto tx = _redis->transaction(true);
  1507. _doRedisUpdate(tx, controllerId, lastOnline);
  1508. }
  1509. }
  1510. } catch (sw::redis::Error &e) {
  1511. #ifdef ZT_TRACE
  1512. fprintf(stderr, "Error in online notification thread (redis): %s\n", e.what());
  1513. #endif
  1514. }
  1515. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1516. }
  1517. }
  1518. void PostgreSQL::_doRedisUpdate(sw::redis::Transaction &tx, std::string &controllerId,
  1519. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > &lastOnline)
  1520. {
  1521. nlohmann::json jtmp1, jtmp2;
  1522. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1523. uint64_t nwid_i = i->first.first;
  1524. uint64_t memberid_i = i->first.second;
  1525. char nwidTmp[64];
  1526. char memTmp[64];
  1527. char ipTmp[64];
  1528. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1529. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", memberid_i);
  1530. if (!get(nwid_i, jtmp1, memberid_i, jtmp2)){
  1531. continue; // skip non existent members/networks
  1532. }
  1533. std::string networkId(nwidTmp);
  1534. std::string memberId(memTmp);
  1535. int64_t ts = i->second.first;
  1536. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1537. std::string timestamp = std::to_string(ts);
  1538. std::unordered_map<std::string, std::string> record = {
  1539. {"id", memberId},
  1540. {"address", ipAddr},
  1541. {"last_updated", std::to_string(ts)}
  1542. };
  1543. tx.zadd("nodes-online:{"+controllerId+"}", memberId, ts)
  1544. .zadd("network-nodes-online:{"+controllerId+"}:"+networkId, memberId, ts)
  1545. .zadd("active-networks:{"+controllerId+"}", networkId, ts)
  1546. .sadd("network-nodes-all:{"+controllerId+"}:"+networkId, memberId)
  1547. .hmset("member:{"+controllerId+"}:"+networkId+":"+memberId, record.begin(), record.end());
  1548. }
  1549. tx.exec();
  1550. // expire records from all-nodes and network-nodes member list
  1551. uint64_t expireOld = OSUtils::now() - 300000;
  1552. auto cursor = 0LL;
  1553. std::unordered_set<std::string> keys;
  1554. // can't scan for keys in a transaction, so we need to fall back to _cluster or _redis
  1555. // to get all network-members keys
  1556. if(_rc->clusterMode) {
  1557. auto r = _cluster->redis(controllerId);
  1558. while(true) {
  1559. cursor = r.scan(cursor, "network-nodes-online:{"+controllerId+"}:*", INT_MAX, std::inserter(keys, keys.begin()));
  1560. if (cursor == 0) {
  1561. break;
  1562. }
  1563. }
  1564. } else {
  1565. while(true) {
  1566. cursor = _redis->scan(cursor, "network-nodes-online:"+controllerId+":*", INT_MAX, std::inserter(keys, keys.begin()));
  1567. if (cursor == 0) {
  1568. break;
  1569. }
  1570. }
  1571. }
  1572. tx.zremrangebyscore("nodes-online:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1573. tx.zremrangebyscore("active-networks:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1574. for(const auto &k : keys) {
  1575. tx.zremrangebyscore(k, sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1576. }
  1577. tx.exec();
  1578. }
  1579. PGconn *PostgreSQL::getPgConn(OverrideMode m)
  1580. {
  1581. if (m == ALLOW_PGBOUNCER_OVERRIDE) {
  1582. char *connStr = getenv("PGBOUNCER_CONNSTR");
  1583. if (connStr != NULL) {
  1584. fprintf(stderr, "PGBouncer Override\n");
  1585. std::string conn(connStr);
  1586. conn += " application_name=controller-";
  1587. conn += _myAddressStr.c_str();
  1588. return PQconnectdb(conn.c_str());
  1589. }
  1590. }
  1591. return PQconnectdb(_connString.c_str());
  1592. }
  1593. #endif //ZT_CONTROLLER_USE_LIBPQ