PostgreSQL.cpp 54 KB

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