PostgreSQL.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891
  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: 2025-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 = "false"; // (_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. fprintf(stderr, "Listening to member stream: %s\n", cmd.c_str());
  747. PGresult *res = PQexec(conn, cmd.c_str());
  748. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  749. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  750. PQclear(res);
  751. PQfinish(conn);
  752. exit(1);
  753. }
  754. PQclear(res); res = NULL;
  755. while(_run == 1) {
  756. if (PQstatus(conn) != CONNECTION_OK) {
  757. fprintf(stderr, "ERROR: Member Watcher lost connection to Postgres.");
  758. exit(-1);
  759. }
  760. PGnotify *notify = NULL;
  761. PQconsumeInput(conn);
  762. while ((notify = PQnotifies(conn)) != NULL) {
  763. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  764. try {
  765. json tmp(json::parse(notify->extra));
  766. json &ov = tmp["old_val"];
  767. json &nv = tmp["new_val"];
  768. json oldConfig, newConfig;
  769. if (ov.is_object()) oldConfig = ov;
  770. if (nv.is_object()) newConfig = nv;
  771. if (oldConfig.is_object() || newConfig.is_object()) {
  772. _memberChanged(oldConfig,newConfig,(this->_ready>=2));
  773. }
  774. } catch (...) {} // ignore bad records
  775. free(notify);
  776. }
  777. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  778. }
  779. }
  780. void PostgreSQL::_membersWatcher_Redis() {
  781. char buf[11] = {0};
  782. std::string key = "member-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  783. fprintf(stderr, "Listening to member stream: %s\n", key.c_str());
  784. while (_run == 1) {
  785. try {
  786. json tmp;
  787. std::unordered_map<std::string, ItemStream> result;
  788. if (_rc->clusterMode) {
  789. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  790. } else {
  791. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  792. }
  793. if (!result.empty()) {
  794. for (auto element : result) {
  795. #ifdef ZT_TRACE
  796. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  797. #endif
  798. for (auto rec : element.second) {
  799. std::string id = rec.first;
  800. auto attrs = rec.second;
  801. #ifdef ZT_TRACE
  802. fprintf(stdout, "Record ID: %s\n", id.c_str());
  803. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  804. #endif
  805. for (auto a : attrs) {
  806. #ifdef ZT_TRACE
  807. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  808. #endif
  809. try {
  810. tmp = json::parse(a.second);
  811. json &ov = tmp["old_val"];
  812. json &nv = tmp["new_val"];
  813. json oldConfig, newConfig;
  814. if (ov.is_object()) oldConfig = ov;
  815. if (nv.is_object()) newConfig = nv;
  816. if (oldConfig.is_object()||newConfig.is_object()) {
  817. _memberChanged(oldConfig,newConfig,(this->_ready >= 2));
  818. }
  819. } catch (...) {
  820. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  821. }
  822. }
  823. if (_rc->clusterMode) {
  824. _cluster->xdel(key, id);
  825. } else {
  826. _redis->xdel(key, id);
  827. }
  828. }
  829. }
  830. }
  831. } catch (sw::redis::Error &e) {
  832. fprintf(stderr, "Error in Redis members watcher: %s\n", e.what());
  833. }
  834. }
  835. fprintf(stderr, "membersWatcher ended\n");
  836. }
  837. void PostgreSQL::networksDbWatcher()
  838. {
  839. PGconn *conn = getPgConn(NO_OVERRIDE);
  840. if (PQstatus(conn) == CONNECTION_BAD) {
  841. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  842. PQfinish(conn);
  843. exit(1);
  844. }
  845. if (_rc) {
  846. PQfinish(conn);
  847. conn = NULL;
  848. _networksWatcher_Redis();
  849. } else {
  850. _networksWatcher_Postgres(conn);
  851. PQfinish(conn);
  852. conn = NULL;
  853. }
  854. if (_run == 1) {
  855. fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  856. exit(8);
  857. }
  858. fprintf(stderr, "Exited networksDbWatcher\n");
  859. }
  860. void PostgreSQL::_networksWatcher_Postgres(PGconn *conn) {
  861. char buf[11] = {0};
  862. std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
  863. PGresult *res = PQexec(conn, cmd.c_str());
  864. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  865. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  866. PQclear(res);
  867. PQfinish(conn);
  868. exit(1);
  869. }
  870. PQclear(res); res = NULL;
  871. while(_run == 1) {
  872. if (PQstatus(conn) != CONNECTION_OK) {
  873. fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
  874. exit(-1);
  875. }
  876. PGnotify *notify = NULL;
  877. PQconsumeInput(conn);
  878. while ((notify = PQnotifies(conn)) != NULL) {
  879. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  880. try {
  881. json tmp(json::parse(notify->extra));
  882. json &ov = tmp["old_val"];
  883. json &nv = tmp["new_val"];
  884. json oldConfig, newConfig;
  885. if (ov.is_object()) oldConfig = ov;
  886. if (nv.is_object()) newConfig = nv;
  887. if (oldConfig.is_object()||newConfig.is_object()) {
  888. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  889. }
  890. } catch (...) {} // ignore bad records
  891. free(notify);
  892. }
  893. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  894. }
  895. }
  896. void PostgreSQL::_networksWatcher_Redis() {
  897. char buf[11] = {0};
  898. std::string key = "network-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  899. while (_run == 1) {
  900. try {
  901. json tmp;
  902. std::unordered_map<std::string, ItemStream> result;
  903. if (_rc->clusterMode) {
  904. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  905. } else {
  906. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  907. }
  908. if (!result.empty()) {
  909. for (auto element : result) {
  910. #ifdef ZT_TRACE
  911. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  912. #endif
  913. for (auto rec : element.second) {
  914. std::string id = rec.first;
  915. auto attrs = rec.second;
  916. #ifdef ZT_TRACE
  917. fprintf(stdout, "Record ID: %s\n", id.c_str());
  918. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  919. #endif
  920. for (auto a : attrs) {
  921. #ifdef ZT_TRACE
  922. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  923. #endif
  924. try {
  925. tmp = json::parse(a.second);
  926. json &ov = tmp["old_val"];
  927. json &nv = tmp["new_val"];
  928. json oldConfig, newConfig;
  929. if (ov.is_object()) oldConfig = ov;
  930. if (nv.is_object()) newConfig = nv;
  931. if (oldConfig.is_object()||newConfig.is_object()) {
  932. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  933. }
  934. } catch (...) {
  935. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  936. }
  937. }
  938. if (_rc->clusterMode) {
  939. _cluster->xdel(key, id);
  940. } else {
  941. _redis->xdel(key, id);
  942. }
  943. }
  944. }
  945. }
  946. } catch (sw::redis::Error &e) {
  947. fprintf(stderr, "Error in Redis networks watcher: %s\n", e.what());
  948. }
  949. }
  950. fprintf(stderr, "networksWatcher ended\n");
  951. }
  952. void PostgreSQL::commitThread()
  953. {
  954. PGconn *conn = getPgConn();
  955. if (PQstatus(conn) == CONNECTION_BAD) {
  956. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  957. PQfinish(conn);
  958. exit(1);
  959. }
  960. std::pair<nlohmann::json,bool> qitem;
  961. while(_commitQueue.get(qitem)&(_run == 1)) {
  962. if (!qitem.first.is_object()) {
  963. continue;
  964. }
  965. if (PQstatus(conn) == CONNECTION_BAD) {
  966. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  967. PQfinish(conn);
  968. exit(1);
  969. }
  970. try {
  971. nlohmann::json *config = &(qitem.first);
  972. const std::string objtype = (*config)["objtype"];
  973. if (objtype == "member") {
  974. try {
  975. bool fromCentral = OSUtils::jsonBool((*config)["fromCentral"], false);
  976. if (!fromCentral) {
  977. // Central already writes all of this to the DB on a change.
  978. // No need for the controller to do it as well.
  979. std::string memberId = (*config)["id"];
  980. std::string networkId = (*config)["nwid"];
  981. std::string identity = (*config)["identity"];
  982. std::string target = "NULL";
  983. if (!(*config)["remoteTraceTarget"].is_null()) {
  984. target = (*config)["remoteTraceTarget"];
  985. }
  986. std::string caps = OSUtils::jsonDump((*config)["capabilities"], -1);
  987. std::string lastAuthTime = std::to_string((long long)(*config)["lastAuthorizedTime"]);
  988. std::string lastDeauthTime = std::to_string((long long)(*config)["lastDeauthorizedTime"]);
  989. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  990. std::string rev = std::to_string((unsigned long long)(*config)["revision"]);
  991. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  992. std::string vmajor = std::to_string((int)(*config)["vMajor"]);
  993. std::string vminor = std::to_string((int)(*config)["vMinor"]);
  994. std::string vrev = std::to_string((int)(*config)["vRev"]);
  995. std::string vproto = std::to_string((int)(*config)["vProto"]);
  996. const char *values[19] = {
  997. memberId.c_str(),
  998. networkId.c_str(),
  999. ((*config)["activeBridge"] ? "true" : "false"),
  1000. ((*config)["authorized"] ? "true" : "false"),
  1001. caps.c_str(),
  1002. identity.c_str(),
  1003. lastAuthTime.c_str(),
  1004. lastDeauthTime.c_str(),
  1005. ((*config)["noAutoAssignIps"] ? "true" : "false"),
  1006. rtraceLevel.c_str(),
  1007. (target == "NULL") ? NULL : target.c_str(),
  1008. rev.c_str(),
  1009. tags.c_str(),
  1010. vmajor.c_str(),
  1011. vminor.c_str(),
  1012. vrev.c_str(),
  1013. vproto.c_str()
  1014. };
  1015. PGresult *res = PQexec(conn, "BEGIN");
  1016. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1017. fprintf(stderr, "ERROR: Error beginning update transaction: %s\n", PQresultErrorMessage(res));
  1018. PQclear(res);
  1019. delete config;
  1020. config = nullptr;
  1021. continue;
  1022. }
  1023. res = PQexecParams(conn,
  1024. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  1025. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  1026. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  1027. "VALUES ($1, $2, $3, $4, $5, $6, "
  1028. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  1029. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  1030. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  1031. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  1032. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  1033. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  1034. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  1035. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  1036. 17,
  1037. NULL,
  1038. values,
  1039. NULL,
  1040. NULL,
  1041. 0);
  1042. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1043. fprintf(stderr, "ERROR: Error updating member: %s\n", PQresultErrorMessage(res));
  1044. fprintf(stderr, "%s", OSUtils::jsonDump(*config, 2).c_str());
  1045. PQclear(res);
  1046. PQclear(PQexec(conn, "ROLLBACK"));
  1047. delete config;
  1048. config = nullptr;
  1049. continue;
  1050. }
  1051. PQclear(res);
  1052. const char *v2[2] = {
  1053. memberId.c_str(),
  1054. networkId.c_str()
  1055. };
  1056. res = PQexecParams(conn,
  1057. "DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  1058. 2,
  1059. NULL,
  1060. v2,
  1061. NULL,
  1062. NULL,
  1063. 0);
  1064. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1065. fprintf(stderr, "ERROR: Error updating IP address assignments: %s\n", PQresultErrorMessage(res));
  1066. PQclear(res);
  1067. PQclear(PQexec(conn, "ROLLBACK"));;
  1068. delete config;
  1069. config = nullptr;
  1070. continue;
  1071. }
  1072. PQclear(res);
  1073. std::vector<std::string> assignments;
  1074. bool ipAssignError = false;
  1075. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  1076. std::string addr = *i;
  1077. if (std::find(assignments.begin(), assignments.end(), addr) != assignments.end()) {
  1078. continue;
  1079. }
  1080. const char *v3[3] = {
  1081. memberId.c_str(),
  1082. networkId.c_str(),
  1083. addr.c_str()
  1084. };
  1085. res = PQexecParams(conn,
  1086. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3) ON CONFLICT (network_id, member_id, address) DO NOTHING",
  1087. 3,
  1088. NULL,
  1089. v3,
  1090. NULL,
  1091. NULL,
  1092. 0);
  1093. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1094. fprintf(stderr, "ERROR: Error setting IP addresses for member: %s\n", PQresultErrorMessage(res));
  1095. PQclear(res);
  1096. PQclear(PQexec(conn, "ROLLBACK"));
  1097. ipAssignError = true;
  1098. break;
  1099. }
  1100. PQclear(res);
  1101. assignments.push_back(addr);
  1102. }
  1103. if (ipAssignError) {
  1104. delete config;
  1105. config = nullptr;
  1106. continue;
  1107. }
  1108. res = PQexec(conn, "COMMIT");
  1109. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1110. fprintf(stderr, "ERROR: Error committing member transaction: %s\n", PQresultErrorMessage(res));
  1111. PQclear(res);
  1112. PQclear(PQexec(conn, "ROLLBACK"));
  1113. delete config;
  1114. config = nullptr;
  1115. continue;
  1116. }
  1117. }
  1118. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  1119. const uint64_t memberidInt = OSUtils::jsonIntHex((*config)["id"], 0ULL);
  1120. if (nwidInt && memberidInt) {
  1121. nlohmann::json nwOrig;
  1122. nlohmann::json memOrig;
  1123. nlohmann::json memNew(*config);
  1124. get(nwidInt, nwOrig, memberidInt, memOrig);
  1125. _memberChanged(memOrig, memNew, qitem.second);
  1126. } else {
  1127. fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %llu-%llu\n", (unsigned long long)nwidInt, (unsigned long long)memberidInt);
  1128. }
  1129. } catch (std::exception &e) {
  1130. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  1131. }
  1132. } else if (objtype == "network") {
  1133. try {
  1134. bool fromCentral = OSUtils::jsonBool((*config)["fromCentral"], false);
  1135. if (!fromCentral) {
  1136. std::string id = (*config)["id"];
  1137. std::string controllerId = _myAddressStr.c_str();
  1138. std::string name = (*config)["name"];
  1139. std::string remoteTraceTarget("NULL");
  1140. if (!(*config)["remoteTraceTarget"].is_null()) {
  1141. remoteTraceTarget = (*config)["remoteTraceTarget"];
  1142. }
  1143. std::string rulesSource;
  1144. if ((*config)["rulesSource"].is_string()) {
  1145. rulesSource = (*config)["rulesSource"];
  1146. }
  1147. std::string caps = OSUtils::jsonDump((*config)["capabilitles"], -1);
  1148. std::string now = std::to_string(OSUtils::now());
  1149. std::string mtu = std::to_string((int)(*config)["mtu"]);
  1150. std::string mcastLimit = std::to_string((int)(*config)["multicastLimit"]);
  1151. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  1152. std::string rules = OSUtils::jsonDump((*config)["rules"], -1);
  1153. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  1154. std::string v4mode = OSUtils::jsonDump((*config)["v4AssignMode"],-1);
  1155. std::string v6mode = OSUtils::jsonDump((*config)["v6AssignMode"], -1);
  1156. bool enableBroadcast = (*config)["enableBroadcast"];
  1157. bool isPrivate = (*config)["private"];
  1158. const char *values[16] = {
  1159. id.c_str(),
  1160. controllerId.c_str(),
  1161. caps.c_str(),
  1162. enableBroadcast ? "true" : "false",
  1163. now.c_str(),
  1164. mtu.c_str(),
  1165. mcastLimit.c_str(),
  1166. name.c_str(),
  1167. isPrivate ? "true" : "false",
  1168. rtraceLevel.c_str(),
  1169. (remoteTraceTarget == "NULL" ? NULL : remoteTraceTarget.c_str()),
  1170. rules.c_str(),
  1171. rulesSource.c_str(),
  1172. tags.c_str(),
  1173. v4mode.c_str(),
  1174. v6mode.c_str(),
  1175. };
  1176. PGresult *res = PQexec(conn, "BEGIN");
  1177. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1178. fprintf(stderr, "ERROR: Error beginnning transaction: %s\n", PQresultErrorMessage(res));
  1179. PQclear(res);
  1180. delete config;
  1181. config = nullptr;
  1182. continue;
  1183. }
  1184. PQclear(res);
  1185. // This ugly query exists because when we want to mirror networks to/from
  1186. // another data store (e.g. FileDB or LFDB) it is possible to get a network
  1187. // that doesn't exist in Central's database. This does an upsert and sets
  1188. // the owner_id to the "first" global admin in the user DB if the record
  1189. // did not previously exist. If the record already exists owner_id is left
  1190. // unchanged, so owner_id should be left out of the update clause.
  1191. res = PQexecParams(conn,
  1192. "INSERT INTO ztc_network (id, creation_time, owner_id, controller_id, capabilities, enable_broadcast, "
  1193. "last_modified, mtu, multicast_limit, name, private, "
  1194. "remote_trace_level, remote_trace_target, rules, rules_source, "
  1195. "tags, v4_assign_mode, v6_assign_mode) VALUES ("
  1196. "$1, TO_TIMESTAMP($5::double precision/1000), "
  1197. "(SELECT user_id AS owner_id FROM ztc_global_permissions WHERE authorize = true AND del = true AND modify = true AND read = true LIMIT 1),"
  1198. "$2, $3, $4, TO_TIMESTAMP($5::double precision/1000), "
  1199. "$6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) "
  1200. "ON CONFLICT (id) DO UPDATE set controller_id = EXCLUDED.controller_id, "
  1201. "capabilities = EXCLUDED.capabilities, enable_broadcast = EXCLUDED.enable_broadcast, "
  1202. "last_modified = EXCLUDED.last_modified, mtu = EXCLUDED.mtu, "
  1203. "multicast_limit = EXCLUDED.multicast_limit, name = EXCLUDED.name, "
  1204. "private = EXCLUDED.private, remote_trace_level = EXCLUDED.remote_trace_level, "
  1205. "remote_trace_target = EXCLUDED.remote_trace_target, rules = EXCLUDED.rules, "
  1206. "rules_source = EXCLUDED.rules_source, tags = EXCLUDED.tags, "
  1207. "v4_assign_mode = EXCLUDED.v4_assign_mode, v6_assign_mode = EXCLUDED.v6_assign_mode",
  1208. 16,
  1209. NULL,
  1210. values,
  1211. NULL,
  1212. NULL,
  1213. 0);
  1214. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1215. fprintf(stderr, "ERROR: Error updating network record: %s\n", PQresultErrorMessage(res));
  1216. PQclear(res);
  1217. PQclear(PQexec(conn, "ROLLBACK"));
  1218. delete config;
  1219. config = nullptr;
  1220. continue;
  1221. }
  1222. PQclear(res);
  1223. const char *params[1] = {
  1224. id.c_str()
  1225. };
  1226. res = PQexecParams(conn,
  1227. "DELETE FROM ztc_network_assignment_pool WHERE network_id = $1",
  1228. 1,
  1229. NULL,
  1230. params,
  1231. NULL,
  1232. NULL,
  1233. 0);
  1234. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1235. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  1236. PQclear(res);
  1237. PQclear(PQexec(conn, "ROLLBACK"));
  1238. delete config;
  1239. config = nullptr;
  1240. continue;
  1241. }
  1242. PQclear(res);
  1243. auto pool = (*config)["ipAssignmentPools"];
  1244. bool err = false;
  1245. for (auto i = pool.begin(); i != pool.end(); ++i) {
  1246. std::string start = (*i)["ipRangeStart"];
  1247. std::string end = (*i)["ipRangeEnd"];
  1248. const char *p[3] = {
  1249. id.c_str(),
  1250. start.c_str(),
  1251. end.c_str()
  1252. };
  1253. res = PQexecParams(conn,
  1254. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  1255. "VALUES ($1, $2, $3)",
  1256. 3,
  1257. NULL,
  1258. p,
  1259. NULL,
  1260. NULL,
  1261. 0);
  1262. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1263. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  1264. PQclear(res);
  1265. err = true;
  1266. break;
  1267. }
  1268. PQclear(res);
  1269. }
  1270. if (err) {
  1271. PQclear(res);
  1272. PQclear(PQexec(conn, "ROLLBACK"));
  1273. delete config;
  1274. config = nullptr;
  1275. continue;
  1276. }
  1277. res = PQexecParams(conn,
  1278. "DELETE FROM ztc_network_route WHERE network_id = $1",
  1279. 1,
  1280. NULL,
  1281. params,
  1282. NULL,
  1283. NULL,
  1284. 0);
  1285. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1286. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  1287. PQclear(res);
  1288. PQclear(PQexec(conn, "ROLLBACK"));
  1289. delete config;
  1290. config = nullptr;
  1291. continue;
  1292. }
  1293. auto routes = (*config)["routes"];
  1294. err = false;
  1295. for (auto i = routes.begin(); i != routes.end(); ++i) {
  1296. std::string t = (*i)["target"];
  1297. std::vector<std::string> target;
  1298. std::istringstream f(t);
  1299. std::string s;
  1300. while(std::getline(f, s, '/')) {
  1301. target.push_back(s);
  1302. }
  1303. if (target.empty() || target.size() != 2) {
  1304. continue;
  1305. }
  1306. std::string targetAddr = target[0];
  1307. std::string targetBits = target[1];
  1308. std::string via = "NULL";
  1309. if (!(*i)["via"].is_null()) {
  1310. via = (*i)["via"];
  1311. }
  1312. const char *p[4] = {
  1313. id.c_str(),
  1314. targetAddr.c_str(),
  1315. targetBits.c_str(),
  1316. (via == "NULL" ? NULL : via.c_str()),
  1317. };
  1318. res = PQexecParams(conn,
  1319. "INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  1320. 4,
  1321. NULL,
  1322. p,
  1323. NULL,
  1324. NULL,
  1325. 0);
  1326. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1327. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  1328. PQclear(res);
  1329. err = true;
  1330. break;
  1331. }
  1332. PQclear(res);
  1333. }
  1334. if (err) {
  1335. PQclear(PQexec(conn, "ROLLBACK"));
  1336. delete config;
  1337. config = nullptr;
  1338. continue;
  1339. }
  1340. auto dns = (*config)["dns"];
  1341. std::string domain = dns["domain"];
  1342. std::stringstream servers;
  1343. servers << "{";
  1344. for (auto j = dns["servers"].begin(); j < dns["servers"].end(); ++j) {
  1345. servers << *j;
  1346. if ( (j+1) != dns["servers"].end()) {
  1347. servers << ",";
  1348. }
  1349. }
  1350. servers << "}";
  1351. const char *p[3] = {
  1352. id.c_str(),
  1353. domain.c_str(),
  1354. servers.str().c_str()
  1355. };
  1356. 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",
  1357. 3,
  1358. NULL,
  1359. p,
  1360. NULL,
  1361. NULL,
  1362. 0);
  1363. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1364. fprintf(stderr, "ERROR: Error updating DNS: %s\n", PQresultErrorMessage(res));
  1365. PQclear(res);
  1366. PQclear(PQexec(conn, "ROLLBACK"));
  1367. err = true;
  1368. break;
  1369. }
  1370. PQclear(res);
  1371. res = PQexec(conn, "COMMIT");
  1372. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1373. fprintf(stderr, "ERROR: Error committing network update: %s\n", PQresultErrorMessage(res));
  1374. PQclear(res);
  1375. PQclear(PQexec(conn, "ROLLBACK"));
  1376. delete config;
  1377. config = nullptr;
  1378. continue;
  1379. }
  1380. PQclear(res);
  1381. }
  1382. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  1383. if (nwidInt) {
  1384. nlohmann::json nwOrig;
  1385. nlohmann::json nwNew(*config);
  1386. get(nwidInt, nwOrig);
  1387. _networkChanged(nwOrig, nwNew, qitem.second);
  1388. } else {
  1389. fprintf(stderr, "Can't notify network changed: %llu\n", (unsigned long long)nwidInt);
  1390. }
  1391. } catch (std::exception &e) {
  1392. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  1393. }
  1394. // if (_rc != NULL) {
  1395. // try {
  1396. // std::string id = (*config)["id"];
  1397. // std::string controllerId = _myAddressStr.c_str();
  1398. // std::string key = "networks:{" + controllerId + "}";
  1399. // if (_rc->clusterMode) {
  1400. // _cluster->sadd(key, id);
  1401. // } else {
  1402. // _redis->sadd(key, id);
  1403. // }
  1404. // } catch (sw::redis::Error &e) {
  1405. // fprintf(stderr, "ERROR: Error adding network to Redis: %s\n", e.what());
  1406. // }
  1407. // }
  1408. } else if (objtype == "_delete_network") {
  1409. try {
  1410. std::string networkId = (*config)["nwid"];
  1411. const char *values[1] = {
  1412. networkId.c_str()
  1413. };
  1414. PGresult * res = PQexecParams(conn,
  1415. "UPDATE ztc_network SET deleted = true WHERE id = $1",
  1416. 1,
  1417. NULL,
  1418. values,
  1419. NULL,
  1420. NULL,
  1421. 0);
  1422. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1423. fprintf(stderr, "ERROR: Error deleting network: %s\n", PQresultErrorMessage(res));
  1424. }
  1425. PQclear(res);
  1426. } catch (std::exception &e) {
  1427. fprintf(stderr, "ERROR: Error deleting network: %s\n", e.what());
  1428. }
  1429. // if (_rc != NULL) {
  1430. // try {
  1431. // std::string id = (*config)["id"];
  1432. // std::string controllerId = _myAddressStr.c_str();
  1433. // std::string key = "networks:{" + controllerId + "}";
  1434. // if (_rc->clusterMode) {
  1435. // _cluster->srem(key, id);
  1436. // _cluster->del("network-nodes-online:{"+controllerId+"}:"+id);
  1437. // } else {
  1438. // _redis->srem(key, id);
  1439. // _redis->del("network-nodes-online:{"+controllerId+"}:"+id);
  1440. // }
  1441. // } catch (sw::redis::Error &e) {
  1442. // fprintf(stderr, "ERROR: Error adding network to Redis: %s\n", e.what());
  1443. // }
  1444. // }
  1445. } else if (objtype == "_delete_member") {
  1446. try {
  1447. std::string memberId = (*config)["id"];
  1448. std::string networkId = (*config)["nwid"];
  1449. const char *values[2] = {
  1450. memberId.c_str(),
  1451. networkId.c_str()
  1452. };
  1453. PGresult *res = PQexecParams(conn,
  1454. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  1455. 2,
  1456. NULL,
  1457. values,
  1458. NULL,
  1459. NULL,
  1460. 0);
  1461. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1462. fprintf(stderr, "ERROR: Error deleting member: %s\n", PQresultErrorMessage(res));
  1463. }
  1464. PQclear(res);
  1465. } catch (std::exception &e) {
  1466. fprintf(stderr, "ERROR: Error deleting member: %s\n", e.what());
  1467. }
  1468. // if (_rc != NULL) {
  1469. // try {
  1470. // std::string memberId = (*config)["id"];
  1471. // std::string networkId = (*config)["nwid"];
  1472. // std::string controllerId = _myAddressStr.c_str();
  1473. // std::string key = "network-nodes-all:{" + controllerId + "}:" + networkId;
  1474. // if (_rc->clusterMode) {
  1475. // _cluster->srem(key, memberId);
  1476. // _cluster->del("member:{"+controllerId+"}:"+networkId+":"+memberId);
  1477. // } else {
  1478. // _redis->srem(key, memberId);
  1479. // _redis->del("member:{"+controllerId+"}:"+networkId+":"+memberId);
  1480. // }
  1481. // } catch (sw::redis::Error &e) {
  1482. // fprintf(stderr, "ERROR: Error deleting member from Redis: %s\n", e.what());
  1483. // }
  1484. // }
  1485. } else {
  1486. fprintf(stderr, "ERROR: unknown objtype");
  1487. }
  1488. } catch (std::exception &e) {
  1489. fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
  1490. }
  1491. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1492. }
  1493. PQfinish(conn);
  1494. if (_run == 1) {
  1495. fprintf(stderr, "ERROR: %s commitThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1496. exit(7);
  1497. }
  1498. fprintf(stderr, "commitThread finished\n");
  1499. }
  1500. void PostgreSQL::onlineNotificationThread()
  1501. {
  1502. waitForReady();
  1503. // if (_rc != NULL) {
  1504. // onlineNotification_Redis();
  1505. // } else {
  1506. onlineNotification_Postgres();
  1507. // }
  1508. }
  1509. void PostgreSQL::onlineNotification_Postgres()
  1510. {
  1511. PGconn *conn = getPgConn();
  1512. if (PQstatus(conn) == CONNECTION_BAD) {
  1513. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  1514. PQfinish(conn);
  1515. exit(1);
  1516. }
  1517. _connected = 1;
  1518. nlohmann::json jtmp1, jtmp2;
  1519. while (_run == 1) {
  1520. if (PQstatus(conn) != CONNECTION_OK) {
  1521. fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres.");
  1522. PQfinish(conn);
  1523. exit(5);
  1524. }
  1525. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1526. {
  1527. std::lock_guard<std::mutex> l(_lastOnline_l);
  1528. lastOnline.swap(_lastOnline);
  1529. }
  1530. PGresult *res = NULL;
  1531. std::stringstream memberUpdate;
  1532. memberUpdate << "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ";
  1533. bool firstRun = true;
  1534. bool memberAdded = false;
  1535. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1536. uint64_t nwid_i = i->first.first;
  1537. char nwidTmp[64];
  1538. char memTmp[64];
  1539. char ipTmp[64];
  1540. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1541. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  1542. if(!get(nwid_i, jtmp1, i->first.second, jtmp2)) {
  1543. continue; // skip non existent networks/members
  1544. }
  1545. std::string networkId(nwidTmp);
  1546. std::string memberId(memTmp);
  1547. const char *qvals[2] = {
  1548. networkId.c_str(),
  1549. memberId.c_str()
  1550. };
  1551. res = PQexecParams(conn,
  1552. "SELECT id, network_id FROM ztc_member WHERE network_id = $1 AND id = $2",
  1553. 2,
  1554. NULL,
  1555. qvals,
  1556. NULL,
  1557. NULL,
  1558. 0);
  1559. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  1560. fprintf(stderr, "Member count failed: %s", PQerrorMessage(conn));
  1561. PQclear(res);
  1562. continue;
  1563. }
  1564. int nrows = PQntuples(res);
  1565. PQclear(res);
  1566. if (nrows == 1) {
  1567. int64_t ts = i->second.first;
  1568. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1569. std::string timestamp = std::to_string(ts);
  1570. if (firstRun) {
  1571. firstRun = false;
  1572. } else {
  1573. memberUpdate << ", ";
  1574. }
  1575. memberUpdate << "('" << networkId << "', '" << memberId << "', ";
  1576. if (ipAddr.empty()) {
  1577. memberUpdate << "NULL, ";
  1578. } else {
  1579. memberUpdate << "'" << ipAddr << "', ";
  1580. }
  1581. memberUpdate << "TO_TIMESTAMP(" << timestamp << "::double precision/1000))";
  1582. memberAdded = true;
  1583. } else if (nrows > 1) {
  1584. fprintf(stderr, "nrows > 1?!?");
  1585. continue;
  1586. } else {
  1587. continue;
  1588. }
  1589. }
  1590. memberUpdate << " ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated;";
  1591. if (memberAdded) {
  1592. res = PQexec(conn, memberUpdate.str().c_str());
  1593. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1594. fprintf(stderr, "Multiple insert failed: %s", PQerrorMessage(conn));
  1595. }
  1596. PQclear(res);
  1597. }
  1598. std::this_thread::sleep_for(std::chrono::seconds(10));
  1599. }
  1600. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  1601. PQfinish(conn);
  1602. if (_run == 1) {
  1603. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1604. exit(6);
  1605. }
  1606. }
  1607. void PostgreSQL::onlineNotification_Redis()
  1608. {
  1609. _connected = 1;
  1610. char buf[11] = {0};
  1611. std::string controllerId = std::string(_myAddress.toString(buf));
  1612. while (_run == 1) {
  1613. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1614. {
  1615. std::lock_guard<std::mutex> l(_lastOnline_l);
  1616. lastOnline.swap(_lastOnline);
  1617. }
  1618. try {
  1619. if (!lastOnline.empty()) {
  1620. if (_rc->clusterMode) {
  1621. auto tx = _cluster->transaction(controllerId, true);
  1622. _doRedisUpdate(tx, controllerId, lastOnline);
  1623. } else {
  1624. auto tx = _redis->transaction(true);
  1625. _doRedisUpdate(tx, controllerId, lastOnline);
  1626. }
  1627. }
  1628. } catch (sw::redis::Error &e) {
  1629. #ifdef ZT_TRACE
  1630. fprintf(stderr, "Error in online notification thread (redis): %s\n", e.what());
  1631. #endif
  1632. }
  1633. std::this_thread::sleep_for(std::chrono::seconds(10));
  1634. }
  1635. }
  1636. void PostgreSQL::_doRedisUpdate(sw::redis::Transaction &tx, std::string &controllerId,
  1637. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > &lastOnline)
  1638. {
  1639. nlohmann::json jtmp1, jtmp2;
  1640. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1641. uint64_t nwid_i = i->first.first;
  1642. uint64_t memberid_i = i->first.second;
  1643. char nwidTmp[64];
  1644. char memTmp[64];
  1645. char ipTmp[64];
  1646. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1647. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", memberid_i);
  1648. if (!get(nwid_i, jtmp1, memberid_i, jtmp2)){
  1649. continue; // skip non existent members/networks
  1650. }
  1651. std::string networkId(nwidTmp);
  1652. std::string memberId(memTmp);
  1653. int64_t ts = i->second.first;
  1654. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1655. std::string timestamp = std::to_string(ts);
  1656. std::unordered_map<std::string, std::string> record = {
  1657. {"id", memberId},
  1658. {"address", ipAddr},
  1659. {"last_updated", std::to_string(ts)}
  1660. };
  1661. tx.zadd("nodes-online:{"+controllerId+"}", memberId, ts)
  1662. .zadd("nodes-online2:{"+controllerId+"}", networkId+"-"+memberId, ts)
  1663. .zadd("network-nodes-online:{"+controllerId+"}:"+networkId, memberId, ts)
  1664. .zadd("active-networks:{"+controllerId+"}", networkId, ts)
  1665. .sadd("network-nodes-all:{"+controllerId+"}:"+networkId, memberId)
  1666. .hmset("member:{"+controllerId+"}:"+networkId+":"+memberId, record.begin(), record.end());
  1667. }
  1668. // expire records from all-nodes and network-nodes member list
  1669. uint64_t expireOld = OSUtils::now() - 300000;
  1670. tx.zremrangebyscore("nodes-online:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1671. tx.zremrangebyscore("nodes-online2:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1672. tx.zremrangebyscore("active-networks:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1673. {
  1674. std::lock_guard<std::mutex> l(_networks_l);
  1675. for (const auto &it : _networks) {
  1676. uint64_t nwid_i = it.first;
  1677. char nwidTmp[64];
  1678. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1679. tx.zremrangebyscore("network-nodes-online:{"+controllerId+"}:"+nwidTmp,
  1680. sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1681. }
  1682. }
  1683. tx.exec();
  1684. }
  1685. PGconn *PostgreSQL::getPgConn(OverrideMode m)
  1686. {
  1687. if (m == ALLOW_PGBOUNCER_OVERRIDE) {
  1688. char *connStr = getenv("PGBOUNCER_CONNSTR");
  1689. if (connStr != NULL) {
  1690. fprintf(stderr, "PGBouncer Override\n");
  1691. std::string conn(connStr);
  1692. conn += " application_name=controller-";
  1693. conn += _myAddressStr.c_str();
  1694. return PQconnectdb(conn.c_str());
  1695. }
  1696. }
  1697. return PQconnectdb(_connString.c_str());
  1698. }
  1699. #endif //ZT_CONTROLLER_USE_LIBPQ