PostgreSQL.cpp 54 KB

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