PostgreSQL.cpp 52 KB

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