PostgreSQL.cpp 55 KB

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