PostgreSQL.cpp 52 KB

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