PostgreSQL.cpp 53 KB

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