PostgreSQL.cpp 49 KB

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