PostgreSQL.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "PostgreSQL.hpp"
  14. #ifdef ZT_CONTROLLER_USE_LIBPQ
  15. #include "../node/Constants.hpp"
  16. #include "../node/SHA512.hpp"
  17. #include "EmbeddedNetworkController.hpp"
  18. #include "../version.h"
  19. #include "Redis.hpp"
  20. #include <libpq-fe.h>
  21. #include <sstream>
  22. #include <climits>
  23. #include <chrono>
  24. // #define ZT_TRACE 1
  25. using json = nlohmann::json;
  26. namespace {
  27. static const int DB_MINIMUM_VERSION = 20;
  28. static const char *_timestr()
  29. {
  30. time_t t = time(0);
  31. char *ts = ctime(&t);
  32. char *p = ts;
  33. if (!p)
  34. return "";
  35. while (*p) {
  36. if (*p == '\n') {
  37. *p = (char)0;
  38. break;
  39. }
  40. ++p;
  41. }
  42. return ts;
  43. }
  44. /*
  45. std::string join(const std::vector<std::string> &elements, const char * const separator)
  46. {
  47. switch(elements.size()) {
  48. case 0:
  49. return "";
  50. case 1:
  51. return elements[0];
  52. default:
  53. std::ostringstream os;
  54. std::copy(elements.begin(), elements.end()-1, std::ostream_iterator<std::string>(os, separator));
  55. os << *elements.rbegin();
  56. return os.str();
  57. }
  58. }
  59. */
  60. std::vector<std::string> split(std::string str, char delim){
  61. std::istringstream iss(str);
  62. std::vector<std::string> tokens;
  63. std::string item;
  64. while(std::getline(iss, item, delim)) {
  65. tokens.push_back(item);
  66. }
  67. return tokens;
  68. }
  69. } // anonymous namespace
  70. using namespace ZeroTier;
  71. MemberNotificationReceiver::MemberNotificationReceiver(PostgreSQL *p, pqxx::connection &c, const std::string &channel)
  72. : pqxx::notification_receiver(c, channel)
  73. , _psql(p)
  74. {
  75. fprintf(stderr, "initialize MemberNotificaitonReceiver\n");
  76. }
  77. void MemberNotificationReceiver::operator() (const std::string &payload, int packend_pid) {
  78. fprintf(stderr, "Member Notification received: %s\n", payload.c_str());
  79. json tmp(json::parse(payload));
  80. json &ov = tmp["old_val"];
  81. json &nv = tmp["new_val"];
  82. json oldConfig, newConfig;
  83. if (ov.is_object()) oldConfig = ov;
  84. if (nv.is_object()) newConfig = nv;
  85. if (oldConfig.is_object() || newConfig.is_object()) {
  86. _psql->_memberChanged(oldConfig,newConfig,(_psql->_ready>=2));
  87. fprintf(stderr, "payload sent\n");
  88. }
  89. }
  90. NetworkNotificationReceiver::NetworkNotificationReceiver(PostgreSQL *p, pqxx::connection &c, const std::string &channel)
  91. : pqxx::notification_receiver(c, channel)
  92. , _psql(p)
  93. {
  94. fprintf(stderr, "initialize NetworkNotificationReceiver\n");
  95. }
  96. void NetworkNotificationReceiver::operator() (const std::string &payload, int packend_pid) {
  97. fprintf(stderr, "Network Notificaiton received: %s\n", payload.c_str());
  98. json tmp(json::parse(payload));
  99. json &ov = tmp["old_val"];
  100. json &nv = tmp["new_val"];
  101. json oldConfig, newConfig;
  102. if (ov.is_object()) oldConfig = ov;
  103. if (nv.is_object()) newConfig = nv;
  104. if (oldConfig.is_object() || newConfig.is_object()) {
  105. _psql->_networkChanged(oldConfig,newConfig,(_psql->_ready>=2));
  106. fprintf(stderr, "payload sent\n");
  107. }
  108. }
  109. using Attrs = std::vector<std::pair<std::string, std::string>>;
  110. using Item = std::pair<std::string, Attrs>;
  111. using ItemStream = std::vector<Item>;
  112. PostgreSQL::PostgreSQL(const Identity &myId, const char *path, int listenPort, RedisConfig *rc)
  113. : DB()
  114. , _pool()
  115. , _myId(myId)
  116. , _myAddress(myId.address())
  117. , _ready(0)
  118. , _connected(1)
  119. , _run(1)
  120. , _waitNoticePrinted(false)
  121. , _listenPort(listenPort)
  122. , _rc(rc)
  123. , _redis(NULL)
  124. , _cluster(NULL)
  125. {
  126. char myAddress[64];
  127. _myAddressStr = myId.address().toString(myAddress);
  128. _connString = std::string(path);
  129. auto f = std::make_shared<PostgresConnFactory>(_connString);
  130. _pool = std::make_shared<ConnectionPool<PostgresConnection> >(
  131. 15, 5, std::static_pointer_cast<ConnectionFactory>(f));
  132. memset(_ssoPsk, 0, sizeof(_ssoPsk));
  133. char *const ssoPskHex = getenv("ZT_SSO_PSK");
  134. #ifdef ZT_TRACE
  135. fprintf(stderr, "ZT_SSO_PSK: %s\n", ssoPskHex);
  136. #endif
  137. if (ssoPskHex) {
  138. // SECURITY: note that ssoPskHex will always be null-terminated if libc acatually
  139. // returns something non-NULL. If the hex encodes something shorter than 48 bytes,
  140. // it will be padded at the end with zeroes. If longer, it'll be truncated.
  141. Utils::unhex(ssoPskHex, _ssoPsk, sizeof(_ssoPsk));
  142. }
  143. auto c = _pool->borrow();
  144. pqxx::work txn{*c->c};
  145. pqxx::row r{txn.exec1("SELECT version FROM ztc_database")};
  146. int dbVersion = r[0].as<int>();
  147. txn.commit();
  148. if (dbVersion < DB_MINIMUM_VERSION) {
  149. 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);
  150. exit(1);
  151. }
  152. _pool->unborrow(c);
  153. if (_rc != NULL) {
  154. sw::redis::ConnectionOptions opts;
  155. sw::redis::ConnectionPoolOptions poolOpts;
  156. opts.host = _rc->hostname;
  157. opts.port = _rc->port;
  158. opts.password = _rc->password;
  159. opts.db = 0;
  160. poolOpts.size = 10;
  161. if (_rc->clusterMode) {
  162. fprintf(stderr, "Using Redis in Cluster Mode\n");
  163. _cluster = std::make_shared<sw::redis::RedisCluster>(opts, poolOpts);
  164. } else {
  165. fprintf(stderr, "Using Redis in Standalone Mode\n");
  166. _redis = std::make_shared<sw::redis::Redis>(opts, poolOpts);
  167. }
  168. }
  169. _readyLock.lock();
  170. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S, ::_timestr(), (unsigned long long)_myAddress.toInt());
  171. _waitNoticePrinted = true;
  172. initializeNetworks();
  173. initializeMembers();
  174. _heartbeatThread = std::thread(&PostgreSQL::heartbeat, this);
  175. _membersDbWatcher = std::thread(&PostgreSQL::membersDbWatcher, this);
  176. _networksDbWatcher = std::thread(&PostgreSQL::networksDbWatcher, this);
  177. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  178. _commitThread[i] = std::thread(&PostgreSQL::commitThread, this);
  179. }
  180. _onlineNotificationThread = std::thread(&PostgreSQL::onlineNotificationThread, this);
  181. }
  182. PostgreSQL::~PostgreSQL()
  183. {
  184. _run = 0;
  185. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  186. _heartbeatThread.join();
  187. _membersDbWatcher.join();
  188. _networksDbWatcher.join();
  189. _commitQueue.stop();
  190. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  191. _commitThread[i].join();
  192. }
  193. _onlineNotificationThread.join();
  194. }
  195. bool PostgreSQL::waitForReady()
  196. {
  197. while (_ready < 2) {
  198. _readyLock.lock();
  199. _readyLock.unlock();
  200. }
  201. return true;
  202. }
  203. bool PostgreSQL::isReady()
  204. {
  205. return ((_ready == 2)&&(_connected));
  206. }
  207. bool PostgreSQL::save(nlohmann::json &record,bool notifyListeners)
  208. {
  209. bool modified = false;
  210. try {
  211. if (!record.is_object()) {
  212. fprintf(stderr, "record is not an object?!?\n");
  213. return false;
  214. }
  215. const std::string objtype = record["objtype"];
  216. if (objtype == "network") {
  217. //fprintf(stderr, "network save\n");
  218. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  219. if (nwid) {
  220. nlohmann::json old;
  221. get(nwid,old);
  222. if ((!old.is_object())||(!_compareRecords(old,record))) {
  223. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  224. _commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
  225. modified = true;
  226. }
  227. }
  228. } else if (objtype == "member") {
  229. std::string networkId = record["nwid"];
  230. std::string memberId = record["id"];
  231. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  232. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  233. //fprintf(stderr, "member save %s-%s\n", networkId.c_str(), memberId.c_str());
  234. if ((id)&&(nwid)) {
  235. nlohmann::json network,old;
  236. get(nwid,network,id,old);
  237. if ((!old.is_object())||(!_compareRecords(old,record))) {
  238. //fprintf(stderr, "commit queue post\n");
  239. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  240. _commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
  241. modified = true;
  242. } else {
  243. //fprintf(stderr, "no change\n");
  244. }
  245. }
  246. } else {
  247. fprintf(stderr, "uhh waaat\n");
  248. }
  249. } catch (std::exception &e) {
  250. fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what());
  251. } catch (...) {
  252. fprintf(stderr, "Unknown error on PostgreSQL::save\n");
  253. }
  254. return modified;
  255. }
  256. void PostgreSQL::eraseNetwork(const uint64_t networkId)
  257. {
  258. fprintf(stderr, "PostgreSQL::eraseNetwork\n");
  259. char tmp2[24];
  260. waitForReady();
  261. Utils::hex(networkId, tmp2);
  262. std::pair<nlohmann::json,bool> tmp;
  263. tmp.first["id"] = tmp2;
  264. tmp.first["objtype"] = "_delete_network";
  265. tmp.second = true;
  266. _commitQueue.post(tmp);
  267. nlohmann::json nullJson;
  268. _networkChanged(tmp.first, nullJson, true);
  269. }
  270. void PostgreSQL::eraseMember(const uint64_t networkId, const uint64_t memberId)
  271. {
  272. fprintf(stderr, "PostgreSQL::eraseMember\n");
  273. char tmp2[24];
  274. waitForReady();
  275. std::pair<nlohmann::json,bool> tmp, nw;
  276. Utils::hex(networkId, tmp2);
  277. tmp.first["nwid"] = tmp2;
  278. Utils::hex(memberId, tmp2);
  279. tmp.first["id"] = tmp2;
  280. tmp.first["objtype"] = "_delete_member";
  281. tmp.second = true;
  282. _commitQueue.post(tmp);
  283. nlohmann::json nullJson;
  284. _memberChanged(tmp.first, nullJson, true);
  285. }
  286. void PostgreSQL::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress)
  287. {
  288. std::lock_guard<std::mutex> l(_lastOnline_l);
  289. std::pair<int64_t, InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId, memberId)];
  290. i.first = OSUtils::now();
  291. if (physicalAddress) {
  292. i.second = physicalAddress;
  293. }
  294. }
  295. std::string PostgreSQL::getSSOAuthURL(const nlohmann::json &member, const std::string &redirectURL)
  296. {
  297. // NONCE is just a random character string. no semantic meaning
  298. // state = HMAC SHA384 of Nonce based on shared sso key
  299. //
  300. // need nonce timeout in database? make sure it's used within X time
  301. // X is 5 minutes for now. Make configurable later?
  302. //
  303. // how do we tell when a nonce is used? if auth_expiration_time is set
  304. std::string networkId = member["nwid"];
  305. std::string memberId = member["id"];
  306. char authenticationURL[4096] = {0};
  307. //fprintf(stderr, "PostgreSQL::updateMemberOnLoad: %s-%s\n", networkId.c_str(), memberId.c_str());
  308. bool have_auth = false;
  309. try {
  310. auto c = _pool->borrow();
  311. pqxx::work w(*c->c);
  312. char nonceBytes[16] = {0};
  313. std::string nonce = "";
  314. // check if the member exists first.
  315. pqxx::row count = w.exec_params1("SELECT count(id) FROM ztc_member WHERE id = $1 AND network_id = $2 AND deleted = false", memberId, networkId);
  316. if (count[0].as<int>() == 1) {
  317. // find an unused nonce, if one exists.
  318. pqxx::result r = w.exec_params("SELECT nonce FROM ztc_sso_expiry "
  319. "WHERE network_id = $1 AND member_id = $2 "
  320. "AND authentication_expiry_time IS NULL AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  321. networkId, memberId);
  322. if (r.size() == 1) {
  323. // we have an existing nonce. Use it
  324. nonce = r.at(0)[0].as<std::string>();
  325. Utils::unhex(nonce.c_str(), nonceBytes, sizeof(nonceBytes));
  326. } else if (r.empty()) {
  327. // create a nonce
  328. Utils::getSecureRandom(nonceBytes, 16);
  329. char nonceBuf[64] = {0};
  330. Utils::hex(nonceBytes, sizeof(nonceBytes), nonceBuf);
  331. nonce = std::string(nonceBuf);
  332. pqxx::result ir = w.exec_params0("INSERT INTO ztc_sso_expiry "
  333. "(nonce, nonce_expiration, network_id, member_id) VALUES "
  334. "($1, TO_TIMESTAMP($2::double precision/1000), $3, $4)",
  335. nonce, OSUtils::now() + 300000, networkId, memberId);
  336. w.commit();
  337. } else {
  338. // > 1 ?!? Thats an error!
  339. fprintf(stderr, "> 1 unused nonce!\n");
  340. exit(6);
  341. }
  342. r = w.exec_params("SELECT org.client_id, org.authorization_endpoint "
  343. "FROM ztc_network AS nw, ztc_org AS org "
  344. "WHERE nw.id = $1 AND nw.sso_enabled = true AND org.owner_id = nw.owner_id", networkId);
  345. std::string client_id = "";
  346. std::string authorization_endpoint = "";
  347. if (r.size() == 1) {
  348. client_id = r.at(0)[0].as<std::string>();
  349. authorization_endpoint = r.at(0)[1].as<std::string>();
  350. } else if (r.size() > 1) {
  351. fprintf(stderr, "ERROR: More than one auth endpoint for an organization?!?!? NetworkID: %s\n", networkId.c_str());
  352. } else {
  353. fprintf(stderr, "No client or auth endpoint?!?\n");
  354. }
  355. // no catch all else because we don't actually care if no records exist here. just continue as normal.
  356. if ((!client_id.empty())&&(!authorization_endpoint.empty())) {
  357. have_auth = true;
  358. uint8_t state[48];
  359. HMACSHA384(_ssoPsk, nonceBytes, sizeof(nonceBytes), state);
  360. char state_hex[256];
  361. Utils::hex(state, 48, state_hex);
  362. OSUtils::ztsnprintf(authenticationURL, sizeof(authenticationURL),
  363. "%s?response_type=id_token&response_mode=form_post&scope=openid+email+profile&redirect_uri=%s&nonce=%s&state=%s&client_id=%s",
  364. authorization_endpoint.c_str(),
  365. redirectURL.c_str(),
  366. nonce.c_str(),
  367. state_hex,
  368. client_id.c_str());
  369. } else {
  370. fprintf(stderr, "client_id: %s\nauthorization_endpoint: %s\n", client_id.c_str(), authorization_endpoint.c_str());
  371. }
  372. }
  373. _pool->unborrow(c);
  374. } catch (std::exception &e) {
  375. fprintf(stderr, "ERROR: Error updating member on load: %s\n", e.what());
  376. }
  377. return std::string(authenticationURL);
  378. }
  379. void PostgreSQL::initializeNetworks()
  380. {
  381. try {
  382. std::string setKey = "networks:{" + _myAddressStr + "}";
  383. fprintf(stderr, "Initializing Networks...\n");
  384. char qbuf[2048] = {0};
  385. sprintf(qbuf, "SELECT n.id, (EXTRACT(EPOCH FROM n.creation_time AT TIME ZONE 'UTC')*1000)::bigint as creation_time, n.capabilities, "
  386. "n.enable_broadcast, (EXTRACT(EPOCH FROM n.last_modified AT TIME ZONE 'UTC')*1000)::bigint AS last_modified, n.mtu, n.multicast_limit, n.name, n.private, n.remote_trace_level, "
  387. "n.remote_trace_target, n.revision, n.rules, n.tags, n.v4_assign_mode, n.v6_assign_mode, n.sso_enabled, (CASE WHEN n.sso_enabled THEN o.client_id ELSE NULL END) as client_id, "
  388. "(CASE WHEN n.sso_enabled THEN o.authorization_endpoint ELSE NULL END) as authorization_endpoint, d.domain, d.servers, "
  389. "ARRAY(SELECT CONCAT(host(ip_range_start),'|', host(ip_range_end)) FROM ztc_network_assignment_pool WHERE network_id = n.id) AS assignment_pool, "
  390. "ARRAY(SELECT CONCAT(host(address),'/',bits::text,'|',COALESCE(host(via), 'NULL'))FROM ztc_network_route WHERE network_id = n.id) AS routes "
  391. "FROM ztc_network n "
  392. "LEFT OUTER JOIN ztc_org o "
  393. " ON o.owner_id = n.owner_id "
  394. "LEFT OUTER JOIN ztc_network_dns d "
  395. " ON d.network_id = n.id "
  396. "WHERE deleted = false AND controller_id = '%s'", _myAddressStr.c_str());
  397. auto c = _pool->borrow();
  398. auto c2 = _pool->borrow();
  399. pqxx::work w{*c->c};
  400. auto stream = pqxx::stream_from::query(w, qbuf);
  401. std::tuple<
  402. std::string // network ID
  403. , std::optional<int64_t> // creationTime
  404. , std::optional<std::string> // capabilities
  405. , std::optional<bool> // enableBroadcast
  406. , std::optional<uint64_t> // lastModified
  407. , std::optional<int> // mtu
  408. , std::optional<int> // multicastLimit
  409. , std::optional<std::string> // name
  410. , bool // private
  411. , std::optional<int> // remoteTraceLevel
  412. , std::optional<std::string> // remoteTraceTarget
  413. , std::optional<uint64_t> // revision
  414. , std::optional<std::string> // rules
  415. , std::optional<std::string> // tags
  416. , std::optional<std::string> // v4AssignMode
  417. , std::optional<std::string> // v6AssignMode
  418. , std::optional<bool> // ssoEnabled
  419. , std::optional<std::string> // clientId
  420. , std::optional<std::string> // authorizationEndpoint
  421. , std::optional<std::string> // domain
  422. , std::optional<std::string> // servers
  423. , std::string // assignmentPoolString
  424. , std::string // routeString
  425. > row;
  426. uint64_t count = 0;
  427. auto tmp = std::chrono::high_resolution_clock::now();
  428. uint64_t total = 0;
  429. while (stream >> row) {
  430. auto start = std::chrono::high_resolution_clock::now();
  431. json empty;
  432. json config;
  433. initNetwork(config);
  434. std::string nwid = std::get<0>(row);
  435. std::optional<int64_t> creationTime = std::get<1>(row);
  436. std::optional<std::string> capabilities = std::get<2>(row);
  437. std::optional<bool> enableBroadcast = std::get<3>(row);
  438. std::optional<uint64_t> lastModified = std::get<4>(row);
  439. std::optional<int> mtu = std::get<5>(row);
  440. std::optional<int> multicastLimit = std::get<6>(row);
  441. std::optional<std::string> name = std::get<7>(row);
  442. bool isPrivate = std::get<8>(row);
  443. std::optional<int> remoteTraceLevel = std::get<9>(row);
  444. std::optional<std::string> remoteTraceTarget = std::get<10>(row);
  445. std::optional<uint64_t> revision = std::get<11>(row);
  446. std::optional<std::string> rules = std::get<12>(row);
  447. std::optional<std::string> tags = std::get<13>(row);
  448. std::optional<std::string> v4AssignMode = std::get<14>(row);
  449. std::optional<std::string> v6AssignMode = std::get<15>(row);
  450. std::optional<bool> ssoEnabled = std::get<16>(row);
  451. std::optional<std::string> clientId = std::get<17>(row);
  452. std::optional<std::string> authorizationEndpoint = std::get<18>(row);
  453. std::optional<std::string> dnsDomain = std::get<19>(row);
  454. std::optional<std::string> dnsServers = std::get<20>(row);
  455. std::string assignmentPoolString = std::get<21>(row);
  456. std::string routesString = std::get<22>(row);
  457. config["id"] = nwid;
  458. config["nwid"] = nwid;
  459. config["creationTime"] = creationTime.value_or(0);
  460. config["capabilities"] = json::parse(capabilities.value_or("[]"));
  461. config["enableBroadcast"] = enableBroadcast.value_or(false);
  462. config["lastModified"] = lastModified.value_or(0);
  463. config["mtu"] = mtu.value_or(2800);
  464. config["multicastLimit"] = multicastLimit.value_or(64);
  465. config["name"] = name.value_or("");
  466. config["private"] = isPrivate;
  467. config["remoteTraceLevel"] = remoteTraceLevel.value_or(0);
  468. config["remoteTraceTarget"] = remoteTraceTarget.value_or("");
  469. config["revision"] = revision.value_or(0);
  470. config["rules"] = json::parse(rules.value_or("[]"));
  471. config["tags"] = json::parse(tags.value_or("[]"));
  472. config["v4AssignMode"] = json::parse(v4AssignMode.value_or("{}"));
  473. config["v6AssignMode"] = json::parse(v6AssignMode.value_or("{}"));
  474. config["ssoEnabled"] = ssoEnabled.value_or(false);
  475. config["objtype"] = "network";
  476. config["ipAssignmentPools"] = json::array();
  477. config["routes"] = json::array();
  478. config["clientId"] = clientId.value_or("");
  479. config["authorizationEndpoint"] = authorizationEndpoint.value_or("");
  480. if (dnsDomain.has_value()) {
  481. std::string serverList = dnsServers.value();
  482. json obj;
  483. auto servers = json::array();
  484. if (serverList.rfind("{",0) != std::string::npos) {
  485. serverList = serverList.substr(1, serverList.size()-2);
  486. std::stringstream ss(serverList);
  487. while(ss.good()) {
  488. std::string server;
  489. std::getline(ss, server, ',');
  490. servers.push_back(server);
  491. }
  492. }
  493. obj["domain"] = dnsDomain.value();
  494. obj["servers"] = servers;
  495. config["dns"] = obj;
  496. }
  497. config["ipAssignmentPools"] = json::array();
  498. if (assignmentPoolString != "{}") {
  499. std::string tmp = assignmentPoolString.substr(1, assignmentPoolString.size()-2);
  500. std::vector<std::string> assignmentPools = split(tmp, ',');
  501. for (auto it = assignmentPools.begin(); it != assignmentPools.end(); ++it) {
  502. std::vector<std::string> r = split(*it, '|');
  503. json ip;
  504. ip["ipRangeStart"] = r[0];
  505. ip["ipRangeEnd"] = r[1];
  506. config["ipAssignmentPools"].push_back(ip);
  507. }
  508. }
  509. config["routes"] = json::array();
  510. if (routesString != "{}") {
  511. std::string tmp = routesString.substr(1, routesString.size()-2);
  512. std::vector<std::string> routes = split(tmp, ',');
  513. for (auto it = routes.begin(); it != routes.end(); ++it) {
  514. std::vector<std::string> r = split(*it, '|');
  515. json route;
  516. route["target"] = r[0];
  517. route["via"] = ((route["via"] == "NULL")? nullptr : r[1]);
  518. config["routes"].push_back(route);
  519. }
  520. }
  521. _networkChanged(empty, config, false);
  522. auto end = std::chrono::high_resolution_clock::now();
  523. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);;
  524. total += dur.count();
  525. ++count;
  526. if (count > 0 && count % 10000 == 0) {
  527. fprintf(stderr, "Averaging %llu us per network\n", (total/count));
  528. }
  529. }
  530. if (count > 0) {
  531. fprintf(stderr, "Took %llu us per network to load\n", (total/count));
  532. }
  533. stream.complete();
  534. w.commit();
  535. _pool->unborrow(c2);
  536. _pool->unborrow(c);
  537. if (++this->_ready == 2) {
  538. if (_waitNoticePrinted) {
  539. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  540. }
  541. _readyLock.unlock();
  542. }
  543. } catch (sw::redis::Error &e) {
  544. fprintf(stderr, "ERROR: Error initializing networks in Redis: %s\n", e.what());
  545. exit(-1);
  546. } catch (std::exception &e) {
  547. fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
  548. exit(-1);
  549. }
  550. }
  551. void PostgreSQL::initializeMembers()
  552. {
  553. std::string memberId;
  554. std::string networkId;
  555. try {
  556. std::unordered_map<std::string, std::string> networkMembers;
  557. fprintf(stderr, "Initializing Members...\n");
  558. char qbuf[2048];
  559. sprintf(qbuf, "SELECT m.id, m.network_id, m.active_bridge, m.authorized, m.capabilities, (EXTRACT(EPOCH FROM m.creation_time AT TIME ZONE 'UTC')*1000)::bigint, m.identity, "
  560. " (EXTRACT(EPOCH FROM m.last_authorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  561. " (EXTRACT(EPOCH FROM m.last_deauthorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  562. " m.remote_trace_level, m.remote_trace_target, m.tags, m.v_major, m.v_minor, m.v_rev, m.v_proto, "
  563. " m.no_auto_assign_ips, m.revision, sso_exempt, "
  564. " (SELECT (EXTRACT(EPOCH FROM e.authentication_expiry_time)*1000)::bigint "
  565. " FROM ztc_sso_expiry e "
  566. " INNER JOIN ztc_network n1 "
  567. " ON n.id = e.network_id "
  568. " WHERE e.network_id = m.network_id AND e.member_id = m.id AND n.sso_enabled = TRUE AND e.authentication_expiry_time IS NOT NULL "
  569. " ORDER BY e.authentication_expiry_time DESC LIMIT 1) AS authentication_expiry_time, "
  570. " ARRAY(SELECT DISTINCT address FROM ztc_member_ip_assignment WHERE member_id = m.id AND network_id = m.network_id) AS assigned_addresses "
  571. "FROM ztc_member m "
  572. "INNER JOIN ztc_network n "
  573. " ON n.id = m.network_id "
  574. "WHERE n.controller_id = '%s' AND m.deleted = false", _myAddressStr.c_str());
  575. auto c = _pool->borrow();
  576. auto c2 = _pool->borrow();
  577. pqxx::work w{*c->c};
  578. auto stream = pqxx::stream_from::query(w, qbuf);
  579. std::tuple<
  580. std::string // memberId
  581. , std::string // memberId
  582. , std::optional<bool> // activeBridge
  583. , std::optional<bool> // authorized
  584. , std::optional<std::string> // capabilities
  585. , std::optional<uint64_t> // creationTime
  586. , std::optional<std::string> // identity
  587. , std::optional<uint64_t> // lastAuthorizedTime
  588. , std::optional<uint64_t> // lastDeauthorizedTime
  589. , std::optional<int> // remoteTraceLevel
  590. , std::optional<std::string> // remoteTraceTarget
  591. , std::optional<std::string> // tags
  592. , std::optional<int> // vMajor
  593. , std::optional<int> // vMinor
  594. , std::optional<int> // vRev
  595. , std::optional<int> // vProto
  596. , std::optional<bool> // noAutoAssignIps
  597. , std::optional<uint64_t> // revision
  598. , std::optional<bool> // ssoExempt
  599. , std::optional<uint64_t> // authenticationExpiryTime
  600. , std::string // assignedAddresses
  601. > row;
  602. uint64_t count = 0;
  603. auto tmp = std::chrono::high_resolution_clock::now();
  604. uint64_t total = 0;
  605. while (stream >> row) {
  606. auto start = std::chrono::high_resolution_clock::now();
  607. json empty;
  608. json config;
  609. initMember(config);
  610. memberId = std::get<0>(row);
  611. networkId = std::get<1>(row);
  612. std::optional<bool> activeBridge = std::get<2>(row);
  613. std::optional<bool> authorized = std::get<3>(row);
  614. std::optional<std::string> capabilities = std::get<4>(row);
  615. std::optional<uint64_t> creationTime = std::get<5>(row);
  616. std::optional<std::string> identity = std::get<6>(row);
  617. std::optional<uint64_t> lastAuthorizedTime = std::get<7>(row);
  618. std::optional<uint64_t> lastDeauthorizedTime = std::get<8>(row);
  619. std::optional<int> remoteTraceLevel = std::get<9>(row);
  620. std::optional<std::string> remoteTraceTarget = std::get<10>(row);
  621. std::optional<std::string> tags = std::get<11>(row);
  622. std::optional<int> vMajor = std::get<12>(row);
  623. std::optional<int> vMinor = std::get<13>(row);
  624. std::optional<int> vRev = std::get<14>(row);
  625. std::optional<int> vProto = std::get<15>(row);
  626. std::optional<bool> noAutoAssignIps = std::get<16>(row);
  627. std::optional<uint64_t> revision = std::get<17>(row);
  628. std::optional<bool> ssoExempt = std::get<18>(row);
  629. std::optional<uint64_t> authenticationExpiryTime = std::get<19>(row);
  630. std::string assignedAddresses = std::get<20>(row);
  631. config["id"] = memberId;
  632. config["nwid"] = networkId;
  633. config["activeBridge"] = activeBridge.value_or(false);
  634. config["authorized"] = authorized.value_or(false);
  635. config["capabilities"] = json::parse(capabilities.value_or("[]"));
  636. config["creationTime"] = creationTime.value_or(0);
  637. config["identity"] = identity.value_or("");
  638. config["lastAuthorizedTime"] = lastAuthorizedTime.value_or(0);
  639. config["lastDeauthorizedTime"] = lastDeauthorizedTime.value_or(0);
  640. config["remoteTraceLevel"] = remoteTraceLevel.value_or(0);
  641. config["remoteTraceTarget"] = remoteTraceTarget.value_or("");
  642. config["tags"] = json::parse(tags.value_or("[]"));
  643. config["vMajor"] = vMajor.value_or(-1);
  644. config["vMinor"] = vMinor.value_or(-1);
  645. config["vRev"] = vRev.value_or(-1);
  646. config["vProto"] = vProto.value_or(-1);
  647. config["noAutoAssignIps"] = noAutoAssignIps.value_or(false);
  648. config["revision"] = revision.value_or(0);
  649. config["ssoExempt"] = ssoExempt.value_or(false);
  650. config["authenticationExpiryTime"] = authenticationExpiryTime.value_or(0);
  651. config["objtype"] = "member";
  652. config["ipAssignments"] = json::array();
  653. if (assignedAddresses != "{}") {
  654. std::string tmp = assignedAddresses.substr(1, assignedAddresses.size()-2);
  655. std::vector<std::string> addrs = split(tmp, ',');
  656. for (auto it = addrs.begin(); it != addrs.end(); ++it) {
  657. config["ipAssignments"].push_back(*it);
  658. }
  659. }
  660. _memberChanged(empty, config, false);
  661. memberId = "";
  662. networkId = "";
  663. auto end = std::chrono::high_resolution_clock::now();
  664. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);;
  665. total += dur.count();
  666. ++count;
  667. if (count > 0 && count % 10000 == 0) {
  668. fprintf(stderr, "Averaging %llu us per member\n", (total/count));
  669. }
  670. }
  671. if (count > 0) {
  672. fprintf(stderr, "Took %llu us per member to load\n", (total/count));
  673. }
  674. stream.complete();
  675. w.commit();
  676. _pool->unborrow(c2);
  677. _pool->unborrow(c);
  678. if (++this->_ready == 2) {
  679. if (_waitNoticePrinted) {
  680. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  681. }
  682. _readyLock.unlock();
  683. }
  684. } catch (sw::redis::Error &e) {
  685. fprintf(stderr, "ERROR: Error initializing members (redis): %s\n", e.what());
  686. } catch (std::exception &e) {
  687. fprintf(stderr, "ERROR: Error initializing member: %s-%s %s\n", networkId.c_str(), memberId.c_str(), e.what());
  688. exit(-1);
  689. }
  690. }
  691. void PostgreSQL::heartbeat()
  692. {
  693. char publicId[1024];
  694. char hostnameTmp[1024];
  695. _myId.toString(false,publicId);
  696. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  697. hostnameTmp[0] = (char)0;
  698. } else {
  699. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  700. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  701. hostnameTmp[i] = (char)0;
  702. break;
  703. }
  704. }
  705. }
  706. const char *controllerId = _myAddressStr.c_str();
  707. const char *publicIdentity = publicId;
  708. const char *hostname = hostnameTmp;
  709. while (_run == 1) {
  710. // fprintf(stderr, "%s: heartbeat\n", controllerId);
  711. auto c = _pool->borrow();
  712. int64_t ts = OSUtils::now();
  713. if(c->c) {
  714. pqxx::work w{*c->c};
  715. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  716. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  717. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  718. std::string build = std::to_string(ZEROTIER_ONE_VERSION_BUILD);
  719. std::string now = std::to_string(ts);
  720. std::string host_port = std::to_string(_listenPort);
  721. std::string use_redis = (_rc != NULL) ? "true" : "false";
  722. try {
  723. pqxx::result res = w.exec0("INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build, host_port, use_redis) "
  724. "VALUES ("+w.quote(controllerId)+", "+w.quote(hostname)+", TO_TIMESTAMP("+now+"::double precision/1000), "+
  725. w.quote(publicIdentity)+", "+major+", "+minor+", "+rev+", "+build+", "+host_port+", "+use_redis+") "
  726. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  727. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  728. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev, host_port = EXCLUDED.host_port, "
  729. "use_redis = EXCLUDED.use_redis");
  730. } catch (std::exception &e) {
  731. fprintf(stderr, "Heartbeat update failed: %s\n", e.what());
  732. w.abort();
  733. _pool->unborrow(c);
  734. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  735. continue;
  736. }
  737. w.commit();
  738. }
  739. _pool->unborrow(c);
  740. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  741. }
  742. fprintf(stderr, "Exited heartbeat thread\n");
  743. }
  744. void PostgreSQL::membersDbWatcher()
  745. {
  746. if (_rc) {
  747. _membersWatcher_Redis();
  748. } else {
  749. _membersWatcher_Postgres();
  750. }
  751. if (_run == 1) {
  752. fprintf(stderr, "ERROR: %s membersDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  753. exit(9);
  754. }
  755. fprintf(stderr, "Exited membersDbWatcher\n");
  756. }
  757. void PostgreSQL::_membersWatcher_Postgres() {
  758. auto c = _pool->borrow();
  759. std::string stream = "member_" + _myAddressStr;
  760. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  761. MemberNotificationReceiver m(this, *c->c, stream);
  762. while(_run == 1) {
  763. c->c->await_notification(5, 0);
  764. }
  765. _pool->unborrow(c);
  766. }
  767. void PostgreSQL::_membersWatcher_Redis() {
  768. char buf[11] = {0};
  769. std::string key = "member-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  770. fprintf(stderr, "Listening to member stream: %s\n", key.c_str());
  771. while (_run == 1) {
  772. try {
  773. json tmp;
  774. std::unordered_map<std::string, ItemStream> result;
  775. if (_rc->clusterMode) {
  776. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  777. } else {
  778. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  779. }
  780. if (!result.empty()) {
  781. for (auto element : result) {
  782. #ifdef ZT_TRACE
  783. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  784. #endif
  785. for (auto rec : element.second) {
  786. std::string id = rec.first;
  787. auto attrs = rec.second;
  788. #ifdef ZT_TRACE
  789. fprintf(stdout, "Record ID: %s\n", id.c_str());
  790. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  791. #endif
  792. for (auto a : attrs) {
  793. #ifdef ZT_TRACE
  794. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  795. #endif
  796. try {
  797. tmp = json::parse(a.second);
  798. json &ov = tmp["old_val"];
  799. json &nv = tmp["new_val"];
  800. json oldConfig, newConfig;
  801. if (ov.is_object()) oldConfig = ov;
  802. if (nv.is_object()) newConfig = nv;
  803. if (oldConfig.is_object()||newConfig.is_object()) {
  804. _memberChanged(oldConfig,newConfig,(this->_ready >= 2));
  805. }
  806. } catch (...) {
  807. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  808. }
  809. }
  810. if (_rc->clusterMode) {
  811. _cluster->xdel(key, id);
  812. } else {
  813. _redis->xdel(key, id);
  814. }
  815. }
  816. }
  817. }
  818. } catch (sw::redis::Error &e) {
  819. fprintf(stderr, "Error in Redis members watcher: %s\n", e.what());
  820. }
  821. }
  822. fprintf(stderr, "membersWatcher ended\n");
  823. }
  824. void PostgreSQL::networksDbWatcher()
  825. {
  826. if (_rc) {
  827. _networksWatcher_Redis();
  828. } else {
  829. _networksWatcher_Postgres();
  830. }
  831. if (_run == 1) {
  832. fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  833. exit(8);
  834. }
  835. fprintf(stderr, "Exited networksDbWatcher\n");
  836. }
  837. void PostgreSQL::_networksWatcher_Postgres() {
  838. std::string stream = "network_" + _myAddressStr;
  839. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  840. auto c = _pool->borrow();
  841. NetworkNotificationReceiver n(this, *c->c, stream);
  842. while(_run == 1) {
  843. c->c->await_notification(5,0);
  844. }
  845. }
  846. void PostgreSQL::_networksWatcher_Redis() {
  847. char buf[11] = {0};
  848. std::string key = "network-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  849. while (_run == 1) {
  850. try {
  851. json tmp;
  852. std::unordered_map<std::string, ItemStream> result;
  853. if (_rc->clusterMode) {
  854. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  855. } else {
  856. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  857. }
  858. if (!result.empty()) {
  859. for (auto element : result) {
  860. #ifdef ZT_TRACE
  861. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  862. #endif
  863. for (auto rec : element.second) {
  864. std::string id = rec.first;
  865. auto attrs = rec.second;
  866. #ifdef ZT_TRACE
  867. fprintf(stdout, "Record ID: %s\n", id.c_str());
  868. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  869. #endif
  870. for (auto a : attrs) {
  871. #ifdef ZT_TRACE
  872. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  873. #endif
  874. try {
  875. tmp = json::parse(a.second);
  876. json &ov = tmp["old_val"];
  877. json &nv = tmp["new_val"];
  878. json oldConfig, newConfig;
  879. if (ov.is_object()) oldConfig = ov;
  880. if (nv.is_object()) newConfig = nv;
  881. if (oldConfig.is_object()||newConfig.is_object()) {
  882. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  883. }
  884. } catch (...) {
  885. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  886. }
  887. }
  888. if (_rc->clusterMode) {
  889. _cluster->xdel(key, id);
  890. } else {
  891. _redis->xdel(key, id);
  892. }
  893. }
  894. }
  895. }
  896. } catch (sw::redis::Error &e) {
  897. fprintf(stderr, "Error in Redis networks watcher: %s\n", e.what());
  898. }
  899. }
  900. fprintf(stderr, "networksWatcher ended\n");
  901. }
  902. void PostgreSQL::commitThread()
  903. {
  904. fprintf(stderr, "%s: commitThread start\n", _myAddressStr.c_str());
  905. std::pair<nlohmann::json,bool> qitem;
  906. while(_commitQueue.get(qitem)&(_run == 1)) {
  907. //fprintf(stderr, "commitThread tick\n");
  908. if (!qitem.first.is_object()) {
  909. fprintf(stderr, "not an object\n");
  910. continue;
  911. }
  912. std::shared_ptr<PostgresConnection> c;
  913. try {
  914. c = _pool->borrow();
  915. } catch (std::exception &e) {
  916. fprintf(stderr, "ERROR: %s\n", e.what());
  917. continue;
  918. }
  919. if (!c) {
  920. fprintf(stderr, "Error getting database connection\n");
  921. continue;
  922. }
  923. try {
  924. nlohmann::json *config = &(qitem.first);
  925. const std::string objtype = (*config)["objtype"];
  926. if (objtype == "member") {
  927. // fprintf(stderr, "%s: commitThread: member\n", _myAddressStr.c_str());
  928. try {
  929. pqxx::work w(*c->c);
  930. std::string memberId = (*config)["id"];
  931. std::string networkId = (*config)["nwid"];
  932. std::string target = "NULL";
  933. if (!(*config)["remoteTraceTarget"].is_null()) {
  934. target = (*config)["remoteTraceTarget"];
  935. }
  936. pqxx::result res = w.exec_params0(
  937. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  938. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  939. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  940. "VALUES ($1, $2, $3, $4, $5, $6, "
  941. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  942. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  943. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  944. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  945. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  946. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  947. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  948. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  949. memberId,
  950. networkId,
  951. (bool)(*config)["activeBridge"],
  952. (bool)(*config)["authorized"],
  953. OSUtils::jsonDump((*config)["capabilities"], -1),
  954. OSUtils::jsonString((*config)["identity"], ""),
  955. (uint64_t)(*config)["lastAuthorizedTime"],
  956. (uint64_t)(*config)["lastDeauthorizedTime"],
  957. (bool)(*config)["noAutoAssignIps"],
  958. (int)(*config)["remoteTraceLevel"],
  959. target,
  960. (uint64_t)(*config)["revision"],
  961. OSUtils::jsonDump((*config)["tags"], -1),
  962. (int)(*config)["vMajor"],
  963. (int)(*config)["vMinor"],
  964. (int)(*config)["vRev"],
  965. (int)(*config)["vProto"]);
  966. res = w.exec_params0("DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  967. memberId, networkId);
  968. std::vector<std::string> assignments;
  969. bool ipAssignError = false;
  970. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  971. std::string addr = *i;
  972. if (std::find(assignments.begin(), assignments.end(), addr) != assignments.end()) {
  973. continue;
  974. }
  975. res = w.exec_params0(
  976. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3) ON CONFLICT (network_id, member_id, address) DO NOTHING",
  977. memberId, networkId, addr);
  978. assignments.push_back(addr);
  979. }
  980. if (ipAssignError) {
  981. fprintf(stderr, "%s: ipAssignError\n", _myAddressStr.c_str());
  982. delete config;
  983. config = nullptr;
  984. w.abort();
  985. _pool->unborrow(c);
  986. c.reset();
  987. continue;
  988. }
  989. w.commit();
  990. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  991. const uint64_t memberidInt = OSUtils::jsonIntHex((*config)["id"], 0ULL);
  992. if (nwidInt && memberidInt) {
  993. nlohmann::json nwOrig;
  994. nlohmann::json memOrig;
  995. nlohmann::json memNew(*config);
  996. get(nwidInt, nwOrig, memberidInt, memOrig);
  997. _memberChanged(memOrig, memNew, qitem.second);
  998. } else {
  999. fprintf(stderr, "%s: Can't notify of change. Error parsing nwid or memberid: %llu-%llu\n", _myAddressStr.c_str(), (unsigned long long)nwidInt, (unsigned long long)memberidInt);
  1000. }
  1001. } catch (std::exception &e) {
  1002. fprintf(stderr, "%s ERROR: Error updating member: %s\n", _myAddressStr.c_str(), e.what());
  1003. }
  1004. } else if (objtype == "network") {
  1005. try {
  1006. // fprintf(stderr, "%s: commitThread: network\n", _myAddressStr.c_str());
  1007. pqxx::work w(*c->c);
  1008. std::string id = (*config)["id"];
  1009. std::string remoteTraceTarget = "";
  1010. if(!(*config)["remoteTraceTarget"].is_null()) {
  1011. remoteTraceTarget = (*config)["remoteTraceTarget"];
  1012. }
  1013. std::string rulesSource = "";
  1014. if ((*config)["rulesSource"].is_string()) {
  1015. rulesSource = (*config)["rulesSource"];
  1016. }
  1017. // This ugly query exists because when we want to mirror networks to/from
  1018. // another data store (e.g. FileDB or LFDB) it is possible to get a network
  1019. // that doesn't exist in Central's database. This does an upsert and sets
  1020. // the owner_id to the "first" global admin in the user DB if the record
  1021. // did not previously exist. If the record already exists owner_id is left
  1022. // unchanged, so owner_id should be left out of the update clause.
  1023. pqxx::result res = w.exec_params0(
  1024. "INSERT INTO ztc_network (id, creation_time, owner_id, controller_id, capabilities, enable_broadcast, "
  1025. "last_modified, mtu, multicast_limit, name, private, "
  1026. "remote_trace_level, remote_trace_target, rules, rules_source, "
  1027. "tags, v4_assign_mode, v6_assign_mode, sso_enabled) VALUES ("
  1028. "$1, TO_TIMESTAMP($5::double precision/1000), "
  1029. "(SELECT user_id AS owner_id FROM ztc_global_permissions WHERE authorize = true AND del = true AND modify = true AND read = true LIMIT 1),"
  1030. "$2, $3, $4, TO_TIMESTAMP($5::double precision/1000), "
  1031. "$6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, 17) "
  1032. "ON CONFLICT (id) DO UPDATE set controller_id = EXCLUDED.controller_id, "
  1033. "capabilities = EXCLUDED.capabilities, enable_broadcast = EXCLUDED.enable_broadcast, "
  1034. "last_modified = EXCLUDED.last_modified, mtu = EXCLUDED.mtu, "
  1035. "multicast_limit = EXCLUDED.multicast_limit, name = EXCLUDED.name, "
  1036. "private = EXCLUDED.private, remote_trace_level = EXCLUDED.remote_trace_level, "
  1037. "remote_trace_target = EXCLUDED.remote_trace_target, rules = EXCLUDED.rules, "
  1038. "rules_source = EXCLUDED.rules_source, tags = EXCLUDED.tags, "
  1039. "v4_assign_mode = EXCLUDED.v4_assign_mode, v6_assign_mode = EXCLUDED.v6_assign_mode, "
  1040. "sso_enabled = EXCLUDED.sso_enabled",
  1041. id,
  1042. _myAddressStr,
  1043. OSUtils::jsonDump((*config)["capabilitles"], -1),
  1044. (bool)(*config)["enableBroadcast"],
  1045. OSUtils::now(),
  1046. (int)(*config)["mtu"],
  1047. (int)(*config)["multicastLimit"],
  1048. OSUtils::jsonString((*config)["name"],""),
  1049. (bool)(*config)["private"],
  1050. (int)(*config)["remoteTraceLevel"],
  1051. remoteTraceTarget,
  1052. OSUtils::jsonDump((*config)["rules"], -1),
  1053. rulesSource,
  1054. OSUtils::jsonDump((*config)["tags"], -1),
  1055. OSUtils::jsonDump((*config)["v4AssignMode"],-1),
  1056. OSUtils::jsonDump((*config)["v6AssignMode"], -1),
  1057. OSUtils::jsonBool((*config)["ssoEnabled"], false));
  1058. res = w.exec_params0("DELETE FROM ztc_network_assignment_pool WHERE network_id = $1", 0);
  1059. auto pool = (*config)["ipAssignmentPools"];
  1060. bool err = false;
  1061. for (auto i = pool.begin(); i != pool.end(); ++i) {
  1062. std::string start = (*i)["ipRangeStart"];
  1063. std::string end = (*i)["ipRangeEnd"];
  1064. res = w.exec_params0(
  1065. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  1066. "VALUES ($1, $2, $3)", id, start, end);
  1067. }
  1068. res = w.exec_params0("DELETE FROM ztc_network_route WHERE network_id = $1", id);
  1069. auto routes = (*config)["routes"];
  1070. err = false;
  1071. for (auto i = routes.begin(); i != routes.end(); ++i) {
  1072. std::string t = (*i)["target"];
  1073. std::vector<std::string> target;
  1074. std::istringstream f(t);
  1075. std::string s;
  1076. while(std::getline(f, s, '/')) {
  1077. target.push_back(s);
  1078. }
  1079. if (target.empty() || target.size() != 2) {
  1080. continue;
  1081. }
  1082. std::string targetAddr = target[0];
  1083. std::string targetBits = target[1];
  1084. std::string via = "NULL";
  1085. if (!(*i)["via"].is_null()) {
  1086. via = (*i)["via"];
  1087. }
  1088. res = w.exec_params0("INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  1089. id, targetAddr, targetBits, (via == "NULL" ? NULL : via.c_str()));
  1090. }
  1091. if (err) {
  1092. fprintf(stderr, "%s: route add error\n", _myAddressStr.c_str());
  1093. w.abort();
  1094. _pool->unborrow(c);
  1095. delete config;
  1096. config = nullptr;
  1097. continue;
  1098. }
  1099. auto dns = (*config)["dns"];
  1100. std::string domain = dns["domain"];
  1101. std::stringstream servers;
  1102. servers << "{";
  1103. for (auto j = dns["servers"].begin(); j < dns["servers"].end(); ++j) {
  1104. servers << *j;
  1105. if ( (j+1) != dns["servers"].end()) {
  1106. servers << ",";
  1107. }
  1108. }
  1109. servers << "}";
  1110. std::string s = servers.str();
  1111. res = w.exec_params0("INSERT INTO ztc_network_dns (network_id, domain, servers) VALUES ($1, $2, $3) ON CONFLICT (network_id) DO UPDATE SET domain = EXCLUDED.domain, servers = EXCLUDED.servers",
  1112. id, domain, s);
  1113. w.commit();
  1114. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  1115. if (nwidInt) {
  1116. nlohmann::json nwOrig;
  1117. nlohmann::json nwNew(*config);
  1118. get(nwidInt, nwOrig);
  1119. _networkChanged(nwOrig, nwNew, qitem.second);
  1120. } else {
  1121. fprintf(stderr, "%s: Can't notify network changed: %llu\n", _myAddressStr.c_str(), (unsigned long long)nwidInt);
  1122. }
  1123. } catch (std::exception &e) {
  1124. fprintf(stderr, "%s ERROR: Error updating network: %s\n", _myAddressStr.c_str(), e.what());
  1125. }
  1126. } else if (objtype == "_delete_network") {
  1127. // fprintf(stderr, "%s: commitThread: delete network\n", _myAddressStr.c_str());
  1128. try {
  1129. pqxx::work w(*c->c);
  1130. std::string networkId = (*config)["nwid"];
  1131. pqxx::result res = w.exec_params0("UPDATE ztc_network SET deleted = true WHERE id = $1",
  1132. networkId);
  1133. w.commit();
  1134. } catch (std::exception &e) {
  1135. fprintf(stderr, "%s ERROR: Error deleting network: %s\n", _myAddressStr.c_str(), e.what());
  1136. }
  1137. } else if (objtype == "_delete_member") {
  1138. // fprintf(stderr, "%s commitThread: delete member\n", _myAddressStr.c_str());
  1139. try {
  1140. pqxx::work w(*c->c);
  1141. std::string memberId = (*config)["id"];
  1142. std::string networkId = (*config)["nwid"];
  1143. pqxx::result res = w.exec_params0(
  1144. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  1145. memberId, networkId);
  1146. w.commit();
  1147. } catch (std::exception &e) {
  1148. fprintf(stderr, "%s ERROR: Error deleting member: %s\n", _myAddressStr.c_str(), e.what());
  1149. }
  1150. } else {
  1151. fprintf(stderr, "%s ERROR: unknown objtype\n", _myAddressStr.c_str());
  1152. }
  1153. } catch (std::exception &e) {
  1154. fprintf(stderr, "%s ERROR: Error getting objtype: %s\n", _myAddressStr.c_str(), e.what());
  1155. }
  1156. _pool->unborrow(c);
  1157. c.reset();
  1158. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1159. }
  1160. fprintf(stderr, "%s commitThread finished\n", _myAddressStr.c_str());
  1161. }
  1162. void PostgreSQL::onlineNotificationThread()
  1163. {
  1164. waitForReady();
  1165. onlineNotification_Postgres();
  1166. }
  1167. void PostgreSQL::onlineNotification_Postgres()
  1168. {
  1169. _connected = 1;
  1170. nlohmann::json jtmp1, jtmp2;
  1171. while (_run == 1) {
  1172. auto c = _pool->borrow();
  1173. try {
  1174. fprintf(stderr, "%s onlineNotification_Postgres\n", _myAddressStr.c_str());
  1175. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1176. {
  1177. std::lock_guard<std::mutex> l(_lastOnline_l);
  1178. lastOnline.swap(_lastOnline);
  1179. }
  1180. pqxx::work w(*c->c);
  1181. // using pqxx::stream_to would be a really nice alternative here, but
  1182. // unfortunately it doesn't support upserts.
  1183. // fprintf(stderr, "online notification tick\n");
  1184. std::stringstream memberUpdate;
  1185. memberUpdate << "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ";
  1186. bool firstRun = true;
  1187. bool memberAdded = false;
  1188. int updateCount = 0;
  1189. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1190. updateCount += 1;
  1191. uint64_t nwid_i = i->first.first;
  1192. char nwidTmp[64];
  1193. char memTmp[64];
  1194. char ipTmp[64];
  1195. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1196. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  1197. if(!get(nwid_i, jtmp1, i->first.second, jtmp2)) {
  1198. continue; // skip non existent networks/members
  1199. }
  1200. std::string networkId(nwidTmp);
  1201. std::string memberId(memTmp);
  1202. const char *qvals[2] = {
  1203. networkId.c_str(),
  1204. memberId.c_str()
  1205. };
  1206. try {
  1207. pqxx::row r = w.exec_params1("SELECT id, network_id FROM ztc_member WHERE network_id = $1 AND id = $2",
  1208. networkId, memberId);
  1209. } catch (pqxx::unexpected_rows &e) {
  1210. // fprintf(stderr, "Member count failed: %s\n", e.what());
  1211. continue;
  1212. }
  1213. int64_t ts = i->second.first;
  1214. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1215. std::string timestamp = std::to_string(ts);
  1216. if (firstRun) {
  1217. firstRun = false;
  1218. } else {
  1219. memberUpdate << ", ";
  1220. }
  1221. memberUpdate << "('" << networkId << "', '" << memberId << "', ";
  1222. if (ipAddr.empty()) {
  1223. memberUpdate << "NULL, ";
  1224. } else {
  1225. memberUpdate << "'" << ipAddr << "', ";
  1226. }
  1227. memberUpdate << "TO_TIMESTAMP(" << timestamp << "::double precision/1000))";
  1228. memberAdded = true;
  1229. }
  1230. memberUpdate << " ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated;";
  1231. if (memberAdded) {
  1232. //fprintf(stderr, "%s\n", memberUpdate.str().c_str());
  1233. pqxx::result res = w.exec0(memberUpdate.str());
  1234. w.commit();
  1235. }
  1236. fprintf(stderr, "%s: Updated online status of %d members\n", _myAddressStr.c_str(), updateCount);
  1237. } catch (std::exception &e) {
  1238. fprintf(stderr, "%s: error in onlinenotification thread: %s\n", _myAddressStr.c_str(), e.what());
  1239. }
  1240. _pool->unborrow(c);
  1241. ConnectionPoolStats stats = _pool->get_stats();
  1242. fprintf(stderr, "%s pool stats: in use size: %llu, available size: %llu, total: %llu\n",
  1243. _myAddressStr.c_str(), stats.borrowed_size, stats.pool_size, (stats.borrowed_size + stats.pool_size));
  1244. std::this_thread::sleep_for(std::chrono::seconds(10));
  1245. }
  1246. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  1247. if (_run == 1) {
  1248. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1249. exit(6);
  1250. }
  1251. }
  1252. void PostgreSQL::onlineNotification_Redis()
  1253. {
  1254. _connected = 1;
  1255. char buf[11] = {0};
  1256. std::string controllerId = std::string(_myAddress.toString(buf));
  1257. while (_run == 1) {
  1258. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1259. {
  1260. std::lock_guard<std::mutex> l(_lastOnline_l);
  1261. lastOnline.swap(_lastOnline);
  1262. }
  1263. try {
  1264. if (!lastOnline.empty()) {
  1265. if (_rc->clusterMode) {
  1266. auto tx = _cluster->transaction(controllerId, true);
  1267. _doRedisUpdate(tx, controllerId, lastOnline);
  1268. } else {
  1269. auto tx = _redis->transaction(true);
  1270. _doRedisUpdate(tx, controllerId, lastOnline);
  1271. }
  1272. }
  1273. } catch (sw::redis::Error &e) {
  1274. #ifdef ZT_TRACE
  1275. fprintf(stderr, "Error in online notification thread (redis): %s\n", e.what());
  1276. #endif
  1277. }
  1278. std::this_thread::sleep_for(std::chrono::seconds(10));
  1279. }
  1280. }
  1281. void PostgreSQL::_doRedisUpdate(sw::redis::Transaction &tx, std::string &controllerId,
  1282. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > &lastOnline)
  1283. {
  1284. nlohmann::json jtmp1, jtmp2;
  1285. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1286. uint64_t nwid_i = i->first.first;
  1287. uint64_t memberid_i = i->first.second;
  1288. char nwidTmp[64];
  1289. char memTmp[64];
  1290. char ipTmp[64];
  1291. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1292. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", memberid_i);
  1293. if (!get(nwid_i, jtmp1, memberid_i, jtmp2)){
  1294. continue; // skip non existent members/networks
  1295. }
  1296. std::string networkId(nwidTmp);
  1297. std::string memberId(memTmp);
  1298. int64_t ts = i->second.first;
  1299. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1300. std::string timestamp = std::to_string(ts);
  1301. std::unordered_map<std::string, std::string> record = {
  1302. {"id", memberId},
  1303. {"address", ipAddr},
  1304. {"last_updated", std::to_string(ts)}
  1305. };
  1306. tx.zadd("nodes-online:{"+controllerId+"}", memberId, ts)
  1307. .zadd("nodes-online2:{"+controllerId+"}", networkId+"-"+memberId, ts)
  1308. .zadd("network-nodes-online:{"+controllerId+"}:"+networkId, memberId, ts)
  1309. .zadd("active-networks:{"+controllerId+"}", networkId, ts)
  1310. .sadd("network-nodes-all:{"+controllerId+"}:"+networkId, memberId)
  1311. .hmset("member:{"+controllerId+"}:"+networkId+":"+memberId, record.begin(), record.end());
  1312. }
  1313. // expire records from all-nodes and network-nodes member list
  1314. uint64_t expireOld = OSUtils::now() - 300000;
  1315. tx.zremrangebyscore("nodes-online:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1316. tx.zremrangebyscore("nodes-online2:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1317. tx.zremrangebyscore("active-networks:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1318. {
  1319. std::lock_guard<std::mutex> l(_networks_l);
  1320. for (const auto &it : _networks) {
  1321. uint64_t nwid_i = it.first;
  1322. char nwidTmp[64];
  1323. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1324. tx.zremrangebyscore("network-nodes-online:{"+controllerId+"}:"+nwidTmp,
  1325. sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1326. }
  1327. }
  1328. tx.exec();
  1329. }
  1330. #endif //ZT_CONTROLLER_USE_LIBPQ