PostgreSQL.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  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. AuthInfo PostgreSQL::getSSOAuthInfo(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. AuthInfo info;
  308. info.enabled = true;
  309. // fprintf(stderr, "PostgreSQL::updateMemberOnLoad: %s-%s\n", networkId.c_str(), memberId.c_str());
  310. try {
  311. auto c = _pool->borrow();
  312. pqxx::work w(*c->c);
  313. char nonceBytes[16] = {0};
  314. std::string nonce = "";
  315. // check if the member exists first.
  316. pqxx::row count = w.exec_params1("SELECT count(id) FROM ztc_member WHERE id = $1 AND network_id = $2 AND deleted = false", memberId, networkId);
  317. if (count[0].as<int>() == 1) {
  318. // find an unused nonce, if one exists.
  319. pqxx::result r = w.exec_params("SELECT nonce FROM ztc_sso_expiry "
  320. "WHERE network_id = $1 AND member_id = $2 "
  321. "AND authentication_expiry_time IS NULL AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  322. networkId, memberId);
  323. if (r.size() == 1) {
  324. // we have an existing nonce. Use it
  325. nonce = r.at(0)[0].as<std::string>();
  326. Utils::unhex(nonce.c_str(), nonceBytes, sizeof(nonceBytes));
  327. } else if (r.empty()) {
  328. // create a nonce
  329. Utils::getSecureRandom(nonceBytes, 16);
  330. char nonceBuf[64] = {0};
  331. Utils::hex(nonceBytes, sizeof(nonceBytes), nonceBuf);
  332. nonce = std::string(nonceBuf);
  333. pqxx::result ir = w.exec_params0("INSERT INTO ztc_sso_expiry "
  334. "(nonce, nonce_expiration, network_id, member_id) VALUES "
  335. "($1, TO_TIMESTAMP($2::double precision/1000), $3, $4)",
  336. nonce, OSUtils::now() + 300000, networkId, memberId);
  337. w.commit();
  338. } else {
  339. // > 1 ?!? Thats an error!
  340. fprintf(stderr, "> 1 unused nonce!\n");
  341. exit(6);
  342. }
  343. r = w.exec_params("SELECT org.client_id, org.authorization_endpoint, org.sso_impl_version "
  344. "FROM ztc_network AS nw, ztc_org AS org "
  345. "WHERE nw.id = $1 AND nw.sso_enabled = true AND org.owner_id = nw.owner_id", networkId);
  346. std::string client_id = "";
  347. std::string authorization_endpoint = "";
  348. uint64_t sso_version = 0;
  349. if (r.size() == 1) {
  350. client_id = r.at(0)[0].as<std::string>();
  351. authorization_endpoint = r.at(0)[1].as<std::string>();
  352. sso_version = r.at(0)[2].as<uint64_t>();
  353. } else if (r.size() > 1) {
  354. fprintf(stderr, "ERROR: More than one auth endpoint for an organization?!?!? NetworkID: %s\n", networkId.c_str());
  355. } else {
  356. fprintf(stderr, "No client or auth endpoint?!?\n");
  357. }
  358. info.version = sso_version;
  359. // no catch all else because we don't actually care if no records exist here. just continue as normal.
  360. if ((!client_id.empty())&&(!authorization_endpoint.empty())) {
  361. uint8_t state[48];
  362. HMACSHA384(_ssoPsk, nonceBytes, sizeof(nonceBytes), state);
  363. char state_hex[256];
  364. Utils::hex(state, 48, state_hex);
  365. if (info.version == 0) {
  366. char url[2048] = {0};
  367. OSUtils::ztsnprintf(url, sizeof(authenticationURL),
  368. "%s?response_type=id_token&response_mode=form_post&scope=openid+email+profile&redirect_uri=%s&nonce=%s&state=%s&client_id=%s",
  369. authorization_endpoint.c_str(),
  370. redirectURL.c_str(),
  371. nonce.c_str(),
  372. state_hex,
  373. client_id.c_str());
  374. info.authenticationURL = std::string(url);
  375. } else if (info.version == 1) {
  376. info.ssoClientID = client_id;
  377. info.issuerURL = authorization_endpoint;
  378. info.ssoNonce = nonce;
  379. info.ssoState = std::string(state_hex);
  380. info.centralAuthURL = redirectURL;
  381. }
  382. } else {
  383. fprintf(stderr, "client_id: %s\nauthorization_endpoint: %s\n", client_id.c_str(), authorization_endpoint.c_str());
  384. }
  385. }
  386. _pool->unborrow(c);
  387. } catch (std::exception &e) {
  388. fprintf(stderr, "ERROR: Error updating member on load: %s\n", e.what());
  389. }
  390. return info; //std::string(authenticationURL);
  391. }
  392. void PostgreSQL::initializeNetworks()
  393. {
  394. try {
  395. std::string setKey = "networks:{" + _myAddressStr + "}";
  396. fprintf(stderr, "Initializing Networks...\n");
  397. char qbuf[2048] = {0};
  398. sprintf(qbuf, "SELECT n.id, (EXTRACT(EPOCH FROM n.creation_time AT TIME ZONE 'UTC')*1000)::bigint as creation_time, n.capabilities, "
  399. "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, "
  400. "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, "
  401. "(CASE WHEN n.sso_enabled THEN o.authorization_endpoint ELSE NULL END) as authorization_endpoint, d.domain, d.servers, "
  402. "ARRAY(SELECT CONCAT(host(ip_range_start),'|', host(ip_range_end)) FROM ztc_network_assignment_pool WHERE network_id = n.id) AS assignment_pool, "
  403. "ARRAY(SELECT CONCAT(host(address),'/',bits::text,'|',COALESCE(host(via), 'NULL'))FROM ztc_network_route WHERE network_id = n.id) AS routes "
  404. "FROM ztc_network n "
  405. "LEFT OUTER JOIN ztc_org o "
  406. " ON o.owner_id = n.owner_id "
  407. "LEFT OUTER JOIN ztc_network_dns d "
  408. " ON d.network_id = n.id "
  409. "WHERE deleted = false AND controller_id = '%s'", _myAddressStr.c_str());
  410. auto c = _pool->borrow();
  411. auto c2 = _pool->borrow();
  412. pqxx::work w{*c->c};
  413. auto stream = pqxx::stream_from::query(w, qbuf);
  414. std::tuple<
  415. std::string // network ID
  416. , std::optional<int64_t> // creationTime
  417. , std::optional<std::string> // capabilities
  418. , std::optional<bool> // enableBroadcast
  419. , std::optional<uint64_t> // lastModified
  420. , std::optional<int> // mtu
  421. , std::optional<int> // multicastLimit
  422. , std::optional<std::string> // name
  423. , bool // private
  424. , std::optional<int> // remoteTraceLevel
  425. , std::optional<std::string> // remoteTraceTarget
  426. , std::optional<uint64_t> // revision
  427. , std::optional<std::string> // rules
  428. , std::optional<std::string> // tags
  429. , std::optional<std::string> // v4AssignMode
  430. , std::optional<std::string> // v6AssignMode
  431. , std::optional<bool> // ssoEnabled
  432. , std::optional<std::string> // clientId
  433. , std::optional<std::string> // authorizationEndpoint
  434. , std::optional<std::string> // domain
  435. , std::optional<std::string> // servers
  436. , std::string // assignmentPoolString
  437. , std::string // routeString
  438. > row;
  439. uint64_t count = 0;
  440. auto tmp = std::chrono::high_resolution_clock::now();
  441. uint64_t total = 0;
  442. while (stream >> row) {
  443. auto start = std::chrono::high_resolution_clock::now();
  444. json empty;
  445. json config;
  446. initNetwork(config);
  447. std::string nwid = std::get<0>(row);
  448. std::optional<int64_t> creationTime = std::get<1>(row);
  449. std::optional<std::string> capabilities = std::get<2>(row);
  450. std::optional<bool> enableBroadcast = std::get<3>(row);
  451. std::optional<uint64_t> lastModified = std::get<4>(row);
  452. std::optional<int> mtu = std::get<5>(row);
  453. std::optional<int> multicastLimit = std::get<6>(row);
  454. std::optional<std::string> name = std::get<7>(row);
  455. bool isPrivate = std::get<8>(row);
  456. std::optional<int> remoteTraceLevel = std::get<9>(row);
  457. std::optional<std::string> remoteTraceTarget = std::get<10>(row);
  458. std::optional<uint64_t> revision = std::get<11>(row);
  459. std::optional<std::string> rules = std::get<12>(row);
  460. std::optional<std::string> tags = std::get<13>(row);
  461. std::optional<std::string> v4AssignMode = std::get<14>(row);
  462. std::optional<std::string> v6AssignMode = std::get<15>(row);
  463. std::optional<bool> ssoEnabled = std::get<16>(row);
  464. std::optional<std::string> clientId = std::get<17>(row);
  465. std::optional<std::string> authorizationEndpoint = std::get<18>(row);
  466. std::optional<std::string> dnsDomain = std::get<19>(row);
  467. std::optional<std::string> dnsServers = std::get<20>(row);
  468. std::string assignmentPoolString = std::get<21>(row);
  469. std::string routesString = std::get<22>(row);
  470. config["id"] = nwid;
  471. config["nwid"] = nwid;
  472. config["creationTime"] = creationTime.value_or(0);
  473. config["capabilities"] = json::parse(capabilities.value_or("[]"));
  474. config["enableBroadcast"] = enableBroadcast.value_or(false);
  475. config["lastModified"] = lastModified.value_or(0);
  476. config["mtu"] = mtu.value_or(2800);
  477. config["multicastLimit"] = multicastLimit.value_or(64);
  478. config["name"] = name.value_or("");
  479. config["private"] = isPrivate;
  480. config["remoteTraceLevel"] = remoteTraceLevel.value_or(0);
  481. config["remoteTraceTarget"] = remoteTraceTarget.value_or("");
  482. config["revision"] = revision.value_or(0);
  483. config["rules"] = json::parse(rules.value_or("[]"));
  484. config["tags"] = json::parse(tags.value_or("[]"));
  485. config["v4AssignMode"] = json::parse(v4AssignMode.value_or("{}"));
  486. config["v6AssignMode"] = json::parse(v6AssignMode.value_or("{}"));
  487. config["ssoEnabled"] = ssoEnabled.value_or(false);
  488. config["objtype"] = "network";
  489. config["ipAssignmentPools"] = json::array();
  490. config["routes"] = json::array();
  491. config["clientId"] = clientId.value_or("");
  492. config["authorizationEndpoint"] = authorizationEndpoint.value_or("");
  493. if (dnsDomain.has_value()) {
  494. std::string serverList = dnsServers.value();
  495. json obj;
  496. auto servers = json::array();
  497. if (serverList.rfind("{",0) != std::string::npos) {
  498. serverList = serverList.substr(1, serverList.size()-2);
  499. std::stringstream ss(serverList);
  500. while(ss.good()) {
  501. std::string server;
  502. std::getline(ss, server, ',');
  503. servers.push_back(server);
  504. }
  505. }
  506. obj["domain"] = dnsDomain.value();
  507. obj["servers"] = servers;
  508. config["dns"] = obj;
  509. }
  510. config["ipAssignmentPools"] = json::array();
  511. if (assignmentPoolString != "{}") {
  512. std::string tmp = assignmentPoolString.substr(1, assignmentPoolString.size()-2);
  513. std::vector<std::string> assignmentPools = split(tmp, ',');
  514. for (auto it = assignmentPools.begin(); it != assignmentPools.end(); ++it) {
  515. std::vector<std::string> r = split(*it, '|');
  516. json ip;
  517. ip["ipRangeStart"] = r[0];
  518. ip["ipRangeEnd"] = r[1];
  519. config["ipAssignmentPools"].push_back(ip);
  520. }
  521. }
  522. config["routes"] = json::array();
  523. if (routesString != "{}") {
  524. std::string tmp = routesString.substr(1, routesString.size()-2);
  525. std::vector<std::string> routes = split(tmp, ',');
  526. for (auto it = routes.begin(); it != routes.end(); ++it) {
  527. std::vector<std::string> r = split(*it, '|');
  528. json route;
  529. route["target"] = r[0];
  530. route["via"] = ((route["via"] == "NULL")? nullptr : r[1]);
  531. config["routes"].push_back(route);
  532. }
  533. }
  534. _networkChanged(empty, config, false);
  535. auto end = std::chrono::high_resolution_clock::now();
  536. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);;
  537. total += dur.count();
  538. ++count;
  539. if (count > 0 && count % 10000 == 0) {
  540. fprintf(stderr, "Averaging %llu us per network\n", (total/count));
  541. }
  542. }
  543. if (count > 0) {
  544. fprintf(stderr, "Took %llu us per network to load\n", (total/count));
  545. }
  546. stream.complete();
  547. w.commit();
  548. _pool->unborrow(c2);
  549. _pool->unborrow(c);
  550. if (++this->_ready == 2) {
  551. if (_waitNoticePrinted) {
  552. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  553. }
  554. _readyLock.unlock();
  555. }
  556. } catch (sw::redis::Error &e) {
  557. fprintf(stderr, "ERROR: Error initializing networks in Redis: %s\n", e.what());
  558. exit(-1);
  559. } catch (std::exception &e) {
  560. fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
  561. exit(-1);
  562. }
  563. }
  564. void PostgreSQL::initializeMembers()
  565. {
  566. std::string memberId;
  567. std::string networkId;
  568. try {
  569. std::unordered_map<std::string, std::string> networkMembers;
  570. fprintf(stderr, "Initializing Members...\n");
  571. char qbuf[2048];
  572. 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, "
  573. " (EXTRACT(EPOCH FROM m.last_authorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  574. " (EXTRACT(EPOCH FROM m.last_deauthorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  575. " m.remote_trace_level, m.remote_trace_target, m.tags, m.v_major, m.v_minor, m.v_rev, m.v_proto, "
  576. " m.no_auto_assign_ips, m.revision, sso_exempt, "
  577. " (SELECT (EXTRACT(EPOCH FROM e.authentication_expiry_time)*1000)::bigint "
  578. " FROM ztc_sso_expiry e "
  579. " INNER JOIN ztc_network n1 "
  580. " ON n.id = e.network_id "
  581. " 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 "
  582. " ORDER BY e.authentication_expiry_time DESC LIMIT 1) AS authentication_expiry_time, "
  583. " ARRAY(SELECT DISTINCT address FROM ztc_member_ip_assignment WHERE member_id = m.id AND network_id = m.network_id) AS assigned_addresses "
  584. "FROM ztc_member m "
  585. "INNER JOIN ztc_network n "
  586. " ON n.id = m.network_id "
  587. "WHERE n.controller_id = '%s' AND m.deleted = false", _myAddressStr.c_str());
  588. auto c = _pool->borrow();
  589. auto c2 = _pool->borrow();
  590. pqxx::work w{*c->c};
  591. auto stream = pqxx::stream_from::query(w, qbuf);
  592. std::tuple<
  593. std::string // memberId
  594. , std::string // memberId
  595. , std::optional<bool> // activeBridge
  596. , std::optional<bool> // authorized
  597. , std::optional<std::string> // capabilities
  598. , std::optional<uint64_t> // creationTime
  599. , std::optional<std::string> // identity
  600. , std::optional<uint64_t> // lastAuthorizedTime
  601. , std::optional<uint64_t> // lastDeauthorizedTime
  602. , std::optional<int> // remoteTraceLevel
  603. , std::optional<std::string> // remoteTraceTarget
  604. , std::optional<std::string> // tags
  605. , std::optional<int> // vMajor
  606. , std::optional<int> // vMinor
  607. , std::optional<int> // vRev
  608. , std::optional<int> // vProto
  609. , std::optional<bool> // noAutoAssignIps
  610. , std::optional<uint64_t> // revision
  611. , std::optional<bool> // ssoExempt
  612. , std::optional<uint64_t> // authenticationExpiryTime
  613. , std::string // assignedAddresses
  614. > row;
  615. uint64_t count = 0;
  616. auto tmp = std::chrono::high_resolution_clock::now();
  617. uint64_t total = 0;
  618. while (stream >> row) {
  619. auto start = std::chrono::high_resolution_clock::now();
  620. json empty;
  621. json config;
  622. initMember(config);
  623. memberId = std::get<0>(row);
  624. networkId = std::get<1>(row);
  625. std::optional<bool> activeBridge = std::get<2>(row);
  626. std::optional<bool> authorized = std::get<3>(row);
  627. std::optional<std::string> capabilities = std::get<4>(row);
  628. std::optional<uint64_t> creationTime = std::get<5>(row);
  629. std::optional<std::string> identity = std::get<6>(row);
  630. std::optional<uint64_t> lastAuthorizedTime = std::get<7>(row);
  631. std::optional<uint64_t> lastDeauthorizedTime = std::get<8>(row);
  632. std::optional<int> remoteTraceLevel = std::get<9>(row);
  633. std::optional<std::string> remoteTraceTarget = std::get<10>(row);
  634. std::optional<std::string> tags = std::get<11>(row);
  635. std::optional<int> vMajor = std::get<12>(row);
  636. std::optional<int> vMinor = std::get<13>(row);
  637. std::optional<int> vRev = std::get<14>(row);
  638. std::optional<int> vProto = std::get<15>(row);
  639. std::optional<bool> noAutoAssignIps = std::get<16>(row);
  640. std::optional<uint64_t> revision = std::get<17>(row);
  641. std::optional<bool> ssoExempt = std::get<18>(row);
  642. std::optional<uint64_t> authenticationExpiryTime = std::get<19>(row);
  643. std::string assignedAddresses = std::get<20>(row);
  644. config["id"] = memberId;
  645. config["nwid"] = networkId;
  646. config["activeBridge"] = activeBridge.value_or(false);
  647. config["authorized"] = authorized.value_or(false);
  648. config["capabilities"] = json::parse(capabilities.value_or("[]"));
  649. config["creationTime"] = creationTime.value_or(0);
  650. config["identity"] = identity.value_or("");
  651. config["lastAuthorizedTime"] = lastAuthorizedTime.value_or(0);
  652. config["lastDeauthorizedTime"] = lastDeauthorizedTime.value_or(0);
  653. config["remoteTraceLevel"] = remoteTraceLevel.value_or(0);
  654. config["remoteTraceTarget"] = remoteTraceTarget.value_or("");
  655. config["tags"] = json::parse(tags.value_or("[]"));
  656. config["vMajor"] = vMajor.value_or(-1);
  657. config["vMinor"] = vMinor.value_or(-1);
  658. config["vRev"] = vRev.value_or(-1);
  659. config["vProto"] = vProto.value_or(-1);
  660. config["noAutoAssignIps"] = noAutoAssignIps.value_or(false);
  661. config["revision"] = revision.value_or(0);
  662. config["ssoExempt"] = ssoExempt.value_or(false);
  663. config["authenticationExpiryTime"] = authenticationExpiryTime.value_or(0);
  664. config["objtype"] = "member";
  665. config["ipAssignments"] = json::array();
  666. if (assignedAddresses != "{}") {
  667. std::string tmp = assignedAddresses.substr(1, assignedAddresses.size()-2);
  668. std::vector<std::string> addrs = split(tmp, ',');
  669. for (auto it = addrs.begin(); it != addrs.end(); ++it) {
  670. config["ipAssignments"].push_back(*it);
  671. }
  672. }
  673. _memberChanged(empty, config, false);
  674. memberId = "";
  675. networkId = "";
  676. auto end = std::chrono::high_resolution_clock::now();
  677. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);;
  678. total += dur.count();
  679. ++count;
  680. if (count > 0 && count % 10000 == 0) {
  681. fprintf(stderr, "Averaging %llu us per member\n", (total/count));
  682. }
  683. }
  684. if (count > 0) {
  685. fprintf(stderr, "Took %llu us per member to load\n", (total/count));
  686. }
  687. stream.complete();
  688. w.commit();
  689. _pool->unborrow(c2);
  690. _pool->unborrow(c);
  691. if (++this->_ready == 2) {
  692. if (_waitNoticePrinted) {
  693. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  694. }
  695. _readyLock.unlock();
  696. }
  697. } catch (sw::redis::Error &e) {
  698. fprintf(stderr, "ERROR: Error initializing members (redis): %s\n", e.what());
  699. } catch (std::exception &e) {
  700. fprintf(stderr, "ERROR: Error initializing member: %s-%s %s\n", networkId.c_str(), memberId.c_str(), e.what());
  701. exit(-1);
  702. }
  703. }
  704. void PostgreSQL::heartbeat()
  705. {
  706. char publicId[1024];
  707. char hostnameTmp[1024];
  708. _myId.toString(false,publicId);
  709. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  710. hostnameTmp[0] = (char)0;
  711. } else {
  712. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  713. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  714. hostnameTmp[i] = (char)0;
  715. break;
  716. }
  717. }
  718. }
  719. const char *controllerId = _myAddressStr.c_str();
  720. const char *publicIdentity = publicId;
  721. const char *hostname = hostnameTmp;
  722. while (_run == 1) {
  723. // fprintf(stderr, "%s: heartbeat\n", controllerId);
  724. auto c = _pool->borrow();
  725. int64_t ts = OSUtils::now();
  726. if(c->c) {
  727. pqxx::work w{*c->c};
  728. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  729. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  730. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  731. std::string build = std::to_string(ZEROTIER_ONE_VERSION_BUILD);
  732. std::string now = std::to_string(ts);
  733. std::string host_port = std::to_string(_listenPort);
  734. std::string use_redis = (_rc != NULL) ? "true" : "false";
  735. try {
  736. 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) "
  737. "VALUES ("+w.quote(controllerId)+", "+w.quote(hostname)+", TO_TIMESTAMP("+now+"::double precision/1000), "+
  738. w.quote(publicIdentity)+", "+major+", "+minor+", "+rev+", "+build+", "+host_port+", "+use_redis+") "
  739. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  740. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  741. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev, host_port = EXCLUDED.host_port, "
  742. "use_redis = EXCLUDED.use_redis");
  743. } catch (std::exception &e) {
  744. fprintf(stderr, "Heartbeat update failed: %s\n", e.what());
  745. w.abort();
  746. _pool->unborrow(c);
  747. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  748. continue;
  749. }
  750. w.commit();
  751. }
  752. _pool->unborrow(c);
  753. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  754. }
  755. fprintf(stderr, "Exited heartbeat thread\n");
  756. }
  757. void PostgreSQL::membersDbWatcher()
  758. {
  759. if (_rc) {
  760. _membersWatcher_Redis();
  761. } else {
  762. _membersWatcher_Postgres();
  763. }
  764. if (_run == 1) {
  765. fprintf(stderr, "ERROR: %s membersDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  766. exit(9);
  767. }
  768. fprintf(stderr, "Exited membersDbWatcher\n");
  769. }
  770. void PostgreSQL::_membersWatcher_Postgres() {
  771. auto c = _pool->borrow();
  772. std::string stream = "member_" + _myAddressStr;
  773. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  774. MemberNotificationReceiver m(this, *c->c, stream);
  775. while(_run == 1) {
  776. c->c->await_notification(5, 0);
  777. }
  778. _pool->unborrow(c);
  779. }
  780. void PostgreSQL::_membersWatcher_Redis() {
  781. char buf[11] = {0};
  782. std::string key = "member-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  783. fprintf(stderr, "Listening to member stream: %s\n", key.c_str());
  784. while (_run == 1) {
  785. try {
  786. json tmp;
  787. std::unordered_map<std::string, ItemStream> result;
  788. if (_rc->clusterMode) {
  789. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  790. } else {
  791. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  792. }
  793. if (!result.empty()) {
  794. for (auto element : result) {
  795. #ifdef ZT_TRACE
  796. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  797. #endif
  798. for (auto rec : element.second) {
  799. std::string id = rec.first;
  800. auto attrs = rec.second;
  801. #ifdef ZT_TRACE
  802. fprintf(stdout, "Record ID: %s\n", id.c_str());
  803. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  804. #endif
  805. for (auto a : attrs) {
  806. #ifdef ZT_TRACE
  807. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  808. #endif
  809. try {
  810. tmp = json::parse(a.second);
  811. json &ov = tmp["old_val"];
  812. json &nv = tmp["new_val"];
  813. json oldConfig, newConfig;
  814. if (ov.is_object()) oldConfig = ov;
  815. if (nv.is_object()) newConfig = nv;
  816. if (oldConfig.is_object()||newConfig.is_object()) {
  817. _memberChanged(oldConfig,newConfig,(this->_ready >= 2));
  818. }
  819. } catch (...) {
  820. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  821. }
  822. }
  823. if (_rc->clusterMode) {
  824. _cluster->xdel(key, id);
  825. } else {
  826. _redis->xdel(key, id);
  827. }
  828. }
  829. }
  830. }
  831. } catch (sw::redis::Error &e) {
  832. fprintf(stderr, "Error in Redis members watcher: %s\n", e.what());
  833. }
  834. }
  835. fprintf(stderr, "membersWatcher ended\n");
  836. }
  837. void PostgreSQL::networksDbWatcher()
  838. {
  839. if (_rc) {
  840. _networksWatcher_Redis();
  841. } else {
  842. _networksWatcher_Postgres();
  843. }
  844. if (_run == 1) {
  845. fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  846. exit(8);
  847. }
  848. fprintf(stderr, "Exited networksDbWatcher\n");
  849. }
  850. void PostgreSQL::_networksWatcher_Postgres() {
  851. std::string stream = "network_" + _myAddressStr;
  852. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  853. auto c = _pool->borrow();
  854. NetworkNotificationReceiver n(this, *c->c, stream);
  855. while(_run == 1) {
  856. c->c->await_notification(5,0);
  857. }
  858. }
  859. void PostgreSQL::_networksWatcher_Redis() {
  860. char buf[11] = {0};
  861. std::string key = "network-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  862. while (_run == 1) {
  863. try {
  864. json tmp;
  865. std::unordered_map<std::string, ItemStream> result;
  866. if (_rc->clusterMode) {
  867. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  868. } else {
  869. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  870. }
  871. if (!result.empty()) {
  872. for (auto element : result) {
  873. #ifdef ZT_TRACE
  874. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  875. #endif
  876. for (auto rec : element.second) {
  877. std::string id = rec.first;
  878. auto attrs = rec.second;
  879. #ifdef ZT_TRACE
  880. fprintf(stdout, "Record ID: %s\n", id.c_str());
  881. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  882. #endif
  883. for (auto a : attrs) {
  884. #ifdef ZT_TRACE
  885. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  886. #endif
  887. try {
  888. tmp = json::parse(a.second);
  889. json &ov = tmp["old_val"];
  890. json &nv = tmp["new_val"];
  891. json oldConfig, newConfig;
  892. if (ov.is_object()) oldConfig = ov;
  893. if (nv.is_object()) newConfig = nv;
  894. if (oldConfig.is_object()||newConfig.is_object()) {
  895. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  896. }
  897. } catch (...) {
  898. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  899. }
  900. }
  901. if (_rc->clusterMode) {
  902. _cluster->xdel(key, id);
  903. } else {
  904. _redis->xdel(key, id);
  905. }
  906. }
  907. }
  908. }
  909. } catch (sw::redis::Error &e) {
  910. fprintf(stderr, "Error in Redis networks watcher: %s\n", e.what());
  911. }
  912. }
  913. fprintf(stderr, "networksWatcher ended\n");
  914. }
  915. void PostgreSQL::commitThread()
  916. {
  917. fprintf(stderr, "%s: commitThread start\n", _myAddressStr.c_str());
  918. std::pair<nlohmann::json,bool> qitem;
  919. while(_commitQueue.get(qitem)&(_run == 1)) {
  920. //fprintf(stderr, "commitThread tick\n");
  921. if (!qitem.first.is_object()) {
  922. fprintf(stderr, "not an object\n");
  923. continue;
  924. }
  925. std::shared_ptr<PostgresConnection> c;
  926. try {
  927. c = _pool->borrow();
  928. } catch (std::exception &e) {
  929. fprintf(stderr, "ERROR: %s\n", e.what());
  930. continue;
  931. }
  932. if (!c) {
  933. fprintf(stderr, "Error getting database connection\n");
  934. continue;
  935. }
  936. try {
  937. nlohmann::json &config = (qitem.first);
  938. const std::string objtype = config["objtype"];
  939. if (objtype == "member") {
  940. // fprintf(stderr, "%s: commitThread: member\n", _myAddressStr.c_str());
  941. std::string memberId;
  942. std::string networkId;
  943. try {
  944. pqxx::work w(*c->c);
  945. memberId = config["id"];
  946. networkId = config["nwid"];
  947. std::string target = "NULL";
  948. if (!config["remoteTraceTarget"].is_null()) {
  949. target = config["remoteTraceTarget"];
  950. }
  951. pqxx::row nwrow = w.exec_params1("SELECT COUNT(id) FROM ztc_network WHERE id = $1", networkId);
  952. int nwcount = nwrow[0].as<int>();
  953. if (nwcount != 1) {
  954. fprintf(stderr, "network %s does not exist. skipping member upsert\n", networkId.c_str());
  955. w.abort();
  956. _pool->unborrow(c);
  957. continue;
  958. }
  959. pqxx::result res = w.exec_params0(
  960. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  961. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  962. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  963. "VALUES ($1, $2, $3, $4, $5, $6, "
  964. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  965. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  966. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  967. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  968. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  969. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  970. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  971. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  972. memberId,
  973. networkId,
  974. (bool)config["activeBridge"],
  975. (bool)config["authorized"],
  976. OSUtils::jsonDump(config["capabilities"], -1),
  977. OSUtils::jsonString(config["identity"], ""),
  978. (uint64_t)config["lastAuthorizedTime"],
  979. (uint64_t)config["lastDeauthorizedTime"],
  980. (bool)config["noAutoAssignIps"],
  981. (int)config["remoteTraceLevel"],
  982. target,
  983. (uint64_t)config["revision"],
  984. OSUtils::jsonDump(config["tags"], -1),
  985. (int)config["vMajor"],
  986. (int)config["vMinor"],
  987. (int)config["vRev"],
  988. (int)config["vProto"]);
  989. res = w.exec_params0("DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  990. memberId, networkId);
  991. std::vector<std::string> assignments;
  992. bool ipAssignError = false;
  993. for (auto i = config["ipAssignments"].begin(); i != config["ipAssignments"].end(); ++i) {
  994. std::string addr = *i;
  995. if (std::find(assignments.begin(), assignments.end(), addr) != assignments.end()) {
  996. continue;
  997. }
  998. res = w.exec_params0(
  999. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3) ON CONFLICT (network_id, member_id, address) DO NOTHING",
  1000. memberId, networkId, addr);
  1001. assignments.push_back(addr);
  1002. }
  1003. if (ipAssignError) {
  1004. fprintf(stderr, "%s: ipAssignError\n", _myAddressStr.c_str());
  1005. w.abort();
  1006. _pool->unborrow(c);
  1007. c.reset();
  1008. continue;
  1009. }
  1010. w.commit();
  1011. const uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  1012. const uint64_t memberidInt = OSUtils::jsonIntHex(config["id"], 0ULL);
  1013. if (nwidInt && memberidInt) {
  1014. nlohmann::json nwOrig;
  1015. nlohmann::json memOrig;
  1016. nlohmann::json memNew(config);
  1017. get(nwidInt, nwOrig, memberidInt, memOrig);
  1018. _memberChanged(memOrig, memNew, qitem.second);
  1019. } else {
  1020. 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);
  1021. }
  1022. } catch (std::exception &e) {
  1023. fprintf(stderr, "%s ERROR: Error updating member %s-%s: %s\n", _myAddressStr.c_str(), networkId.c_str(), memberId.c_str(), e.what());
  1024. }
  1025. } else if (objtype == "network") {
  1026. try {
  1027. // fprintf(stderr, "%s: commitThread: network\n", _myAddressStr.c_str());
  1028. pqxx::work w(*c->c);
  1029. std::string id = config["id"];
  1030. std::string remoteTraceTarget = "";
  1031. if(!config["remoteTraceTarget"].is_null()) {
  1032. remoteTraceTarget = config["remoteTraceTarget"];
  1033. }
  1034. std::string rulesSource = "";
  1035. if (config["rulesSource"].is_string()) {
  1036. rulesSource = config["rulesSource"];
  1037. }
  1038. // This ugly query exists because when we want to mirror networks to/from
  1039. // another data store (e.g. FileDB or LFDB) it is possible to get a network
  1040. // that doesn't exist in Central's database. This does an upsert and sets
  1041. // the owner_id to the "first" global admin in the user DB if the record
  1042. // did not previously exist. If the record already exists owner_id is left
  1043. // unchanged, so owner_id should be left out of the update clause.
  1044. pqxx::result res = w.exec_params0(
  1045. "INSERT INTO ztc_network (id, creation_time, owner_id, controller_id, capabilities, enable_broadcast, "
  1046. "last_modified, mtu, multicast_limit, name, private, "
  1047. "remote_trace_level, remote_trace_target, rules, rules_source, "
  1048. "tags, v4_assign_mode, v6_assign_mode, sso_enabled) VALUES ("
  1049. "$1, TO_TIMESTAMP($5::double precision/1000), "
  1050. "(SELECT user_id AS owner_id FROM ztc_global_permissions WHERE authorize = true AND del = true AND modify = true AND read = true LIMIT 1),"
  1051. "$2, $3, $4, TO_TIMESTAMP($5::double precision/1000), "
  1052. "$6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, 17) "
  1053. "ON CONFLICT (id) DO UPDATE set controller_id = EXCLUDED.controller_id, "
  1054. "capabilities = EXCLUDED.capabilities, enable_broadcast = EXCLUDED.enable_broadcast, "
  1055. "last_modified = EXCLUDED.last_modified, mtu = EXCLUDED.mtu, "
  1056. "multicast_limit = EXCLUDED.multicast_limit, name = EXCLUDED.name, "
  1057. "private = EXCLUDED.private, remote_trace_level = EXCLUDED.remote_trace_level, "
  1058. "remote_trace_target = EXCLUDED.remote_trace_target, rules = EXCLUDED.rules, "
  1059. "rules_source = EXCLUDED.rules_source, tags = EXCLUDED.tags, "
  1060. "v4_assign_mode = EXCLUDED.v4_assign_mode, v6_assign_mode = EXCLUDED.v6_assign_mode, "
  1061. "sso_enabled = EXCLUDED.sso_enabled",
  1062. id,
  1063. _myAddressStr,
  1064. OSUtils::jsonDump(config["capabilitles"], -1),
  1065. (bool)config["enableBroadcast"],
  1066. OSUtils::now(),
  1067. (int)config["mtu"],
  1068. (int)config["multicastLimit"],
  1069. OSUtils::jsonString(config["name"],""),
  1070. (bool)config["private"],
  1071. (int)config["remoteTraceLevel"],
  1072. remoteTraceTarget,
  1073. OSUtils::jsonDump(config["rules"], -1),
  1074. rulesSource,
  1075. OSUtils::jsonDump(config["tags"], -1),
  1076. OSUtils::jsonDump(config["v4AssignMode"],-1),
  1077. OSUtils::jsonDump(config["v6AssignMode"], -1),
  1078. OSUtils::jsonBool(config["ssoEnabled"], false));
  1079. res = w.exec_params0("DELETE FROM ztc_network_assignment_pool WHERE network_id = $1", 0);
  1080. auto pool = config["ipAssignmentPools"];
  1081. bool err = false;
  1082. for (auto i = pool.begin(); i != pool.end(); ++i) {
  1083. std::string start = (*i)["ipRangeStart"];
  1084. std::string end = (*i)["ipRangeEnd"];
  1085. res = w.exec_params0(
  1086. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  1087. "VALUES ($1, $2, $3)", id, start, end);
  1088. }
  1089. res = w.exec_params0("DELETE FROM ztc_network_route WHERE network_id = $1", id);
  1090. auto routes = config["routes"];
  1091. err = false;
  1092. for (auto i = routes.begin(); i != routes.end(); ++i) {
  1093. std::string t = (*i)["target"];
  1094. std::vector<std::string> target;
  1095. std::istringstream f(t);
  1096. std::string s;
  1097. while(std::getline(f, s, '/')) {
  1098. target.push_back(s);
  1099. }
  1100. if (target.empty() || target.size() != 2) {
  1101. continue;
  1102. }
  1103. std::string targetAddr = target[0];
  1104. std::string targetBits = target[1];
  1105. std::string via = "NULL";
  1106. if (!(*i)["via"].is_null()) {
  1107. via = (*i)["via"];
  1108. }
  1109. res = w.exec_params0("INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  1110. id, targetAddr, targetBits, (via == "NULL" ? NULL : via.c_str()));
  1111. }
  1112. if (err) {
  1113. fprintf(stderr, "%s: route add error\n", _myAddressStr.c_str());
  1114. w.abort();
  1115. _pool->unborrow(c);
  1116. continue;
  1117. }
  1118. auto dns = config["dns"];
  1119. std::string domain = dns["domain"];
  1120. std::stringstream servers;
  1121. servers << "{";
  1122. for (auto j = dns["servers"].begin(); j < dns["servers"].end(); ++j) {
  1123. servers << *j;
  1124. if ( (j+1) != dns["servers"].end()) {
  1125. servers << ",";
  1126. }
  1127. }
  1128. servers << "}";
  1129. std::string s = servers.str();
  1130. 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",
  1131. id, domain, s);
  1132. w.commit();
  1133. const uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  1134. if (nwidInt) {
  1135. nlohmann::json nwOrig;
  1136. nlohmann::json nwNew(config);
  1137. get(nwidInt, nwOrig);
  1138. _networkChanged(nwOrig, nwNew, qitem.second);
  1139. } else {
  1140. fprintf(stderr, "%s: Can't notify network changed: %llu\n", _myAddressStr.c_str(), (unsigned long long)nwidInt);
  1141. }
  1142. } catch (std::exception &e) {
  1143. fprintf(stderr, "%s ERROR: Error updating network: %s\n", _myAddressStr.c_str(), e.what());
  1144. }
  1145. } else if (objtype == "_delete_network") {
  1146. // fprintf(stderr, "%s: commitThread: delete network\n", _myAddressStr.c_str());
  1147. try {
  1148. pqxx::work w(*c->c);
  1149. std::string networkId = config["nwid"];
  1150. pqxx::result res = w.exec_params0("UPDATE ztc_network SET deleted = true WHERE id = $1",
  1151. networkId);
  1152. w.commit();
  1153. } catch (std::exception &e) {
  1154. fprintf(stderr, "%s ERROR: Error deleting network: %s\n", _myAddressStr.c_str(), e.what());
  1155. }
  1156. } else if (objtype == "_delete_member") {
  1157. // fprintf(stderr, "%s commitThread: delete member\n", _myAddressStr.c_str());
  1158. try {
  1159. pqxx::work w(*c->c);
  1160. std::string memberId = config["id"];
  1161. std::string networkId = config["nwid"];
  1162. pqxx::result res = w.exec_params0(
  1163. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  1164. memberId, networkId);
  1165. w.commit();
  1166. } catch (std::exception &e) {
  1167. fprintf(stderr, "%s ERROR: Error deleting member: %s\n", _myAddressStr.c_str(), e.what());
  1168. }
  1169. } else {
  1170. fprintf(stderr, "%s ERROR: unknown objtype\n", _myAddressStr.c_str());
  1171. }
  1172. } catch (std::exception &e) {
  1173. fprintf(stderr, "%s ERROR: Error getting objtype: %s\n", _myAddressStr.c_str(), e.what());
  1174. }
  1175. _pool->unborrow(c);
  1176. c.reset();
  1177. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1178. }
  1179. fprintf(stderr, "%s commitThread finished\n", _myAddressStr.c_str());
  1180. }
  1181. void PostgreSQL::onlineNotificationThread()
  1182. {
  1183. waitForReady();
  1184. onlineNotification_Postgres();
  1185. }
  1186. void PostgreSQL::onlineNotification_Postgres()
  1187. {
  1188. _connected = 1;
  1189. nlohmann::json jtmp1, jtmp2;
  1190. while (_run == 1) {
  1191. auto c = _pool->borrow();
  1192. auto c2 = _pool->borrow();
  1193. try {
  1194. fprintf(stderr, "%s onlineNotification_Postgres\n", _myAddressStr.c_str());
  1195. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1196. {
  1197. std::lock_guard<std::mutex> l(_lastOnline_l);
  1198. lastOnline.swap(_lastOnline);
  1199. }
  1200. pqxx::work w(*c->c);
  1201. pqxx::work w2(*c2->c);
  1202. fprintf(stderr, "online notification tick\n");
  1203. bool firstRun = true;
  1204. bool memberAdded = false;
  1205. int updateCount = 0;
  1206. pqxx::pipeline pipe(w);
  1207. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1208. updateCount += 1;
  1209. uint64_t nwid_i = i->first.first;
  1210. char nwidTmp[64];
  1211. char memTmp[64];
  1212. char ipTmp[64];
  1213. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1214. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  1215. if(!get(nwid_i, jtmp1, i->first.second, jtmp2)) {
  1216. continue; // skip non existent networks/members
  1217. }
  1218. std::string networkId(nwidTmp);
  1219. std::string memberId(memTmp);
  1220. try {
  1221. pqxx::row r = w2.exec_params1("SELECT id, network_id FROM ztc_member WHERE network_id = $1 AND id = $2",
  1222. networkId, memberId);
  1223. } catch (pqxx::unexpected_rows &e) {
  1224. continue;
  1225. }
  1226. int64_t ts = i->second.first;
  1227. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1228. std::string timestamp = std::to_string(ts);
  1229. std::stringstream memberUpdate;
  1230. memberUpdate << "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES "
  1231. << "('" << networkId << "', '" << memberId << "', ";
  1232. if (ipAddr.empty()) {
  1233. memberUpdate << "NULL, ";
  1234. } else {
  1235. memberUpdate << "'" << ipAddr << "', ";
  1236. }
  1237. memberUpdate << "TO_TIMESTAMP(" << timestamp << "::double precision/1000)) "
  1238. << " ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated";
  1239. pipe.insert(memberUpdate.str());
  1240. }
  1241. while(!pipe.empty()) {
  1242. pipe.retrieve();
  1243. }
  1244. pipe.complete();
  1245. w.commit();
  1246. fprintf(stderr, "%s: Updated online status of %d members\n", _myAddressStr.c_str(), updateCount);
  1247. } catch (std::exception &e) {
  1248. fprintf(stderr, "%s: error in onlinenotification thread: %s\n", _myAddressStr.c_str(), e.what());
  1249. }
  1250. _pool->unborrow(c2);
  1251. _pool->unborrow(c);
  1252. ConnectionPoolStats stats = _pool->get_stats();
  1253. fprintf(stderr, "%s pool stats: in use size: %llu, available size: %llu, total: %llu\n",
  1254. _myAddressStr.c_str(), stats.borrowed_size, stats.pool_size, (stats.borrowed_size + stats.pool_size));
  1255. std::this_thread::sleep_for(std::chrono::seconds(10));
  1256. }
  1257. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  1258. if (_run == 1) {
  1259. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1260. exit(6);
  1261. }
  1262. }
  1263. void PostgreSQL::onlineNotification_Redis()
  1264. {
  1265. _connected = 1;
  1266. char buf[11] = {0};
  1267. std::string controllerId = std::string(_myAddress.toString(buf));
  1268. while (_run == 1) {
  1269. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1270. {
  1271. std::lock_guard<std::mutex> l(_lastOnline_l);
  1272. lastOnline.swap(_lastOnline);
  1273. }
  1274. try {
  1275. if (!lastOnline.empty()) {
  1276. if (_rc->clusterMode) {
  1277. auto tx = _cluster->transaction(controllerId, true);
  1278. _doRedisUpdate(tx, controllerId, lastOnline);
  1279. } else {
  1280. auto tx = _redis->transaction(true);
  1281. _doRedisUpdate(tx, controllerId, lastOnline);
  1282. }
  1283. }
  1284. } catch (sw::redis::Error &e) {
  1285. #ifdef ZT_TRACE
  1286. fprintf(stderr, "Error in online notification thread (redis): %s\n", e.what());
  1287. #endif
  1288. }
  1289. std::this_thread::sleep_for(std::chrono::seconds(10));
  1290. }
  1291. }
  1292. void PostgreSQL::_doRedisUpdate(sw::redis::Transaction &tx, std::string &controllerId,
  1293. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > &lastOnline)
  1294. {
  1295. nlohmann::json jtmp1, jtmp2;
  1296. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1297. uint64_t nwid_i = i->first.first;
  1298. uint64_t memberid_i = i->first.second;
  1299. char nwidTmp[64];
  1300. char memTmp[64];
  1301. char ipTmp[64];
  1302. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1303. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", memberid_i);
  1304. if (!get(nwid_i, jtmp1, memberid_i, jtmp2)){
  1305. continue; // skip non existent members/networks
  1306. }
  1307. std::string networkId(nwidTmp);
  1308. std::string memberId(memTmp);
  1309. int64_t ts = i->second.first;
  1310. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1311. std::string timestamp = std::to_string(ts);
  1312. std::unordered_map<std::string, std::string> record = {
  1313. {"id", memberId},
  1314. {"address", ipAddr},
  1315. {"last_updated", std::to_string(ts)}
  1316. };
  1317. tx.zadd("nodes-online:{"+controllerId+"}", memberId, ts)
  1318. .zadd("nodes-online2:{"+controllerId+"}", networkId+"-"+memberId, ts)
  1319. .zadd("network-nodes-online:{"+controllerId+"}:"+networkId, memberId, ts)
  1320. .zadd("active-networks:{"+controllerId+"}", networkId, ts)
  1321. .sadd("network-nodes-all:{"+controllerId+"}:"+networkId, memberId)
  1322. .hmset("member:{"+controllerId+"}:"+networkId+":"+memberId, record.begin(), record.end());
  1323. }
  1324. // expire records from all-nodes and network-nodes member list
  1325. uint64_t expireOld = OSUtils::now() - 300000;
  1326. tx.zremrangebyscore("nodes-online:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1327. tx.zremrangebyscore("nodes-online2:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1328. tx.zremrangebyscore("active-networks:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1329. {
  1330. std::lock_guard<std::mutex> l(_networks_l);
  1331. for (const auto &it : _networks) {
  1332. uint64_t nwid_i = it.first;
  1333. char nwidTmp[64];
  1334. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1335. tx.zremrangebyscore("network-nodes-online:{"+controllerId+"}:"+nwidTmp,
  1336. sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1337. }
  1338. }
  1339. tx.exec();
  1340. }
  1341. #endif //ZT_CONTROLLER_USE_LIBPQ