CV1.cpp 63 KB

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