2
0

PostgreSQL.cpp 52 KB

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