PostgreSQL.cpp 55 KB

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