PostgreSQL.cpp 52 KB

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