PostgreSQL.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058
  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: 2026-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 "../version.h"
  18. #include "EmbeddedNetworkController.hpp"
  19. #include "Redis.hpp"
  20. #include <chrono>
  21. #include <climits>
  22. #include <iomanip>
  23. #include <libpq-fe.h>
  24. #include <smeeclient.h>
  25. #include <sstream>
  26. // #define REDIS_TRACE 1
  27. using json = nlohmann::json;
  28. namespace {
  29. static const int DB_MINIMUM_VERSION = 38;
  30. static const char* _timestr()
  31. {
  32. time_t t = time(0);
  33. char* ts = ctime(&t);
  34. char* p = ts;
  35. if (! p)
  36. return "";
  37. while (*p) {
  38. if (*p == '\n') {
  39. *p = (char)0;
  40. break;
  41. }
  42. ++p;
  43. }
  44. return ts;
  45. }
  46. /*
  47. std::string join(const std::vector<std::string> &elements, const char * const separator)
  48. {
  49. switch(elements.size()) {
  50. case 0:
  51. return "";
  52. case 1:
  53. return elements[0];
  54. default:
  55. std::ostringstream os;
  56. std::copy(elements.begin(), elements.end()-1, std::ostream_iterator<std::string>(os, separator));
  57. os << *elements.rbegin();
  58. return os.str();
  59. }
  60. }
  61. */
  62. std::vector<std::string> split(std::string str, char delim)
  63. {
  64. std::istringstream iss(str);
  65. std::vector<std::string> tokens;
  66. std::string item;
  67. while (std::getline(iss, item, delim)) {
  68. tokens.push_back(item);
  69. }
  70. return tokens;
  71. }
  72. std::string url_encode(const std::string& value)
  73. {
  74. std::ostringstream escaped;
  75. escaped.fill('0');
  76. escaped << std::hex;
  77. for (std::string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
  78. std::string::value_type c = (*i);
  79. // Keep alphanumeric and other accepted characters intact
  80. if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
  81. escaped << c;
  82. continue;
  83. }
  84. // Any other characters are percent-encoded
  85. escaped << std::uppercase;
  86. escaped << '%' << std::setw(2) << int((unsigned char)c);
  87. escaped << std::nouppercase;
  88. }
  89. return escaped.str();
  90. }
  91. } // anonymous namespace
  92. using namespace ZeroTier;
  93. MemberNotificationReceiver::MemberNotificationReceiver(PostgreSQL* p, pqxx::connection& c, const std::string& channel) : pqxx::notification_receiver(c, channel), _psql(p)
  94. {
  95. fprintf(stderr, "initialize MemberNotificationReceiver\n");
  96. }
  97. void MemberNotificationReceiver::operator()(const std::string& payload, int packend_pid)
  98. {
  99. fprintf(stderr, "Member Notification received: %s\n", payload.c_str());
  100. Metrics::pgsql_mem_notification++;
  101. json tmp(json::parse(payload));
  102. json& ov = tmp["old_val"];
  103. json& nv = tmp["new_val"];
  104. json oldConfig, newConfig;
  105. if (ov.is_object())
  106. oldConfig = ov;
  107. if (nv.is_object())
  108. newConfig = nv;
  109. if (oldConfig.is_object() || newConfig.is_object()) {
  110. _psql->_memberChanged(oldConfig, newConfig, (_psql->_ready >= 2));
  111. fprintf(stderr, "payload sent\n");
  112. }
  113. }
  114. NetworkNotificationReceiver::NetworkNotificationReceiver(PostgreSQL* p, pqxx::connection& c, const std::string& channel) : pqxx::notification_receiver(c, channel), _psql(p)
  115. {
  116. fprintf(stderr, "initialize NetworkNotificationReceiver\n");
  117. }
  118. void NetworkNotificationReceiver::operator()(const std::string& payload, int packend_pid)
  119. {
  120. fprintf(stderr, "Network Notification received: %s\n", payload.c_str());
  121. Metrics::pgsql_net_notification++;
  122. json tmp(json::parse(payload));
  123. json& ov = tmp["old_val"];
  124. json& nv = tmp["new_val"];
  125. json oldConfig, newConfig;
  126. if (ov.is_object())
  127. oldConfig = ov;
  128. if (nv.is_object())
  129. newConfig = nv;
  130. if (oldConfig.is_object() || newConfig.is_object()) {
  131. _psql->_networkChanged(oldConfig, newConfig, (_psql->_ready >= 2));
  132. fprintf(stderr, "payload sent\n");
  133. }
  134. }
  135. using Attrs = std::vector<std::pair<std::string, std::string> >;
  136. using Item = std::pair<std::string, Attrs>;
  137. using ItemStream = std::vector<Item>;
  138. PostgreSQL::PostgreSQL(const Identity& myId, const char* path, int listenPort, RedisConfig* rc)
  139. : DB()
  140. , _pool()
  141. , _myId(myId)
  142. , _myAddress(myId.address())
  143. , _ready(0)
  144. , _connected(1)
  145. , _run(1)
  146. , _waitNoticePrinted(false)
  147. , _listenPort(listenPort)
  148. , _rc(rc)
  149. , _redis(NULL)
  150. , _cluster(NULL)
  151. , _redisMemberStatus(false)
  152. , _smee(NULL)
  153. {
  154. char myAddress[64];
  155. _myAddressStr = myId.address().toString(myAddress);
  156. _connString = std::string(path);
  157. auto f = std::make_shared<PostgresConnFactory>(_connString);
  158. _pool = std::make_shared<ConnectionPool<PostgresConnection> >(15, 5, std::static_pointer_cast<ConnectionFactory>(f));
  159. memset(_ssoPsk, 0, sizeof(_ssoPsk));
  160. char* const ssoPskHex = getenv("ZT_SSO_PSK");
  161. #ifdef ZT_TRACE
  162. fprintf(stderr, "ZT_SSO_PSK: %s\n", ssoPskHex);
  163. #endif
  164. if (ssoPskHex) {
  165. // SECURITY: note that ssoPskHex will always be null-terminated if libc actually
  166. // returns something non-NULL. If the hex encodes something shorter than 48 bytes,
  167. // it will be padded at the end with zeroes. If longer, it'll be truncated.
  168. Utils::unhex(ssoPskHex, _ssoPsk, sizeof(_ssoPsk));
  169. }
  170. const char* redisMemberStatus = getenv("ZT_REDIS_MEMBER_STATUS");
  171. if (redisMemberStatus && (strcmp(redisMemberStatus, "true") == 0)) {
  172. _redisMemberStatus = true;
  173. fprintf(stderr, "Using redis for member status\n");
  174. }
  175. auto c = _pool->borrow();
  176. pqxx::work txn { *c->c };
  177. pqxx::row r { txn.exec1("SELECT version FROM ztc_database") };
  178. int dbVersion = r[0].as<int>();
  179. txn.commit();
  180. if (dbVersion < DB_MINIMUM_VERSION) {
  181. 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);
  182. exit(1);
  183. }
  184. _pool->unborrow(c);
  185. if (_rc != NULL) {
  186. sw::redis::ConnectionOptions opts;
  187. sw::redis::ConnectionPoolOptions poolOpts;
  188. opts.host = _rc->hostname;
  189. opts.port = _rc->port;
  190. opts.password = _rc->password;
  191. opts.db = 0;
  192. opts.keep_alive = true;
  193. opts.connect_timeout = std::chrono::seconds(3);
  194. poolOpts.size = 25;
  195. poolOpts.wait_timeout = std::chrono::seconds(5);
  196. poolOpts.connection_lifetime = std::chrono::minutes(3);
  197. poolOpts.connection_idle_time = std::chrono::minutes(1);
  198. if (_rc->clusterMode) {
  199. fprintf(stderr, "Using Redis in Cluster Mode\n");
  200. _cluster = std::make_shared<sw::redis::RedisCluster>(opts, poolOpts);
  201. }
  202. else {
  203. fprintf(stderr, "Using Redis in Standalone Mode\n");
  204. _redis = std::make_shared<sw::redis::Redis>(opts, poolOpts);
  205. }
  206. }
  207. _readyLock.lock();
  208. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S, ::_timestr(), (unsigned long long)_myAddress.toInt());
  209. _waitNoticePrinted = true;
  210. initializeNetworks();
  211. initializeMembers();
  212. _heartbeatThread = std::thread(&PostgreSQL::heartbeat, this);
  213. _membersDbWatcher = std::thread(&PostgreSQL::membersDbWatcher, this);
  214. _networksDbWatcher = std::thread(&PostgreSQL::networksDbWatcher, this);
  215. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  216. _commitThread[i] = std::thread(&PostgreSQL::commitThread, this);
  217. }
  218. _onlineNotificationThread = std::thread(&PostgreSQL::onlineNotificationThread, this);
  219. configureSmee();
  220. }
  221. PostgreSQL::~PostgreSQL()
  222. {
  223. if (_smee != NULL) {
  224. smeeclient::smee_client_delete(_smee);
  225. _smee = NULL;
  226. }
  227. _run = 0;
  228. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  229. _heartbeatThread.join();
  230. _membersDbWatcher.join();
  231. _networksDbWatcher.join();
  232. _commitQueue.stop();
  233. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  234. _commitThread[i].join();
  235. }
  236. _onlineNotificationThread.join();
  237. }
  238. void PostgreSQL::configureSmee()
  239. {
  240. const char* TEMPORAL_SCHEME = "ZT_TEMPORAL_SCHEME";
  241. const char* TEMPORAL_HOST = "ZT_TEMPORAL_HOST";
  242. const char* TEMPORAL_PORT = "ZT_TEMPORAL_PORT";
  243. const char* TEMPORAL_NAMESPACE = "ZT_TEMPORAL_NAMESPACE";
  244. const char* SMEE_TASK_QUEUE = "ZT_SMEE_TASK_QUEUE";
  245. const char* scheme = getenv(TEMPORAL_SCHEME);
  246. if (scheme == NULL) {
  247. scheme = "http";
  248. }
  249. const char* host = getenv(TEMPORAL_HOST);
  250. const char* port = getenv(TEMPORAL_PORT);
  251. const char* ns = getenv(TEMPORAL_NAMESPACE);
  252. const char* task_queue = getenv(SMEE_TASK_QUEUE);
  253. if (scheme != NULL && host != NULL && port != NULL && ns != NULL && task_queue != NULL) {
  254. fprintf(stderr, "creating smee client\n");
  255. std::string hostPort = std::string(scheme) + std::string("://") + std::string(host) + std::string(":") + std::string(port);
  256. this->_smee = smeeclient::smee_client_new(hostPort.c_str(), ns, task_queue);
  257. }
  258. else {
  259. fprintf(stderr, "Smee client not configured\n");
  260. }
  261. }
  262. bool PostgreSQL::waitForReady()
  263. {
  264. while (_ready < 2) {
  265. _readyLock.lock();
  266. _readyLock.unlock();
  267. }
  268. return true;
  269. }
  270. bool PostgreSQL::isReady()
  271. {
  272. return ((_ready == 2) && (_connected));
  273. }
  274. bool PostgreSQL::save(nlohmann::json& record, bool notifyListeners)
  275. {
  276. bool modified = false;
  277. try {
  278. if (! record.is_object()) {
  279. fprintf(stderr, "record is not an object?!?\n");
  280. return false;
  281. }
  282. const std::string objtype = record["objtype"];
  283. if (objtype == "network") {
  284. // fprintf(stderr, "network save\n");
  285. const uint64_t nwid = OSUtils::jsonIntHex(record["id"], 0ULL);
  286. if (nwid) {
  287. nlohmann::json old;
  288. get(nwid, old);
  289. if ((! old.is_object()) || (! _compareRecords(old, record))) {
  290. record["revision"] = OSUtils::jsonInt(record["revision"], 0ULL) + 1ULL;
  291. _commitQueue.post(std::pair<nlohmann::json, bool>(record, notifyListeners));
  292. modified = true;
  293. }
  294. }
  295. }
  296. else if (objtype == "member") {
  297. std::string networkId = record["nwid"];
  298. std::string memberId = record["id"];
  299. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"], 0ULL);
  300. const uint64_t id = OSUtils::jsonIntHex(record["id"], 0ULL);
  301. // fprintf(stderr, "member save %s-%s\n", networkId.c_str(), memberId.c_str());
  302. if ((id) && (nwid)) {
  303. nlohmann::json network, old;
  304. get(nwid, network, id, old);
  305. if ((! old.is_object()) || (! _compareRecords(old, record))) {
  306. // fprintf(stderr, "commit queue post\n");
  307. record["revision"] = OSUtils::jsonInt(record["revision"], 0ULL) + 1ULL;
  308. _commitQueue.post(std::pair<nlohmann::json, bool>(record, notifyListeners));
  309. modified = true;
  310. }
  311. else {
  312. // fprintf(stderr, "no change\n");
  313. }
  314. }
  315. }
  316. else {
  317. fprintf(stderr, "uhh waaat\n");
  318. }
  319. }
  320. catch (std::exception& e) {
  321. fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what());
  322. }
  323. catch (...) {
  324. fprintf(stderr, "Unknown error on PostgreSQL::save\n");
  325. }
  326. return modified;
  327. }
  328. void PostgreSQL::eraseNetwork(const uint64_t networkId)
  329. {
  330. fprintf(stderr, "PostgreSQL::eraseNetwork\n");
  331. char tmp2[24];
  332. waitForReady();
  333. Utils::hex(networkId, tmp2);
  334. std::pair<nlohmann::json, bool> tmp;
  335. tmp.first["id"] = tmp2;
  336. tmp.first["objtype"] = "_delete_network";
  337. tmp.second = true;
  338. _commitQueue.post(tmp);
  339. nlohmann::json nullJson;
  340. _networkChanged(tmp.first, nullJson, true);
  341. }
  342. void PostgreSQL::eraseMember(const uint64_t networkId, const uint64_t memberId)
  343. {
  344. fprintf(stderr, "PostgreSQL::eraseMember\n");
  345. char tmp2[24];
  346. waitForReady();
  347. std::pair<nlohmann::json, bool> tmp, nw;
  348. Utils::hex(networkId, tmp2);
  349. tmp.first["nwid"] = tmp2;
  350. Utils::hex(memberId, tmp2);
  351. tmp.first["id"] = tmp2;
  352. tmp.first["objtype"] = "_delete_member";
  353. tmp.second = true;
  354. _commitQueue.post(tmp);
  355. nlohmann::json nullJson;
  356. _memberChanged(tmp.first, nullJson, true);
  357. }
  358. void PostgreSQL::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress)
  359. {
  360. std::lock_guard<std::mutex> l(_lastOnline_l);
  361. std::pair<int64_t, InetAddress>& i = _lastOnline[std::pair<uint64_t, uint64_t>(networkId, memberId)];
  362. i.first = OSUtils::now();
  363. if (physicalAddress) {
  364. i.second = physicalAddress;
  365. }
  366. }
  367. AuthInfo PostgreSQL::getSSOAuthInfo(const nlohmann::json& member, const std::string& redirectURL)
  368. {
  369. Metrics::db_get_sso_info++;
  370. // NONCE is just a random character string. no semantic meaning
  371. // state = HMAC SHA384 of Nonce based on shared sso key
  372. //
  373. // need nonce timeout in database? make sure it's used within X time
  374. // X is 5 minutes for now. Make configurable later?
  375. //
  376. // how do we tell when a nonce is used? if auth_expiration_time is set
  377. std::string networkId = member["nwid"];
  378. std::string memberId = member["id"];
  379. char authenticationURL[4096] = { 0 };
  380. AuthInfo info;
  381. info.enabled = true;
  382. // if (memberId == "a10dccea52" && networkId == "8056c2e21c24673d") {
  383. // fprintf(stderr, "invalid authinfo for grant's machine\n");
  384. // info.version=1;
  385. // return info;
  386. // }
  387. // fprintf(stderr, "PostgreSQL::updateMemberOnLoad: %s-%s\n", networkId.c_str(), memberId.c_str());
  388. std::shared_ptr<PostgresConnection> c;
  389. try {
  390. c = _pool->borrow();
  391. pqxx::work w(*c->c);
  392. char nonceBytes[16] = { 0 };
  393. std::string nonce = "";
  394. // check if the member exists first.
  395. pqxx::row count = w.exec_params1("SELECT count(id) FROM ztc_member WHERE id = $1 AND network_id = $2 AND deleted = false", memberId, networkId);
  396. if (count[0].as<int>() == 1) {
  397. // get active nonce, if exists.
  398. pqxx::result r = w.exec_params(
  399. "SELECT nonce FROM ztc_sso_expiry "
  400. "WHERE network_id = $1 AND member_id = $2 "
  401. "AND ((NOW() AT TIME ZONE 'UTC') <= authentication_expiry_time) AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  402. networkId,
  403. memberId);
  404. if (r.size() == 0) {
  405. // no active nonce.
  406. // find an unused nonce, if one exists.
  407. pqxx::result r = w.exec_params(
  408. "SELECT nonce FROM ztc_sso_expiry "
  409. "WHERE network_id = $1 AND member_id = $2 "
  410. "AND authentication_expiry_time IS NULL AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  411. networkId,
  412. memberId);
  413. if (r.size() == 1) {
  414. // we have an existing nonce. Use it
  415. nonce = r.at(0)[0].as<std::string>();
  416. Utils::unhex(nonce.c_str(), nonceBytes, sizeof(nonceBytes));
  417. }
  418. else if (r.empty()) {
  419. // create a nonce
  420. Utils::getSecureRandom(nonceBytes, 16);
  421. char nonceBuf[64] = { 0 };
  422. Utils::hex(nonceBytes, sizeof(nonceBytes), nonceBuf);
  423. nonce = std::string(nonceBuf);
  424. pqxx::result ir = w.exec_params0(
  425. "INSERT INTO ztc_sso_expiry "
  426. "(nonce, nonce_expiration, network_id, member_id) VALUES "
  427. "($1, TO_TIMESTAMP($2::double precision/1000), $3, $4)",
  428. nonce,
  429. OSUtils::now() + 300000,
  430. networkId,
  431. memberId);
  432. w.commit();
  433. }
  434. else {
  435. // > 1 ?!? Thats an error!
  436. fprintf(stderr, "> 1 unused nonce!\n");
  437. exit(6);
  438. }
  439. }
  440. else if (r.size() == 1) {
  441. nonce = r.at(0)[0].as<std::string>();
  442. Utils::unhex(nonce.c_str(), nonceBytes, sizeof(nonceBytes));
  443. }
  444. else {
  445. // more than 1 nonce in use? Uhhh...
  446. fprintf(stderr, "> 1 nonce in use for network member?!?\n");
  447. exit(7);
  448. }
  449. r = w.exec_params(
  450. "SELECT oc.client_id, oc.authorization_endpoint, oc.issuer, oc.provider, oc.sso_impl_version "
  451. "FROM ztc_network AS n "
  452. "INNER JOIN ztc_org o "
  453. " ON o.owner_id = n.owner_id "
  454. "LEFT OUTER JOIN ztc_network_oidc_config noc "
  455. " ON noc.network_id = n.id "
  456. "LEFT OUTER JOIN ztc_oidc_config oc "
  457. " ON noc.client_id = oc.client_id AND oc.org_id = o.org_id "
  458. "WHERE n.id = $1 AND n.sso_enabled = true",
  459. networkId);
  460. std::string client_id = "";
  461. std::string authorization_endpoint = "";
  462. std::string issuer = "";
  463. std::string provider = "";
  464. uint64_t sso_version = 0;
  465. if (r.size() == 1) {
  466. client_id = r.at(0)[0].as<std::optional<std::string> >().value_or("");
  467. authorization_endpoint = r.at(0)[1].as<std::optional<std::string> >().value_or("");
  468. issuer = r.at(0)[2].as<std::optional<std::string> >().value_or("");
  469. provider = r.at(0)[3].as<std::optional<std::string> >().value_or("");
  470. sso_version = r.at(0)[4].as<std::optional<uint64_t> >().value_or(1);
  471. }
  472. else if (r.size() > 1) {
  473. fprintf(stderr, "ERROR: More than one auth endpoint for an organization?!?!? NetworkID: %s\n", networkId.c_str());
  474. }
  475. else {
  476. fprintf(stderr, "No client or auth endpoint?!?\n");
  477. }
  478. info.version = sso_version;
  479. // no catch all else because we don't actually care if no records exist here. just continue as normal.
  480. if ((! client_id.empty()) && (! authorization_endpoint.empty())) {
  481. uint8_t state[48];
  482. HMACSHA384(_ssoPsk, nonceBytes, sizeof(nonceBytes), state);
  483. char state_hex[256];
  484. Utils::hex(state, 48, state_hex);
  485. if (info.version == 0) {
  486. char url[2048] = { 0 };
  487. OSUtils::ztsnprintf(
  488. url,
  489. sizeof(authenticationURL),
  490. "%s?response_type=id_token&response_mode=form_post&scope=openid+email+profile&redirect_uri=%s&nonce=%s&state=%s&client_id=%s",
  491. authorization_endpoint.c_str(),
  492. url_encode(redirectURL).c_str(),
  493. nonce.c_str(),
  494. state_hex,
  495. client_id.c_str());
  496. info.authenticationURL = std::string(url);
  497. }
  498. else if (info.version == 1) {
  499. info.ssoClientID = client_id;
  500. info.issuerURL = issuer;
  501. info.ssoProvider = provider;
  502. info.ssoNonce = nonce;
  503. info.ssoState = std::string(state_hex) + "_" + networkId;
  504. info.centralAuthURL = redirectURL;
  505. #ifdef ZT_DEBUG
  506. fprintf(
  507. stderr,
  508. "ssoClientID: %s\nissuerURL: %s\nssoNonce: %s\nssoState: %s\ncentralAuthURL: %s\nprovider: %s\n",
  509. info.ssoClientID.c_str(),
  510. info.issuerURL.c_str(),
  511. info.ssoNonce.c_str(),
  512. info.ssoState.c_str(),
  513. info.centralAuthURL.c_str(),
  514. provider.c_str());
  515. #endif
  516. }
  517. }
  518. else {
  519. fprintf(stderr, "client_id: %s\nauthorization_endpoint: %s\n", client_id.c_str(), authorization_endpoint.c_str());
  520. }
  521. }
  522. _pool->unborrow(c);
  523. }
  524. catch (std::exception& e) {
  525. fprintf(stderr, "ERROR: Error updating member on load for network %s: %s\n", networkId.c_str(), e.what());
  526. }
  527. return info; // std::string(authenticationURL);
  528. }
  529. void PostgreSQL::initializeNetworks()
  530. {
  531. try {
  532. std::string setKey = "networks:{" + _myAddressStr + "}";
  533. fprintf(stderr, "Initializing Networks...\n");
  534. if (_redisMemberStatus) {
  535. fprintf(stderr, "Init Redis for networks...\n");
  536. try {
  537. if (_rc->clusterMode) {
  538. _cluster->del(setKey);
  539. }
  540. else {
  541. _redis->del(setKey);
  542. }
  543. }
  544. catch (sw::redis::Error& e) {
  545. // ignore. if this key doesn't exist, there's no reason to delete it
  546. }
  547. }
  548. std::unordered_set<std::string> networkSet;
  549. char qbuf[2048] = { 0 };
  550. sprintf(
  551. qbuf,
  552. "SELECT n.id, (EXTRACT(EPOCH FROM n.creation_time AT TIME ZONE 'UTC')*1000)::bigint as creation_time, n.capabilities, "
  553. "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, "
  554. "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 noc.client_id ELSE NULL END) as client_id, "
  555. "(CASE WHEN n.sso_enabled THEN oc.authorization_endpoint ELSE NULL END) as authorization_endpoint, "
  556. "(CASE WHEN n.sso_enabled THEN oc.provider ELSE NULL END) as provider, d.domain, d.servers, "
  557. "ARRAY(SELECT CONCAT(host(ip_range_start),'|', host(ip_range_end)) FROM ztc_network_assignment_pool WHERE network_id = n.id) AS assignment_pool, "
  558. "ARRAY(SELECT CONCAT(host(address),'/',bits::text,'|',COALESCE(host(via), 'NULL'))FROM ztc_network_route WHERE network_id = n.id) AS routes "
  559. "FROM ztc_network n "
  560. "LEFT OUTER JOIN ztc_org o "
  561. " ON o.owner_id = n.owner_id "
  562. "LEFT OUTER JOIN ztc_network_oidc_config noc "
  563. " ON noc.network_id = n.id "
  564. "LEFT OUTER JOIN ztc_oidc_config oc "
  565. " ON noc.client_id = oc.client_id AND oc.org_id = o.org_id "
  566. "LEFT OUTER JOIN ztc_network_dns d "
  567. " ON d.network_id = n.id "
  568. "WHERE deleted = false AND controller_id = '%s'",
  569. _myAddressStr.c_str());
  570. auto c = _pool->borrow();
  571. auto c2 = _pool->borrow();
  572. pqxx::work w { *c->c };
  573. fprintf(stderr, "Load networks from psql...\n");
  574. auto stream = pqxx::stream_from::query(w, qbuf);
  575. std::tuple<
  576. std::string // network ID
  577. ,
  578. std::optional<int64_t> // creationTime
  579. ,
  580. std::optional<std::string> // capabilities
  581. ,
  582. std::optional<bool> // enableBroadcast
  583. ,
  584. std::optional<uint64_t> // lastModified
  585. ,
  586. std::optional<int> // mtu
  587. ,
  588. std::optional<int> // multicastLimit
  589. ,
  590. std::optional<std::string> // name
  591. ,
  592. bool // private
  593. ,
  594. std::optional<int> // remoteTraceLevel
  595. ,
  596. std::optional<std::string> // remoteTraceTarget
  597. ,
  598. std::optional<uint64_t> // revision
  599. ,
  600. std::optional<std::string> // rules
  601. ,
  602. std::optional<std::string> // tags
  603. ,
  604. std::optional<std::string> // v4AssignMode
  605. ,
  606. std::optional<std::string> // v6AssignMode
  607. ,
  608. std::optional<bool> // ssoEnabled
  609. ,
  610. std::optional<std::string> // clientId
  611. ,
  612. std::optional<std::string> // authorizationEndpoint
  613. ,
  614. std::optional<std::string> // ssoProvider
  615. ,
  616. std::optional<std::string> // domain
  617. ,
  618. std::optional<std::string> // servers
  619. ,
  620. std::string // assignmentPoolString
  621. ,
  622. std::string // routeString
  623. >
  624. row;
  625. uint64_t count = 0;
  626. auto tmp = std::chrono::high_resolution_clock::now();
  627. uint64_t total = 0;
  628. while (stream >> row) {
  629. auto start = std::chrono::high_resolution_clock::now();
  630. json empty;
  631. json config;
  632. initNetwork(config);
  633. std::string nwid = std::get<0>(row);
  634. std::optional<int64_t> creationTime = std::get<1>(row);
  635. std::optional<std::string> capabilities = std::get<2>(row);
  636. std::optional<bool> enableBroadcast = std::get<3>(row);
  637. std::optional<uint64_t> lastModified = std::get<4>(row);
  638. std::optional<int> mtu = std::get<5>(row);
  639. std::optional<int> multicastLimit = std::get<6>(row);
  640. std::optional<std::string> name = std::get<7>(row);
  641. bool isPrivate = std::get<8>(row);
  642. std::optional<int> remoteTraceLevel = std::get<9>(row);
  643. std::optional<std::string> remoteTraceTarget = std::get<10>(row);
  644. std::optional<uint64_t> revision = std::get<11>(row);
  645. std::optional<std::string> rules = std::get<12>(row);
  646. std::optional<std::string> tags = std::get<13>(row);
  647. std::optional<std::string> v4AssignMode = std::get<14>(row);
  648. std::optional<std::string> v6AssignMode = std::get<15>(row);
  649. std::optional<bool> ssoEnabled = std::get<16>(row);
  650. std::optional<std::string> clientId = std::get<17>(row);
  651. std::optional<std::string> authorizationEndpoint = std::get<18>(row);
  652. std::optional<std::string> ssoProvider = std::get<19>(row);
  653. std::optional<std::string> dnsDomain = std::get<20>(row);
  654. std::optional<std::string> dnsServers = std::get<21>(row);
  655. std::string assignmentPoolString = std::get<22>(row);
  656. std::string routesString = std::get<23>(row);
  657. config["id"] = nwid;
  658. config["nwid"] = nwid;
  659. config["creationTime"] = creationTime.value_or(0);
  660. config["capabilities"] = json::parse(capabilities.value_or("[]"));
  661. config["enableBroadcast"] = enableBroadcast.value_or(false);
  662. config["lastModified"] = lastModified.value_or(0);
  663. config["mtu"] = mtu.value_or(2800);
  664. config["multicastLimit"] = multicastLimit.value_or(64);
  665. config["name"] = name.value_or("");
  666. config["private"] = isPrivate;
  667. config["remoteTraceLevel"] = remoteTraceLevel.value_or(0);
  668. config["remoteTraceTarget"] = remoteTraceTarget.value_or("");
  669. config["revision"] = revision.value_or(0);
  670. config["rules"] = json::parse(rules.value_or("[]"));
  671. config["tags"] = json::parse(tags.value_or("[]"));
  672. config["v4AssignMode"] = json::parse(v4AssignMode.value_or("{}"));
  673. config["v6AssignMode"] = json::parse(v6AssignMode.value_or("{}"));
  674. config["ssoEnabled"] = ssoEnabled.value_or(false);
  675. config["objtype"] = "network";
  676. config["ipAssignmentPools"] = json::array();
  677. config["routes"] = json::array();
  678. config["clientId"] = clientId.value_or("");
  679. config["authorizationEndpoint"] = authorizationEndpoint.value_or("");
  680. config["provider"] = ssoProvider.value_or("");
  681. networkSet.insert(nwid);
  682. if (dnsDomain.has_value()) {
  683. std::string serverList = dnsServers.value();
  684. json obj;
  685. auto servers = json::array();
  686. if (serverList.rfind("{", 0) != std::string::npos) {
  687. serverList = serverList.substr(1, serverList.size() - 2);
  688. std::stringstream ss(serverList);
  689. while (ss.good()) {
  690. std::string server;
  691. std::getline(ss, server, ',');
  692. servers.push_back(server);
  693. }
  694. }
  695. obj["domain"] = dnsDomain.value();
  696. obj["servers"] = servers;
  697. config["dns"] = obj;
  698. }
  699. config["ipAssignmentPools"] = json::array();
  700. if (assignmentPoolString != "{}") {
  701. std::string tmp = assignmentPoolString.substr(1, assignmentPoolString.size() - 2);
  702. std::vector<std::string> assignmentPools = split(tmp, ',');
  703. for (auto it = assignmentPools.begin(); it != assignmentPools.end(); ++it) {
  704. std::vector<std::string> r = split(*it, '|');
  705. json ip;
  706. ip["ipRangeStart"] = r[0];
  707. ip["ipRangeEnd"] = r[1];
  708. config["ipAssignmentPools"].push_back(ip);
  709. }
  710. }
  711. config["routes"] = json::array();
  712. if (routesString != "{}") {
  713. std::string tmp = routesString.substr(1, routesString.size() - 2);
  714. std::vector<std::string> routes = split(tmp, ',');
  715. for (auto it = routes.begin(); it != routes.end(); ++it) {
  716. std::vector<std::string> r = split(*it, '|');
  717. json route;
  718. route["target"] = r[0];
  719. route["via"] = ((route["via"] == "NULL") ? nullptr : r[1]);
  720. config["routes"].push_back(route);
  721. }
  722. }
  723. Metrics::network_count++;
  724. _networkChanged(empty, config, false);
  725. auto end = std::chrono::high_resolution_clock::now();
  726. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
  727. ;
  728. total += dur.count();
  729. ++count;
  730. if (count > 0 && count % 10000 == 0) {
  731. fprintf(stderr, "Averaging %llu us per network\n", (total / count));
  732. }
  733. }
  734. if (count > 0) {
  735. fprintf(stderr, "Took %llu us per network to load\n", (total / count));
  736. }
  737. stream.complete();
  738. w.commit();
  739. _pool->unborrow(c2);
  740. _pool->unborrow(c);
  741. fprintf(stderr, "done.\n");
  742. if (! networkSet.empty()) {
  743. if (_redisMemberStatus) {
  744. fprintf(stderr, "adding networks to redis...\n");
  745. if (_rc->clusterMode) {
  746. auto tx = _cluster->transaction(_myAddressStr, true, false);
  747. uint64_t count = 0;
  748. for (std::string nwid : networkSet) {
  749. tx.sadd(setKey, nwid);
  750. if (++count % 30000 == 0) {
  751. tx.exec();
  752. tx = _cluster->transaction(_myAddressStr, true, false);
  753. }
  754. }
  755. tx.exec();
  756. }
  757. else {
  758. auto tx = _redis->transaction(true, false);
  759. uint64_t count = 0;
  760. for (std::string nwid : networkSet) {
  761. tx.sadd(setKey, nwid);
  762. if (++count % 30000 == 0) {
  763. tx.exec();
  764. tx = _redis->transaction(true, false);
  765. }
  766. }
  767. tx.exec();
  768. }
  769. fprintf(stderr, "done.\n");
  770. }
  771. }
  772. if (++this->_ready == 2) {
  773. if (_waitNoticePrinted) {
  774. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S, _timestr(), (unsigned long long)_myAddress.toInt());
  775. }
  776. _readyLock.unlock();
  777. }
  778. fprintf(stderr, "network init done.\n");
  779. }
  780. catch (sw::redis::Error& e) {
  781. fprintf(stderr, "ERROR: Error initializing networks in Redis: %s\n", e.what());
  782. std::this_thread::sleep_for(std::chrono::milliseconds(5000));
  783. exit(-1);
  784. }
  785. catch (std::exception& e) {
  786. fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
  787. std::this_thread::sleep_for(std::chrono::milliseconds(5000));
  788. exit(-1);
  789. }
  790. }
  791. void PostgreSQL::initializeMembers()
  792. {
  793. std::string memberId;
  794. std::string networkId;
  795. try {
  796. std::unordered_map<std::string, std::string> networkMembers;
  797. fprintf(stderr, "Initializing Members...\n");
  798. std::string setKeyBase = "network-nodes-all:{" + _myAddressStr + "}:";
  799. if (_redisMemberStatus) {
  800. fprintf(stderr, "Initialize Redis for members...\n");
  801. std::unique_lock<std::shared_mutex> l(_networks_l);
  802. std::unordered_set<std::string> deletes;
  803. for (auto it : _networks) {
  804. uint64_t nwid_i = it.first;
  805. char nwidTmp[64] = { 0 };
  806. OSUtils::ztsnprintf(nwidTmp, sizeof(nwidTmp), "%.16llx", nwid_i);
  807. std::string nwid(nwidTmp);
  808. std::string key = setKeyBase + nwid;
  809. deletes.insert(key);
  810. }
  811. if (! deletes.empty()) {
  812. try {
  813. if (_rc->clusterMode) {
  814. auto tx = _cluster->transaction(_myAddressStr, true, false);
  815. for (std::string k : deletes) {
  816. tx.del(k);
  817. }
  818. tx.exec();
  819. }
  820. else {
  821. auto tx = _redis->transaction(true, false);
  822. for (std::string k : deletes) {
  823. tx.del(k);
  824. }
  825. tx.exec();
  826. }
  827. }
  828. catch (sw::redis::Error& e) {
  829. // ignore
  830. }
  831. }
  832. }
  833. char qbuf[2048];
  834. sprintf(
  835. qbuf,
  836. "SELECT m.id, m.network_id, m.active_bridge, m.authorized, m.capabilities, "
  837. "(EXTRACT(EPOCH FROM m.creation_time AT TIME ZONE 'UTC')*1000)::bigint, m.identity, "
  838. "(EXTRACT(EPOCH FROM m.last_authorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  839. "(EXTRACT(EPOCH FROM m.last_deauthorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  840. "m.remote_trace_level, m.remote_trace_target, m.tags, m.v_major, m.v_minor, m.v_rev, m.v_proto, "
  841. "m.no_auto_assign_ips, m.revision, m.sso_exempt, "
  842. "(CASE WHEN n.sso_enabled = TRUE AND m.sso_exempt = FALSE THEN "
  843. " ( "
  844. " SELECT (EXTRACT(EPOCH FROM e.authentication_expiry_time)*1000)::bigint "
  845. " FROM ztc_sso_expiry e "
  846. " INNER JOIN ztc_network n1 "
  847. " ON n1.id = e.network_id AND n1.deleted = TRUE "
  848. " 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 "
  849. " ORDER BY e.authentication_expiry_time DESC LIMIT 1 "
  850. " ) "
  851. " ELSE NULL "
  852. " END) AS authentication_expiry_time, "
  853. "ARRAY(SELECT DISTINCT address FROM ztc_member_ip_assignment WHERE member_id = m.id AND network_id = m.network_id) AS assigned_addresses "
  854. "FROM ztc_member m "
  855. "INNER JOIN ztc_network n "
  856. " ON n.id = m.network_id "
  857. "WHERE n.controller_id = '%s' AND n.deleted = FALSE AND m.deleted = FALSE",
  858. _myAddressStr.c_str());
  859. auto c = _pool->borrow();
  860. auto c2 = _pool->borrow();
  861. pqxx::work w { *c->c };
  862. fprintf(stderr, "Load members from psql...\n");
  863. auto stream = pqxx::stream_from::query(w, qbuf);
  864. std::tuple<
  865. std::string // memberId
  866. ,
  867. std::string // memberId
  868. ,
  869. std::optional<bool> // activeBridge
  870. ,
  871. std::optional<bool> // authorized
  872. ,
  873. std::optional<std::string> // capabilities
  874. ,
  875. std::optional<uint64_t> // creationTime
  876. ,
  877. std::optional<std::string> // identity
  878. ,
  879. std::optional<uint64_t> // lastAuthorizedTime
  880. ,
  881. std::optional<uint64_t> // lastDeauthorizedTime
  882. ,
  883. std::optional<int> // remoteTraceLevel
  884. ,
  885. std::optional<std::string> // remoteTraceTarget
  886. ,
  887. std::optional<std::string> // tags
  888. ,
  889. std::optional<int> // vMajor
  890. ,
  891. std::optional<int> // vMinor
  892. ,
  893. std::optional<int> // vRev
  894. ,
  895. std::optional<int> // vProto
  896. ,
  897. std::optional<bool> // noAutoAssignIps
  898. ,
  899. std::optional<uint64_t> // revision
  900. ,
  901. std::optional<bool> // ssoExempt
  902. ,
  903. std::optional<uint64_t> // authenticationExpiryTime
  904. ,
  905. std::string // assignedAddresses
  906. >
  907. row;
  908. uint64_t count = 0;
  909. auto tmp = std::chrono::high_resolution_clock::now();
  910. uint64_t total = 0;
  911. while (stream >> row) {
  912. auto start = std::chrono::high_resolution_clock::now();
  913. json empty;
  914. json config;
  915. initMember(config);
  916. memberId = std::get<0>(row);
  917. networkId = std::get<1>(row);
  918. std::optional<bool> activeBridge = std::get<2>(row);
  919. std::optional<bool> authorized = std::get<3>(row);
  920. std::optional<std::string> capabilities = std::get<4>(row);
  921. std::optional<uint64_t> creationTime = std::get<5>(row);
  922. std::optional<std::string> identity = std::get<6>(row);
  923. std::optional<uint64_t> lastAuthorizedTime = std::get<7>(row);
  924. std::optional<uint64_t> lastDeauthorizedTime = std::get<8>(row);
  925. std::optional<int> remoteTraceLevel = std::get<9>(row);
  926. std::optional<std::string> remoteTraceTarget = std::get<10>(row);
  927. std::optional<std::string> tags = std::get<11>(row);
  928. std::optional<int> vMajor = std::get<12>(row);
  929. std::optional<int> vMinor = std::get<13>(row);
  930. std::optional<int> vRev = std::get<14>(row);
  931. std::optional<int> vProto = std::get<15>(row);
  932. std::optional<bool> noAutoAssignIps = std::get<16>(row);
  933. std::optional<uint64_t> revision = std::get<17>(row);
  934. std::optional<bool> ssoExempt = std::get<18>(row);
  935. std::optional<uint64_t> authenticationExpiryTime = std::get<19>(row);
  936. std::string assignedAddresses = std::get<20>(row);
  937. networkMembers.insert(std::pair<std::string, std::string>(setKeyBase + networkId, memberId));
  938. config["id"] = memberId;
  939. config["address"] = memberId;
  940. config["nwid"] = networkId;
  941. config["activeBridge"] = activeBridge.value_or(false);
  942. config["authorized"] = authorized.value_or(false);
  943. config["capabilities"] = json::parse(capabilities.value_or("[]"));
  944. config["creationTime"] = creationTime.value_or(0);
  945. config["identity"] = identity.value_or("");
  946. config["lastAuthorizedTime"] = lastAuthorizedTime.value_or(0);
  947. config["lastDeauthorizedTime"] = lastDeauthorizedTime.value_or(0);
  948. config["remoteTraceLevel"] = remoteTraceLevel.value_or(0);
  949. config["remoteTraceTarget"] = remoteTraceTarget.value_or("");
  950. config["tags"] = json::parse(tags.value_or("[]"));
  951. config["vMajor"] = vMajor.value_or(-1);
  952. config["vMinor"] = vMinor.value_or(-1);
  953. config["vRev"] = vRev.value_or(-1);
  954. config["vProto"] = vProto.value_or(-1);
  955. config["noAutoAssignIps"] = noAutoAssignIps.value_or(false);
  956. config["revision"] = revision.value_or(0);
  957. config["ssoExempt"] = ssoExempt.value_or(false);
  958. config["authenticationExpiryTime"] = authenticationExpiryTime.value_or(0);
  959. config["objtype"] = "member";
  960. config["ipAssignments"] = json::array();
  961. if (assignedAddresses != "{}") {
  962. std::string tmp = assignedAddresses.substr(1, assignedAddresses.size() - 2);
  963. std::vector<std::string> addrs = split(tmp, ',');
  964. for (auto it = addrs.begin(); it != addrs.end(); ++it) {
  965. config["ipAssignments"].push_back(*it);
  966. }
  967. }
  968. Metrics::member_count++;
  969. _memberChanged(empty, config, false);
  970. memberId = "";
  971. networkId = "";
  972. auto end = std::chrono::high_resolution_clock::now();
  973. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
  974. total += dur.count();
  975. ++count;
  976. if (count > 0 && count % 10000 == 0) {
  977. fprintf(stderr, "Averaging %llu us per member\n", (total / count));
  978. }
  979. }
  980. if (count > 0) {
  981. fprintf(stderr, "Took %llu us per member to load\n", (total / count));
  982. }
  983. stream.complete();
  984. w.commit();
  985. _pool->unborrow(c2);
  986. _pool->unborrow(c);
  987. fprintf(stderr, "done.\n");
  988. if (! networkMembers.empty()) {
  989. if (_redisMemberStatus) {
  990. fprintf(stderr, "Load member data into redis...\n");
  991. if (_rc->clusterMode) {
  992. auto tx = _cluster->transaction(_myAddressStr, true, false);
  993. uint64_t count = 0;
  994. for (auto it : networkMembers) {
  995. tx.sadd(it.first, it.second);
  996. if (++count % 30000 == 0) {
  997. tx.exec();
  998. tx = _cluster->transaction(_myAddressStr, true, false);
  999. }
  1000. }
  1001. tx.exec();
  1002. }
  1003. else {
  1004. auto tx = _redis->transaction(true, false);
  1005. uint64_t count = 0;
  1006. for (auto it : networkMembers) {
  1007. tx.sadd(it.first, it.second);
  1008. if (++count % 30000 == 0) {
  1009. tx.exec();
  1010. tx = _redis->transaction(true, false);
  1011. }
  1012. }
  1013. tx.exec();
  1014. }
  1015. fprintf(stderr, "done.\n");
  1016. }
  1017. }
  1018. fprintf(stderr, "Done loading members...\n");
  1019. if (++this->_ready == 2) {
  1020. if (_waitNoticePrinted) {
  1021. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S, _timestr(), (unsigned long long)_myAddress.toInt());
  1022. }
  1023. _readyLock.unlock();
  1024. }
  1025. }
  1026. catch (sw::redis::Error& e) {
  1027. fprintf(stderr, "ERROR: Error initializing members (redis): %s\n", e.what());
  1028. exit(-1);
  1029. }
  1030. catch (std::exception& e) {
  1031. fprintf(stderr, "ERROR: Error initializing member: %s-%s %s\n", networkId.c_str(), memberId.c_str(), e.what());
  1032. exit(-1);
  1033. }
  1034. }
  1035. void PostgreSQL::heartbeat()
  1036. {
  1037. char publicId[1024];
  1038. char hostnameTmp[1024];
  1039. _myId.toString(false, publicId);
  1040. if (gethostname(hostnameTmp, sizeof(hostnameTmp)) != 0) {
  1041. hostnameTmp[0] = (char)0;
  1042. }
  1043. else {
  1044. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  1045. if ((hostnameTmp[i] == '.') || (hostnameTmp[i] == 0)) {
  1046. hostnameTmp[i] = (char)0;
  1047. break;
  1048. }
  1049. }
  1050. }
  1051. const char* controllerId = _myAddressStr.c_str();
  1052. const char* publicIdentity = publicId;
  1053. const char* hostname = hostnameTmp;
  1054. while (_run == 1) {
  1055. // fprintf(stderr, "%s: heartbeat\n", controllerId);
  1056. auto c = _pool->borrow();
  1057. int64_t ts = OSUtils::now();
  1058. if (c->c) {
  1059. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  1060. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  1061. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  1062. std::string build = std::to_string(ZEROTIER_ONE_VERSION_BUILD);
  1063. std::string now = std::to_string(ts);
  1064. std::string host_port = std::to_string(_listenPort);
  1065. std::string use_redis = (_rc != NULL) ? "true" : "false";
  1066. std::string redis_mem_status = (_redisMemberStatus) ? "true" : "false";
  1067. try {
  1068. pqxx::work w { *c->c };
  1069. pqxx::result res = w.exec0(
  1070. "INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build, host_port, use_redis, redis_member_status) "
  1071. "VALUES ("
  1072. + w.quote(controllerId) + ", " + w.quote(hostname) + ", TO_TIMESTAMP(" + now + "::double precision/1000), " + w.quote(publicIdentity) + ", " + major + ", " + minor + ", " + rev + ", " + build + ", " + host_port + ", "
  1073. + use_redis + ", " + redis_mem_status
  1074. + ") "
  1075. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  1076. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  1077. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev, host_port = EXCLUDED.host_port, "
  1078. "use_redis = EXCLUDED.use_redis, redis_member_status = EXCLUDED.redis_member_status");
  1079. w.commit();
  1080. }
  1081. catch (std::exception& e) {
  1082. fprintf(stderr, "%s: Heartbeat update failed: %s\n", controllerId, e.what());
  1083. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  1084. continue;
  1085. }
  1086. }
  1087. _pool->unborrow(c);
  1088. try {
  1089. if (_redisMemberStatus) {
  1090. if (_rc->clusterMode) {
  1091. _cluster->zadd("controllers", "controllerId", ts);
  1092. }
  1093. else {
  1094. _redis->zadd("controllers", "controllerId", ts);
  1095. }
  1096. }
  1097. }
  1098. catch (sw::redis::Error& e) {
  1099. fprintf(stderr, "ERROR: Redis error in heartbeat thread: %s\n", e.what());
  1100. }
  1101. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  1102. }
  1103. fprintf(stderr, "Exited heartbeat thread\n");
  1104. }
  1105. void PostgreSQL::membersDbWatcher()
  1106. {
  1107. if (_rc) {
  1108. _membersWatcher_Redis();
  1109. }
  1110. else {
  1111. _membersWatcher_Postgres();
  1112. }
  1113. if (_run == 1) {
  1114. fprintf(stderr, "ERROR: %s membersDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1115. exit(9);
  1116. }
  1117. fprintf(stderr, "Exited membersDbWatcher\n");
  1118. }
  1119. void PostgreSQL::_membersWatcher_Postgres()
  1120. {
  1121. auto c = _pool->borrow();
  1122. std::string stream = "member_" + _myAddressStr;
  1123. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  1124. MemberNotificationReceiver m(this, *c->c, stream);
  1125. while (_run == 1) {
  1126. c->c->await_notification(5, 0);
  1127. }
  1128. _pool->unborrow(c);
  1129. }
  1130. void PostgreSQL::_membersWatcher_Redis()
  1131. {
  1132. char buf[11] = { 0 };
  1133. std::string key = "member-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  1134. std::string lastID = "0";
  1135. fprintf(stderr, "Listening to member stream: %s\n", key.c_str());
  1136. while (_run == 1) {
  1137. try {
  1138. json tmp;
  1139. std::unordered_map<std::string, ItemStream> result;
  1140. if (_rc->clusterMode) {
  1141. _cluster->xread(key, lastID, std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  1142. }
  1143. else {
  1144. _redis->xread(key, lastID, std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  1145. }
  1146. if (! result.empty()) {
  1147. for (auto element : result) {
  1148. #ifdef REDIS_TRACE
  1149. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  1150. #endif
  1151. for (auto rec : element.second) {
  1152. std::string id = rec.first;
  1153. auto attrs = rec.second;
  1154. #ifdef REDIS_TRACE
  1155. fprintf(stdout, "Record ID: %s\n", id.c_str());
  1156. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  1157. #endif
  1158. for (auto a : attrs) {
  1159. #ifdef REDIS_TRACE
  1160. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  1161. #endif
  1162. try {
  1163. tmp = json::parse(a.second);
  1164. json& ov = tmp["old_val"];
  1165. json& nv = tmp["new_val"];
  1166. json oldConfig, newConfig;
  1167. if (ov.is_object())
  1168. oldConfig = ov;
  1169. if (nv.is_object())
  1170. newConfig = nv;
  1171. if (oldConfig.is_object() || newConfig.is_object()) {
  1172. _memberChanged(oldConfig, newConfig, (this->_ready >= 2));
  1173. }
  1174. }
  1175. catch (...) {
  1176. fprintf(stderr, "json parse error in _membersWatcher_Redis: %s\n", a.second.c_str());
  1177. }
  1178. }
  1179. if (_rc->clusterMode) {
  1180. _cluster->xdel(key, id);
  1181. }
  1182. else {
  1183. _redis->xdel(key, id);
  1184. }
  1185. lastID = id;
  1186. Metrics::redis_mem_notification++;
  1187. }
  1188. }
  1189. }
  1190. }
  1191. catch (sw::redis::Error& e) {
  1192. fprintf(stderr, "Error in Redis members watcher: %s\n", e.what());
  1193. }
  1194. }
  1195. fprintf(stderr, "membersWatcher ended\n");
  1196. }
  1197. void PostgreSQL::networksDbWatcher()
  1198. {
  1199. if (_rc) {
  1200. _networksWatcher_Redis();
  1201. }
  1202. else {
  1203. _networksWatcher_Postgres();
  1204. }
  1205. if (_run == 1) {
  1206. fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1207. exit(8);
  1208. }
  1209. fprintf(stderr, "Exited networksDbWatcher\n");
  1210. }
  1211. void PostgreSQL::_networksWatcher_Postgres()
  1212. {
  1213. std::string stream = "network_" + _myAddressStr;
  1214. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  1215. auto c = _pool->borrow();
  1216. NetworkNotificationReceiver n(this, *c->c, stream);
  1217. while (_run == 1) {
  1218. c->c->await_notification(5, 0);
  1219. }
  1220. }
  1221. void PostgreSQL::_networksWatcher_Redis()
  1222. {
  1223. char buf[11] = { 0 };
  1224. std::string key = "network-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  1225. std::string lastID = "0";
  1226. while (_run == 1) {
  1227. try {
  1228. json tmp;
  1229. std::unordered_map<std::string, ItemStream> result;
  1230. if (_rc->clusterMode) {
  1231. _cluster->xread(key, lastID, std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  1232. }
  1233. else {
  1234. _redis->xread(key, lastID, std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  1235. }
  1236. if (! result.empty()) {
  1237. for (auto element : result) {
  1238. #ifdef REDIS_TRACE
  1239. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  1240. #endif
  1241. for (auto rec : element.second) {
  1242. std::string id = rec.first;
  1243. auto attrs = rec.second;
  1244. #ifdef REDIS_TRACE
  1245. fprintf(stdout, "Record ID: %s\n", id.c_str());
  1246. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  1247. #endif
  1248. for (auto a : attrs) {
  1249. #ifdef REDIS_TRACE
  1250. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  1251. #endif
  1252. try {
  1253. tmp = json::parse(a.second);
  1254. json& ov = tmp["old_val"];
  1255. json& nv = tmp["new_val"];
  1256. json oldConfig, newConfig;
  1257. if (ov.is_object())
  1258. oldConfig = ov;
  1259. if (nv.is_object())
  1260. newConfig = nv;
  1261. if (oldConfig.is_object() || newConfig.is_object()) {
  1262. _networkChanged(oldConfig, newConfig, (this->_ready >= 2));
  1263. }
  1264. }
  1265. catch (std::exception& e) {
  1266. fprintf(stderr, "json parse error in networkWatcher_Redis: what: %s json: %s\n", e.what(), a.second.c_str());
  1267. }
  1268. }
  1269. if (_rc->clusterMode) {
  1270. _cluster->xdel(key, id);
  1271. }
  1272. else {
  1273. _redis->xdel(key, id);
  1274. }
  1275. lastID = id;
  1276. }
  1277. Metrics::redis_net_notification++;
  1278. }
  1279. }
  1280. }
  1281. catch (sw::redis::Error& e) {
  1282. fprintf(stderr, "Error in Redis networks watcher: %s\n", e.what());
  1283. }
  1284. }
  1285. fprintf(stderr, "networksWatcher ended\n");
  1286. }
  1287. void PostgreSQL::commitThread()
  1288. {
  1289. fprintf(stderr, "%s: commitThread start\n", _myAddressStr.c_str());
  1290. std::pair<nlohmann::json, bool> qitem;
  1291. while (_commitQueue.get(qitem) & (_run == 1)) {
  1292. // fprintf(stderr, "commitThread tick\n");
  1293. if (! qitem.first.is_object()) {
  1294. fprintf(stderr, "not an object\n");
  1295. continue;
  1296. }
  1297. std::shared_ptr<PostgresConnection> c;
  1298. try {
  1299. c = _pool->borrow();
  1300. }
  1301. catch (std::exception& e) {
  1302. fprintf(stderr, "ERROR: %s\n", e.what());
  1303. continue;
  1304. }
  1305. if (! c) {
  1306. fprintf(stderr, "Error getting database connection\n");
  1307. continue;
  1308. }
  1309. Metrics::pgsql_commit_ticks++;
  1310. try {
  1311. nlohmann::json& config = (qitem.first);
  1312. const std::string objtype = config["objtype"];
  1313. if (objtype == "member") {
  1314. // fprintf(stderr, "%s: commitThread: member\n", _myAddressStr.c_str());
  1315. std::string memberId;
  1316. std::string networkId;
  1317. try {
  1318. pqxx::work w(*c->c);
  1319. memberId = config["id"];
  1320. networkId = config["nwid"];
  1321. std::string target = "NULL";
  1322. if (! config["remoteTraceTarget"].is_null()) {
  1323. target = config["remoteTraceTarget"];
  1324. }
  1325. pqxx::row nwrow = w.exec_params1("SELECT COUNT(id) FROM ztc_network WHERE id = $1", networkId);
  1326. int nwcount = nwrow[0].as<int>();
  1327. if (nwcount != 1) {
  1328. fprintf(stderr, "network %s does not exist. skipping member upsert\n", networkId.c_str());
  1329. w.abort();
  1330. _pool->unborrow(c);
  1331. continue;
  1332. }
  1333. pqxx::row mrow = w.exec_params1("SELECT COUNT(id) FROM ztc_member WHERE id = $1 AND network_id = $2", memberId, networkId);
  1334. int membercount = mrow[0].as<int>();
  1335. bool isNewMember = false;
  1336. if (membercount == 0) {
  1337. // new member
  1338. isNewMember = true;
  1339. pqxx::result res = w.exec_params0(
  1340. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  1341. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  1342. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  1343. "VALUES ($1, $2, $3, $4, $5, $6, "
  1344. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  1345. "$9, $10, $11, $12, $13, $14, $15, $16, $17)",
  1346. memberId,
  1347. networkId,
  1348. (bool)config["activeBridge"],
  1349. (bool)config["authorized"],
  1350. OSUtils::jsonDump(config["capabilities"], -1),
  1351. OSUtils::jsonString(config["identity"], ""),
  1352. (uint64_t)config["lastAuthorizedTime"],
  1353. (uint64_t)config["lastDeauthorizedTime"],
  1354. (bool)config["noAutoAssignIps"],
  1355. (int)config["remoteTraceLevel"],
  1356. target,
  1357. (uint64_t)config["revision"],
  1358. OSUtils::jsonDump(config["tags"], -1),
  1359. (int)config["vMajor"],
  1360. (int)config["vMinor"],
  1361. (int)config["vRev"],
  1362. (int)config["vProto"]);
  1363. }
  1364. else {
  1365. // existing member
  1366. pqxx::result res = w.exec_params0(
  1367. "UPDATE ztc_member "
  1368. "SET active_bridge = $3, authorized = $4, capabilities = $5, identity = $6, "
  1369. "last_authorized_time = TO_TIMESTAMP($7::double precision/1000), "
  1370. "last_deauthorized_time = TO_TIMESTAMP($8::double precision/1000), "
  1371. "no_auto_assign_ips = $9, remote_trace_level = $10, remote_trace_target= $11, "
  1372. "revision = $12, tags = $13, v_major = $14, v_minor = $15, v_rev = $16, v_proto = $17 "
  1373. "WHERE id = $1 AND network_id = $2",
  1374. memberId,
  1375. networkId,
  1376. (bool)config["activeBridge"],
  1377. (bool)config["authorized"],
  1378. OSUtils::jsonDump(config["capabilities"], -1),
  1379. OSUtils::jsonString(config["identity"], ""),
  1380. (uint64_t)config["lastAuthorizedTime"],
  1381. (uint64_t)config["lastDeauthorizedTime"],
  1382. (bool)config["noAutoAssignIps"],
  1383. (int)config["remoteTraceLevel"],
  1384. target,
  1385. (uint64_t)config["revision"],
  1386. OSUtils::jsonDump(config["tags"], -1),
  1387. (int)config["vMajor"],
  1388. (int)config["vMinor"],
  1389. (int)config["vRev"],
  1390. (int)config["vProto"]);
  1391. }
  1392. if (! isNewMember) {
  1393. pqxx::result res = w.exec_params0("DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2", memberId, networkId);
  1394. }
  1395. std::vector<std::string> assignments;
  1396. bool ipAssignError = false;
  1397. for (auto i = config["ipAssignments"].begin(); i != config["ipAssignments"].end(); ++i) {
  1398. std::string addr = *i;
  1399. if (std::find(assignments.begin(), assignments.end(), addr) != assignments.end()) {
  1400. continue;
  1401. }
  1402. pqxx::result res = w.exec_params0("INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3) ON CONFLICT (network_id, member_id, address) DO NOTHING", memberId, networkId, addr);
  1403. assignments.push_back(addr);
  1404. }
  1405. if (ipAssignError) {
  1406. fprintf(stderr, "%s: ipAssignError\n", _myAddressStr.c_str());
  1407. w.abort();
  1408. _pool->unborrow(c);
  1409. c.reset();
  1410. continue;
  1411. }
  1412. w.commit();
  1413. if (_smee != NULL && isNewMember) {
  1414. pqxx::row row = w.exec_params1(
  1415. "SELECT "
  1416. " count(h.hook_id) "
  1417. "FROM "
  1418. " ztc_hook h "
  1419. " INNER JOIN ztc_org o ON o.org_id = h.org_id "
  1420. " INNER JOIN ztc_network n ON n.owner_id = o.owner_id "
  1421. " WHERE "
  1422. "n.id = $1 ",
  1423. networkId);
  1424. int64_t hookCount = row[0].as<int64_t>();
  1425. if (hookCount > 0) {
  1426. notifyNewMember(networkId, memberId);
  1427. }
  1428. }
  1429. const uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  1430. const uint64_t memberidInt = OSUtils::jsonIntHex(config["id"], 0ULL);
  1431. if (nwidInt && memberidInt) {
  1432. nlohmann::json nwOrig;
  1433. nlohmann::json memOrig;
  1434. nlohmann::json memNew(config);
  1435. get(nwidInt, nwOrig, memberidInt, memOrig);
  1436. _memberChanged(memOrig, memNew, qitem.second);
  1437. }
  1438. else {
  1439. 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);
  1440. }
  1441. }
  1442. catch (std::exception& e) {
  1443. fprintf(stderr, "%s ERROR: Error updating member %s-%s: %s\n", _myAddressStr.c_str(), networkId.c_str(), memberId.c_str(), e.what());
  1444. }
  1445. }
  1446. else if (objtype == "network") {
  1447. try {
  1448. // fprintf(stderr, "%s: commitThread: network\n", _myAddressStr.c_str());
  1449. pqxx::work w(*c->c);
  1450. std::string id = config["id"];
  1451. std::string remoteTraceTarget = "";
  1452. if (! config["remoteTraceTarget"].is_null()) {
  1453. remoteTraceTarget = config["remoteTraceTarget"];
  1454. }
  1455. std::string rulesSource = "";
  1456. if (config["rulesSource"].is_string()) {
  1457. rulesSource = config["rulesSource"];
  1458. }
  1459. // This ugly query exists because when we want to mirror networks to/from
  1460. // another data store (e.g. FileDB or LFDB) it is possible to get a network
  1461. // that doesn't exist in Central's database. This does an upsert and sets
  1462. // the owner_id to the "first" global admin in the user DB if the record
  1463. // did not previously exist. If the record already exists owner_id is left
  1464. // unchanged, so owner_id should be left out of the update clause.
  1465. pqxx::result res = w.exec_params0(
  1466. "INSERT INTO ztc_network (id, creation_time, owner_id, controller_id, capabilities, enable_broadcast, "
  1467. "last_modified, mtu, multicast_limit, name, private, "
  1468. "remote_trace_level, remote_trace_target, rules, rules_source, "
  1469. "tags, v4_assign_mode, v6_assign_mode, sso_enabled) VALUES ("
  1470. "$1, TO_TIMESTAMP($5::double precision/1000), "
  1471. "(SELECT user_id AS owner_id FROM ztc_global_permissions WHERE authorize = true AND del = true AND modify = true AND read = true LIMIT 1),"
  1472. "$2, $3, $4, TO_TIMESTAMP($5::double precision/1000), "
  1473. "$6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) "
  1474. "ON CONFLICT (id) DO UPDATE set controller_id = EXCLUDED.controller_id, "
  1475. "capabilities = EXCLUDED.capabilities, enable_broadcast = EXCLUDED.enable_broadcast, "
  1476. "last_modified = EXCLUDED.last_modified, mtu = EXCLUDED.mtu, "
  1477. "multicast_limit = EXCLUDED.multicast_limit, name = EXCLUDED.name, "
  1478. "private = EXCLUDED.private, remote_trace_level = EXCLUDED.remote_trace_level, "
  1479. "remote_trace_target = EXCLUDED.remote_trace_target, rules = EXCLUDED.rules, "
  1480. "rules_source = EXCLUDED.rules_source, tags = EXCLUDED.tags, "
  1481. "v4_assign_mode = EXCLUDED.v4_assign_mode, v6_assign_mode = EXCLUDED.v6_assign_mode, "
  1482. "sso_enabled = EXCLUDED.sso_enabled",
  1483. id,
  1484. _myAddressStr,
  1485. OSUtils::jsonDump(config["capabilities"], -1),
  1486. (bool)config["enableBroadcast"],
  1487. OSUtils::now(),
  1488. (int)config["mtu"],
  1489. (int)config["multicastLimit"],
  1490. OSUtils::jsonString(config["name"], ""),
  1491. (bool)config["private"],
  1492. (int)config["remoteTraceLevel"],
  1493. remoteTraceTarget,
  1494. OSUtils::jsonDump(config["rules"], -1),
  1495. rulesSource,
  1496. OSUtils::jsonDump(config["tags"], -1),
  1497. OSUtils::jsonDump(config["v4AssignMode"], -1),
  1498. OSUtils::jsonDump(config["v6AssignMode"], -1),
  1499. OSUtils::jsonBool(config["ssoEnabled"], false));
  1500. res = w.exec_params0("DELETE FROM ztc_network_assignment_pool WHERE network_id = $1", 0);
  1501. auto pool = config["ipAssignmentPools"];
  1502. bool err = false;
  1503. for (auto i = pool.begin(); i != pool.end(); ++i) {
  1504. std::string start = (*i)["ipRangeStart"];
  1505. std::string end = (*i)["ipRangeEnd"];
  1506. res = w.exec_params0(
  1507. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  1508. "VALUES ($1, $2, $3)",
  1509. id,
  1510. start,
  1511. end);
  1512. }
  1513. res = w.exec_params0("DELETE FROM ztc_network_route WHERE network_id = $1", id);
  1514. auto routes = config["routes"];
  1515. err = false;
  1516. for (auto i = routes.begin(); i != routes.end(); ++i) {
  1517. std::string t = (*i)["target"];
  1518. std::vector<std::string> target;
  1519. std::istringstream f(t);
  1520. std::string s;
  1521. while (std::getline(f, s, '/')) {
  1522. target.push_back(s);
  1523. }
  1524. if (target.empty() || target.size() != 2) {
  1525. continue;
  1526. }
  1527. std::string targetAddr = target[0];
  1528. std::string targetBits = target[1];
  1529. std::string via = "NULL";
  1530. if (! (*i)["via"].is_null()) {
  1531. via = (*i)["via"];
  1532. }
  1533. res = w.exec_params0("INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)", id, targetAddr, targetBits, (via == "NULL" ? NULL : via.c_str()));
  1534. }
  1535. if (err) {
  1536. fprintf(stderr, "%s: route add error\n", _myAddressStr.c_str());
  1537. w.abort();
  1538. _pool->unborrow(c);
  1539. continue;
  1540. }
  1541. auto dns = config["dns"];
  1542. std::string domain = dns["domain"];
  1543. std::stringstream servers;
  1544. servers << "{";
  1545. for (auto j = dns["servers"].begin(); j < dns["servers"].end(); ++j) {
  1546. servers << *j;
  1547. if ((j + 1) != dns["servers"].end()) {
  1548. servers << ",";
  1549. }
  1550. }
  1551. servers << "}";
  1552. std::string s = servers.str();
  1553. 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", id, domain, s);
  1554. w.commit();
  1555. const uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  1556. if (nwidInt) {
  1557. nlohmann::json nwOrig;
  1558. nlohmann::json nwNew(config);
  1559. get(nwidInt, nwOrig);
  1560. _networkChanged(nwOrig, nwNew, qitem.second);
  1561. }
  1562. else {
  1563. fprintf(stderr, "%s: Can't notify network changed: %llu\n", _myAddressStr.c_str(), (unsigned long long)nwidInt);
  1564. }
  1565. }
  1566. catch (std::exception& e) {
  1567. fprintf(stderr, "%s ERROR: Error updating network: %s\n", _myAddressStr.c_str(), e.what());
  1568. }
  1569. if (_redisMemberStatus) {
  1570. try {
  1571. std::string id = config["id"];
  1572. std::string controllerId = _myAddressStr.c_str();
  1573. std::string key = "networks:{" + controllerId + "}";
  1574. if (_rc->clusterMode) {
  1575. _cluster->sadd(key, id);
  1576. }
  1577. else {
  1578. _redis->sadd(key, id);
  1579. }
  1580. }
  1581. catch (sw::redis::Error& e) {
  1582. fprintf(stderr, "ERROR: Error adding network to Redis: %s\n", e.what());
  1583. }
  1584. }
  1585. }
  1586. else if (objtype == "_delete_network") {
  1587. // fprintf(stderr, "%s: commitThread: delete network\n", _myAddressStr.c_str());
  1588. try {
  1589. pqxx::work w(*c->c);
  1590. std::string networkId = config["nwid"];
  1591. pqxx::result res = w.exec_params0("UPDATE ztc_network SET deleted = true WHERE id = $1", networkId);
  1592. w.commit();
  1593. }
  1594. catch (std::exception& e) {
  1595. fprintf(stderr, "%s ERROR: Error deleting network: %s\n", _myAddressStr.c_str(), e.what());
  1596. }
  1597. if (_redisMemberStatus) {
  1598. try {
  1599. std::string id = config["id"];
  1600. std::string controllerId = _myAddressStr.c_str();
  1601. std::string key = "networks:{" + controllerId + "}";
  1602. if (_rc->clusterMode) {
  1603. _cluster->srem(key, id);
  1604. _cluster->del("network-nodes-online:{" + controllerId + "}:" + id);
  1605. }
  1606. else {
  1607. _redis->srem(key, id);
  1608. _redis->del("network-nodes-online:{" + controllerId + "}:" + id);
  1609. }
  1610. }
  1611. catch (sw::redis::Error& e) {
  1612. fprintf(stderr, "ERROR: Error adding network to Redis: %s\n", e.what());
  1613. }
  1614. }
  1615. }
  1616. else if (objtype == "_delete_member") {
  1617. // fprintf(stderr, "%s commitThread: delete member\n", _myAddressStr.c_str());
  1618. try {
  1619. pqxx::work w(*c->c);
  1620. std::string memberId = config["id"];
  1621. std::string networkId = config["nwid"];
  1622. pqxx::result res = w.exec_params0("UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2", memberId, networkId);
  1623. w.commit();
  1624. }
  1625. catch (std::exception& e) {
  1626. fprintf(stderr, "%s ERROR: Error deleting member: %s\n", _myAddressStr.c_str(), e.what());
  1627. }
  1628. if (_redisMemberStatus) {
  1629. try {
  1630. std::string memberId = config["id"];
  1631. std::string networkId = config["nwid"];
  1632. std::string controllerId = _myAddressStr.c_str();
  1633. std::string key = "network-nodes-all:{" + controllerId + "}:" + networkId;
  1634. if (_rc->clusterMode) {
  1635. _cluster->srem(key, memberId);
  1636. _cluster->del("member:{" + controllerId + "}:" + networkId + ":" + memberId);
  1637. }
  1638. else {
  1639. _redis->srem(key, memberId);
  1640. _redis->del("member:{" + controllerId + "}:" + networkId + ":" + memberId);
  1641. }
  1642. }
  1643. catch (sw::redis::Error& e) {
  1644. fprintf(stderr, "ERROR: Error deleting member from Redis: %s\n", e.what());
  1645. }
  1646. }
  1647. }
  1648. else {
  1649. fprintf(stderr, "%s ERROR: unknown objtype\n", _myAddressStr.c_str());
  1650. }
  1651. }
  1652. catch (std::exception& e) {
  1653. fprintf(stderr, "%s ERROR: Error getting objtype: %s\n", _myAddressStr.c_str(), e.what());
  1654. }
  1655. _pool->unborrow(c);
  1656. c.reset();
  1657. }
  1658. fprintf(stderr, "%s commitThread finished\n", _myAddressStr.c_str());
  1659. }
  1660. void PostgreSQL::notifyNewMember(const std::string& networkID, const std::string& memberID)
  1661. {
  1662. smeeclient::smee_client_notify_network_joined(_smee, networkID.c_str(), memberID.c_str());
  1663. }
  1664. void PostgreSQL::onlineNotificationThread()
  1665. {
  1666. waitForReady();
  1667. if (_redisMemberStatus) {
  1668. onlineNotification_Redis();
  1669. }
  1670. else {
  1671. onlineNotification_Postgres();
  1672. }
  1673. }
  1674. /**
  1675. * ONLY UNCOMMENT FOR TEMPORARY DB MAINTENANCE
  1676. *
  1677. * This define temporarily turns off writing to the member status table
  1678. * so it can be reindexed when the indexes get too large.
  1679. */
  1680. // #define DISABLE_MEMBER_STATUS 1
  1681. void PostgreSQL::onlineNotification_Postgres()
  1682. {
  1683. _connected = 1;
  1684. nlohmann::json jtmp1, jtmp2;
  1685. while (_run == 1) {
  1686. auto c = _pool->borrow();
  1687. auto c2 = _pool->borrow();
  1688. try {
  1689. fprintf(stderr, "%s onlineNotification_Postgres\n", _myAddressStr.c_str());
  1690. std::unordered_map<std::pair<uint64_t, uint64_t>, std::pair<int64_t, InetAddress>, _PairHasher> lastOnline;
  1691. {
  1692. std::lock_guard<std::mutex> l(_lastOnline_l);
  1693. lastOnline.swap(_lastOnline);
  1694. }
  1695. #ifndef DISABLE_MEMBER_STATUS
  1696. pqxx::work w(*c->c);
  1697. pqxx::work w2(*c2->c);
  1698. fprintf(stderr, "online notification tick\n");
  1699. bool firstRun = true;
  1700. bool memberAdded = false;
  1701. int updateCount = 0;
  1702. pqxx::pipeline pipe(w);
  1703. for (auto i = lastOnline.begin(); i != lastOnline.end(); ++i) {
  1704. updateCount += 1;
  1705. uint64_t nwid_i = i->first.first;
  1706. char nwidTmp[64];
  1707. char memTmp[64];
  1708. char ipTmp[64];
  1709. OSUtils::ztsnprintf(nwidTmp, sizeof(nwidTmp), "%.16llx", nwid_i);
  1710. OSUtils::ztsnprintf(memTmp, sizeof(memTmp), "%.10llx", i->first.second);
  1711. if (! get(nwid_i, jtmp1, i->first.second, jtmp2)) {
  1712. continue; // skip non existent networks/members
  1713. }
  1714. std::string networkId(nwidTmp);
  1715. std::string memberId(memTmp);
  1716. try {
  1717. pqxx::row r = w2.exec_params1("SELECT id, network_id FROM ztc_member WHERE network_id = $1 AND id = $2", networkId, memberId);
  1718. }
  1719. catch (pqxx::unexpected_rows& e) {
  1720. continue;
  1721. }
  1722. int64_t ts = i->second.first;
  1723. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1724. std::string timestamp = std::to_string(ts);
  1725. std::stringstream memberUpdate;
  1726. memberUpdate << "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES "
  1727. << "('" << networkId << "', '" << memberId << "', ";
  1728. if (ipAddr.empty()) {
  1729. memberUpdate << "NULL, ";
  1730. }
  1731. else {
  1732. memberUpdate << "'" << ipAddr << "', ";
  1733. }
  1734. memberUpdate << "TO_TIMESTAMP(" << timestamp << "::double precision/1000)) "
  1735. << " ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated";
  1736. pipe.insert(memberUpdate.str());
  1737. Metrics::pgsql_node_checkin++;
  1738. }
  1739. while (! pipe.empty()) {
  1740. pipe.retrieve();
  1741. }
  1742. pipe.complete();
  1743. w.commit();
  1744. fprintf(stderr, "%s: Updated online status of %d members\n", _myAddressStr.c_str(), updateCount);
  1745. #endif
  1746. }
  1747. catch (std::exception& e) {
  1748. fprintf(stderr, "%s: error in onlinenotification thread: %s\n", _myAddressStr.c_str(), e.what());
  1749. }
  1750. _pool->unborrow(c2);
  1751. _pool->unborrow(c);
  1752. ConnectionPoolStats stats = _pool->get_stats();
  1753. fprintf(stderr, "%s pool stats: in use size: %llu, available size: %llu, total: %llu\n", _myAddressStr.c_str(), stats.borrowed_size, stats.pool_size, (stats.borrowed_size + stats.pool_size));
  1754. std::this_thread::sleep_for(std::chrono::seconds(10));
  1755. }
  1756. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  1757. if (_run == 1) {
  1758. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1759. exit(6);
  1760. }
  1761. }
  1762. void PostgreSQL::onlineNotification_Redis()
  1763. {
  1764. _connected = 1;
  1765. char buf[11] = { 0 };
  1766. std::string controllerId = std::string(_myAddress.toString(buf));
  1767. while (_run == 1) {
  1768. fprintf(stderr, "onlineNotification tick\n");
  1769. auto start = std::chrono::high_resolution_clock::now();
  1770. uint64_t count = 0;
  1771. std::unordered_map<std::pair<uint64_t, uint64_t>, std::pair<int64_t, InetAddress>, _PairHasher> lastOnline;
  1772. {
  1773. std::lock_guard<std::mutex> l(_lastOnline_l);
  1774. lastOnline.swap(_lastOnline);
  1775. }
  1776. try {
  1777. if (! lastOnline.empty()) {
  1778. if (_rc->clusterMode) {
  1779. auto tx = _cluster->transaction(controllerId, true, false);
  1780. count = _doRedisUpdate(tx, controllerId, lastOnline);
  1781. }
  1782. else {
  1783. auto tx = _redis->transaction(true, false);
  1784. count = _doRedisUpdate(tx, controllerId, lastOnline);
  1785. }
  1786. }
  1787. }
  1788. catch (sw::redis::Error& e) {
  1789. fprintf(stderr, "Error in online notification thread (redis): %s\n", e.what());
  1790. }
  1791. auto end = std::chrono::high_resolution_clock::now();
  1792. auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  1793. auto total = dur.count();
  1794. fprintf(stderr, "onlineNotification ran in %llu ms\n", total);
  1795. std::this_thread::sleep_for(std::chrono::seconds(5));
  1796. }
  1797. }
  1798. uint64_t PostgreSQL::_doRedisUpdate(sw::redis::Transaction& tx, std::string& controllerId, std::unordered_map<std::pair<uint64_t, uint64_t>, std::pair<int64_t, InetAddress>, _PairHasher>& lastOnline)
  1799. {
  1800. nlohmann::json jtmp1, jtmp2;
  1801. uint64_t count = 0;
  1802. for (auto i = lastOnline.begin(); i != lastOnline.end(); ++i) {
  1803. uint64_t nwid_i = i->first.first;
  1804. uint64_t memberid_i = i->first.second;
  1805. char nwidTmp[64];
  1806. char memTmp[64];
  1807. char ipTmp[64];
  1808. OSUtils::ztsnprintf(nwidTmp, sizeof(nwidTmp), "%.16llx", nwid_i);
  1809. OSUtils::ztsnprintf(memTmp, sizeof(memTmp), "%.10llx", memberid_i);
  1810. if (! get(nwid_i, jtmp1, memberid_i, jtmp2)) {
  1811. continue; // skip non existent members/networks
  1812. }
  1813. std::string networkId(nwidTmp);
  1814. std::string memberId(memTmp);
  1815. int64_t ts = i->second.first;
  1816. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1817. std::string timestamp = std::to_string(ts);
  1818. std::unordered_map<std::string, std::string> record = { { "id", memberId }, { "address", ipAddr }, { "last_updated", std::to_string(ts) } };
  1819. tx.zadd("nodes-online:{" + controllerId + "}", memberId, ts)
  1820. .zadd("nodes-online2:{" + controllerId + "}", networkId + "-" + memberId, ts)
  1821. .zadd("network-nodes-online:{" + controllerId + "}:" + networkId, memberId, ts)
  1822. .zadd("active-networks:{" + controllerId + "}", networkId, ts)
  1823. .sadd("network-nodes-all:{" + controllerId + "}:" + networkId, memberId)
  1824. .hmset("member:{" + controllerId + "}:" + networkId + ":" + memberId, record.begin(), record.end());
  1825. ++count;
  1826. Metrics::redis_node_checkin++;
  1827. }
  1828. // expire records from all-nodes and network-nodes member list
  1829. uint64_t expireOld = OSUtils::now() - 300000;
  1830. tx.zremrangebyscore("nodes-online:{" + controllerId + "}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1831. tx.zremrangebyscore("nodes-online2:{" + controllerId + "}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1832. tx.zremrangebyscore("active-networks:{" + controllerId + "}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1833. {
  1834. std::shared_lock<std::shared_mutex> l(_networks_l);
  1835. for (const auto& it : _networks) {
  1836. uint64_t nwid_i = it.first;
  1837. char nwidTmp[64];
  1838. OSUtils::ztsnprintf(nwidTmp, sizeof(nwidTmp), "%.16llx", nwid_i);
  1839. tx.zremrangebyscore("network-nodes-online:{" + controllerId + "}:" + nwidTmp, sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1840. }
  1841. }
  1842. tx.exec();
  1843. fprintf(stderr, "%s: Updated online status of %d members\n", _myAddressStr.c_str(), count);
  1844. return count;
  1845. }
  1846. #endif // ZT_CONTROLLER_USE_LIBPQ