CentralDB.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  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 "CentralDB.hpp"
  14. #ifdef ZT_CONTROLLER_USE_LIBPQ
  15. #include "../../node/Constants.hpp"
  16. #include "../../node/SHA512.hpp"
  17. #include "../../version.h"
  18. #include "BigTableStatusWriter.hpp"
  19. #include "ControllerConfig.hpp"
  20. #include "CtlUtil.hpp"
  21. #include "EmbeddedNetworkController.hpp"
  22. #include "PostgresStatusWriter.hpp"
  23. #include "PubSubListener.hpp"
  24. #include "Redis.hpp"
  25. #include "RedisListener.hpp"
  26. #include "RedisStatusWriter.hpp"
  27. #include "opentelemetry/trace/provider.h"
  28. #include <chrono>
  29. #include <climits>
  30. #include <iomanip>
  31. #include <libpq-fe.h>
  32. #include <optional>
  33. #include <pqxx/pqxx>
  34. #include <rustybits.h>
  35. #include <sstream>
  36. // #define REDIS_TRACE 1
  37. using json = nlohmann::json;
  38. using namespace ZeroTier;
  39. using Attrs = std::vector<std::pair<std::string, std::string> >;
  40. using Item = std::pair<std::string, Attrs>;
  41. using ItemStream = std::vector<Item>;
  42. CentralDB::CentralDB(
  43. const Identity& myId,
  44. const char* connString,
  45. int listenPort,
  46. CentralDB::ListenerMode listenMode,
  47. CentralDB::StatusWriterMode statusMode,
  48. const ControllerConfig* cc)
  49. : DB()
  50. , _listenerMode(listenMode)
  51. , _statusWriterMode(statusMode)
  52. , _cc(cc)
  53. , _pool()
  54. , _myId(myId)
  55. , _myAddress(myId.address())
  56. , _ready(0)
  57. , _connected(1)
  58. , _run(1)
  59. , _waitNoticePrinted(false)
  60. , _listenPort(listenPort)
  61. , _redis(NULL)
  62. , _cluster(NULL)
  63. , _redisMemberStatus(false)
  64. , _smee(NULL)
  65. {
  66. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  67. auto tracer = provider->GetTracer("CentralDB");
  68. auto span = tracer->StartSpan("CentralDB::CentralDB");
  69. auto scope = tracer->WithActiveSpan(span);
  70. rustybits::init_async_runtime();
  71. char myAddress[64];
  72. _myAddressStr = myId.address().toString(myAddress);
  73. _connString = std::string(connString);
  74. auto f = std::make_shared<PostgresConnFactory>(_connString);
  75. _pool =
  76. std::make_shared<ConnectionPool<PostgresConnection> >(15, 5, std::static_pointer_cast<ConnectionFactory>(f));
  77. memset(_ssoPsk, 0, sizeof(_ssoPsk));
  78. char* const ssoPskHex = getenv("ZT_SSO_PSK");
  79. #ifdef ZT_TRACE
  80. fprintf(stderr, "ZT_SSO_PSK: %s\n", ssoPskHex);
  81. #endif
  82. if (ssoPskHex) {
  83. // SECURITY: note that ssoPskHex will always be null-terminated if libc actually
  84. // returns something non-NULL. If the hex encodes something shorter than 48 bytes,
  85. // it will be padded at the end with zeroes. If longer, it'll be truncated.
  86. Utils::unhex(ssoPskHex, _ssoPsk, sizeof(_ssoPsk));
  87. }
  88. const char* redisMemberStatus = getenv("ZT_REDIS_MEMBER_STATUS");
  89. if (redisMemberStatus && (strcmp(redisMemberStatus, "true") == 0)) {
  90. _redisMemberStatus = true;
  91. fprintf(stderr, "Using redis for member status\n");
  92. }
  93. if ((listenMode == LISTENER_MODE_REDIS || statusMode == STATUS_WRITER_MODE_REDIS) && _cc->redisConfig != NULL) {
  94. auto innerspan = tracer->StartSpan("CentralDB::CentralDB::configureRedis");
  95. auto innerscope = tracer->WithActiveSpan(innerspan);
  96. sw::redis::ConnectionOptions opts;
  97. sw::redis::ConnectionPoolOptions poolOpts;
  98. opts.host = _cc->redisConfig->hostname;
  99. opts.port = _cc->redisConfig->port;
  100. opts.password = _cc->redisConfig->password;
  101. opts.db = 0;
  102. opts.keep_alive = true;
  103. opts.connect_timeout = std::chrono::seconds(3);
  104. poolOpts.size = 25;
  105. poolOpts.wait_timeout = std::chrono::seconds(5);
  106. poolOpts.connection_lifetime = std::chrono::minutes(3);
  107. poolOpts.connection_idle_time = std::chrono::minutes(1);
  108. if (_cc->redisConfig->clusterMode) {
  109. innerspan->SetAttribute("cluster_mode", "true");
  110. fprintf(stderr, "Using Redis in Cluster Mode\n");
  111. _cluster = std::make_shared<sw::redis::RedisCluster>(opts, poolOpts);
  112. }
  113. else {
  114. innerspan->SetAttribute("cluster_mode", "false");
  115. fprintf(stderr, "Using Redis in Standalone Mode\n");
  116. _redis = std::make_shared<sw::redis::Redis>(opts, poolOpts);
  117. }
  118. }
  119. _readyLock.lock();
  120. fprintf(
  121. stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S,
  122. ::_timestr(), (unsigned long long)_myAddress.toInt());
  123. _waitNoticePrinted = true;
  124. initializeNetworks();
  125. initializeMembers();
  126. _heartbeatThread = std::thread(&CentralDB::heartbeat, this);
  127. switch (listenMode) {
  128. case LISTENER_MODE_REDIS:
  129. if (_cc->redisConfig != NULL) {
  130. if (_cc->redisConfig->clusterMode) {
  131. _membersDbWatcher = std::make_shared<RedisMemberListener>(_myAddressStr, _cluster, this);
  132. _networksDbWatcher = std::make_shared<RedisNetworkListener>(_myAddressStr, _cluster, this);
  133. }
  134. else {
  135. _membersDbWatcher = std::make_shared<RedisMemberListener>(_myAddressStr, _redis, this);
  136. _networksDbWatcher = std::make_shared<RedisNetworkListener>(_myAddressStr, _redis, this);
  137. }
  138. }
  139. else {
  140. throw std::runtime_error("CentralDB: Redis listener mode selected but no Redis configuration provided");
  141. }
  142. case LISTENER_MODE_PUBSUB:
  143. if (cc->pubSubConfig != NULL) {
  144. _membersDbWatcher =
  145. std::make_shared<PubSubMemberListener>(_myAddressStr, cc->pubSubConfig->project_id, this);
  146. _networksDbWatcher =
  147. std::make_shared<PubSubNetworkListener>(_myAddressStr, cc->pubSubConfig->project_id, this);
  148. }
  149. else {
  150. throw std::runtime_error(
  151. "CentralDB: PubSub listener mode selected but no PubSub configuration provided");
  152. }
  153. break;
  154. case LISTENER_MODE_PGSQL:
  155. default:
  156. _membersDbWatcher = std::make_shared<PostgresMemberListener>(this, _pool, "member_" + _myAddressStr, 5);
  157. _networksDbWatcher = std::make_shared<PostgresNetworkListener>(this, _pool, "network_" + _myAddressStr, 5);
  158. break;
  159. }
  160. switch (statusMode) {
  161. case STATUS_WRITER_MODE_REDIS:
  162. if (_cc->redisConfig != NULL) {
  163. if (_cc->redisConfig->clusterMode) {
  164. _statusWriter = std::make_shared<RedisStatusWriter>(_cluster, _myAddressStr);
  165. }
  166. else {
  167. _statusWriter = std::make_shared<RedisStatusWriter>(_redis, _myAddressStr);
  168. }
  169. }
  170. else {
  171. throw std::runtime_error("CentralDB: Redis status mode selected but no Redis configuration provided");
  172. }
  173. break;
  174. case STATUS_WRITER_MODE_BIGTABLE:
  175. _statusWriter = std::make_shared<BigTableStatusWriter>(
  176. cc->bigTableConfig->project_id, cc->bigTableConfig->instance_id, cc->bigTableConfig->table_id);
  177. break;
  178. case STATUS_WRITER_MODE_PGSQL:
  179. default:
  180. _statusWriter = std::make_shared<PostgresStatusWriter>(_pool);
  181. break;
  182. }
  183. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  184. _commitThread[i] = std::thread(&CentralDB::commitThread, this);
  185. }
  186. _onlineNotificationThread = std::thread(&CentralDB::onlineNotificationThread, this);
  187. configureSmee();
  188. }
  189. CentralDB::~CentralDB()
  190. {
  191. if (_smee != NULL) {
  192. rustybits::smee_client_delete(_smee);
  193. _smee = NULL;
  194. }
  195. rustybits::shutdown_async_runtime();
  196. _run = 0;
  197. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  198. _heartbeatThread.join();
  199. _commitQueue.stop();
  200. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  201. _commitThread[i].join();
  202. }
  203. _onlineNotificationThread.join();
  204. }
  205. void CentralDB::configureSmee()
  206. {
  207. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  208. auto tracer = provider->GetTracer("CentralDB");
  209. auto span = tracer->StartSpan("CentralDB::configureSmee");
  210. auto scope = tracer->WithActiveSpan(span);
  211. const char* TEMPORAL_SCHEME = "ZT_TEMPORAL_SCHEME";
  212. const char* TEMPORAL_HOST = "ZT_TEMPORAL_HOST";
  213. const char* TEMPORAL_PORT = "ZT_TEMPORAL_PORT";
  214. const char* TEMPORAL_NAMESPACE = "ZT_TEMPORAL_NAMESPACE";
  215. const char* SMEE_TASK_QUEUE = "ZT_SMEE_TASK_QUEUE";
  216. const char* scheme = getenv(TEMPORAL_SCHEME);
  217. if (scheme == NULL) {
  218. scheme = "http";
  219. }
  220. const char* host = getenv(TEMPORAL_HOST);
  221. const char* port = getenv(TEMPORAL_PORT);
  222. const char* ns = getenv(TEMPORAL_NAMESPACE);
  223. const char* task_queue = getenv(SMEE_TASK_QUEUE);
  224. if (scheme != NULL && host != NULL && port != NULL && ns != NULL && task_queue != NULL) {
  225. fprintf(stderr, "creating smee client\n");
  226. std::string hostPort =
  227. std::string(scheme) + std::string("://") + std::string(host) + std::string(":") + std::string(port);
  228. this->_smee = rustybits::smee_client_new(hostPort.c_str(), ns, task_queue);
  229. }
  230. else {
  231. fprintf(stderr, "Smee client not configured\n");
  232. }
  233. }
  234. bool CentralDB::waitForReady()
  235. {
  236. while (_ready < 2) {
  237. _readyLock.lock();
  238. _readyLock.unlock();
  239. }
  240. return true;
  241. }
  242. bool CentralDB::isReady()
  243. {
  244. return ((_ready == 2) && (_connected));
  245. }
  246. bool CentralDB::save(nlohmann::json& record, bool notifyListeners)
  247. {
  248. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  249. auto tracer = provider->GetTracer("CentralDB");
  250. auto span = tracer->StartSpan("CentralDB::save");
  251. auto scope = tracer->WithActiveSpan(span);
  252. bool modified = false;
  253. try {
  254. if (! record.is_object()) {
  255. fprintf(stderr, "record is not an object?!?\n");
  256. return false;
  257. }
  258. const std::string objtype = record["objtype"];
  259. if (objtype == "network") {
  260. // fprintf(stderr, "network save\n");
  261. const uint64_t nwid = OSUtils::jsonIntHex(record["id"], 0ULL);
  262. if (nwid) {
  263. nlohmann::json old;
  264. get(nwid, old);
  265. if ((! old.is_object()) || (! _compareRecords(old, record))) {
  266. record["revision"] = OSUtils::jsonInt(record["revision"], 0ULL) + 1ULL;
  267. _commitQueue.post(std::pair<nlohmann::json, bool>(record, notifyListeners));
  268. modified = true;
  269. }
  270. }
  271. }
  272. else if (objtype == "member") {
  273. std::string networkId = record["nwid"];
  274. std::string memberId = record["id"];
  275. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"], 0ULL);
  276. const uint64_t id = OSUtils::jsonIntHex(record["id"], 0ULL);
  277. // fprintf(stderr, "member save %s-%s\n", networkId.c_str(), memberId.c_str());
  278. if ((id) && (nwid)) {
  279. nlohmann::json network, old;
  280. get(nwid, network, id, old);
  281. if ((! old.is_object()) || (! _compareRecords(old, record))) {
  282. // fprintf(stderr, "commit queue post\n");
  283. record["revision"] = OSUtils::jsonInt(record["revision"], 0ULL) + 1ULL;
  284. _commitQueue.post(std::pair<nlohmann::json, bool>(record, notifyListeners));
  285. modified = true;
  286. }
  287. else {
  288. // fprintf(stderr, "no change\n");
  289. }
  290. }
  291. }
  292. else {
  293. fprintf(stderr, "uhh waaat\n");
  294. }
  295. }
  296. catch (std::exception& e) {
  297. fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what());
  298. }
  299. catch (...) {
  300. fprintf(stderr, "Unknown error on PostgreSQL::save\n");
  301. }
  302. return modified;
  303. }
  304. void CentralDB::eraseNetwork(const uint64_t networkId)
  305. {
  306. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  307. auto tracer = provider->GetTracer("CentralDB");
  308. auto span = tracer->StartSpan("CentralDB::eraseNetwork");
  309. auto scope = tracer->WithActiveSpan(span);
  310. char networkIdStr[17];
  311. span->SetAttribute("network_id", Utils::hex(networkId, networkIdStr));
  312. fprintf(stderr, "PostgreSQL::eraseNetwork\n");
  313. char tmp2[24];
  314. waitForReady();
  315. Utils::hex(networkId, tmp2);
  316. std::pair<nlohmann::json, bool> tmp;
  317. tmp.first["id"] = tmp2;
  318. tmp.first["objtype"] = "_delete_network";
  319. tmp.second = true;
  320. _commitQueue.post(tmp);
  321. nlohmann::json nullJson;
  322. _networkChanged(tmp.first, nullJson, true);
  323. }
  324. void CentralDB::eraseMember(const uint64_t networkId, const uint64_t memberId)
  325. {
  326. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  327. auto tracer = provider->GetTracer("CentralDB");
  328. auto span = tracer->StartSpan("CentralDB::eraseMember");
  329. auto scope = tracer->WithActiveSpan(span);
  330. char networkIdStr[17];
  331. char memberIdStr[11];
  332. span->SetAttribute("network_id", Utils::hex(networkId, networkIdStr));
  333. span->SetAttribute("member_id", Utils::hex10(memberId, memberIdStr));
  334. fprintf(stderr, "PostgreSQL::eraseMember\n");
  335. char tmp2[24];
  336. waitForReady();
  337. std::pair<nlohmann::json, bool> tmp, nw;
  338. Utils::hex(networkId, tmp2);
  339. tmp.first["nwid"] = tmp2;
  340. Utils::hex(memberId, tmp2);
  341. tmp.first["id"] = tmp2;
  342. tmp.first["objtype"] = "_delete_member";
  343. tmp.second = true;
  344. _commitQueue.post(tmp);
  345. nlohmann::json nullJson;
  346. _memberChanged(tmp.first, nullJson, true);
  347. }
  348. void CentralDB::nodeIsOnline(
  349. const uint64_t networkId,
  350. const uint64_t memberId,
  351. const InetAddress& physicalAddress,
  352. const char* osArch)
  353. {
  354. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  355. auto tracer = provider->GetTracer("CentralDB");
  356. auto span = tracer->StartSpan("CentralDB::nodeIsOnline");
  357. auto scope = tracer->WithActiveSpan(span);
  358. char networkIdStr[17];
  359. char memberIdStr[11];
  360. char ipStr[INET6_ADDRSTRLEN];
  361. span->SetAttribute("network_id", Utils::hex(networkId, networkIdStr));
  362. span->SetAttribute("member_id", Utils::hex10(memberId, memberIdStr));
  363. span->SetAttribute("physical_address", physicalAddress.toString(ipStr));
  364. span->SetAttribute("os_arch", osArch);
  365. std::lock_guard<std::mutex> l(_lastOnline_l);
  366. NodeOnlineRecord& i = _lastOnline[std::pair<uint64_t, uint64_t>(networkId, memberId)];
  367. i.lastSeen = OSUtils::now();
  368. if (physicalAddress) {
  369. i.physicalAddress = physicalAddress;
  370. }
  371. i.osArch = std::string(osArch);
  372. }
  373. void CentralDB::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress)
  374. {
  375. this->nodeIsOnline(networkId, memberId, physicalAddress, "unknown/unknown");
  376. }
  377. AuthInfo CentralDB::getSSOAuthInfo(const nlohmann::json& member, const std::string& redirectURL)
  378. {
  379. if (_cc->ssoEnabled) {
  380. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  381. auto tracer = provider->GetTracer("CentralDB");
  382. auto span = tracer->StartSpan("CentralDB::getSSOAuthInfo");
  383. auto scope = tracer->WithActiveSpan(span);
  384. Metrics::db_get_sso_info++;
  385. // NONCE is just a random character string. no semantic meaning
  386. // state = HMAC SHA384 of Nonce based on shared sso key
  387. //
  388. // need nonce timeout in database? make sure it's used within X time
  389. // X is 5 minutes for now. Make configurable later?
  390. //
  391. // how do we tell when a nonce is used? if auth_expiration_time is set
  392. std::string networkId = member["nwid"];
  393. std::string memberId = member["id"];
  394. char authenticationURL[4096] = { 0 };
  395. AuthInfo info;
  396. info.enabled = true;
  397. // if (memberId == "a10dccea52" && networkId == "8056c2e21c24673d") {
  398. // fprintf(stderr, "invalid authinfo for grant's machine\n");
  399. // info.version=1;
  400. // return info;
  401. // }
  402. // fprintf(stderr, "PostgreSQL::updateMemberOnLoad: %s-%s\n", networkId.c_str(), memberId.c_str());
  403. std::shared_ptr<PostgresConnection> c;
  404. try {
  405. c = _pool->borrow();
  406. pqxx::work w(*c->c);
  407. char nonceBytes[16] = { 0 };
  408. std::string nonce = "";
  409. // check if the member exists first.
  410. pqxx::row count = w.exec_params1(
  411. "SELECT count(id) FROM ztc_member WHERE id = $1 AND network_id = $2 AND deleted = false", memberId,
  412. networkId);
  413. if (count[0].as<int>() == 1) {
  414. // get active nonce, if exists.
  415. pqxx::result r = w.exec_params(
  416. "SELECT nonce FROM ztc_sso_expiry "
  417. "WHERE network_id = $1 AND member_id = $2 "
  418. "AND ((NOW() AT TIME ZONE 'UTC') <= authentication_expiry_time) AND ((NOW() AT TIME ZONE 'UTC') <= "
  419. "nonce_expiration)",
  420. networkId, memberId);
  421. if (r.size() == 0) {
  422. // no active nonce.
  423. // find an unused nonce, if one exists.
  424. pqxx::result r = w.exec_params(
  425. "SELECT nonce FROM ztc_sso_expiry "
  426. "WHERE network_id = $1 AND member_id = $2 "
  427. "AND authentication_expiry_time IS NULL AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  428. networkId, memberId);
  429. if (r.size() == 1) {
  430. // we have an existing nonce. Use it
  431. nonce = r.at(0)[0].as<std::string>();
  432. Utils::unhex(nonce.c_str(), nonceBytes, sizeof(nonceBytes));
  433. }
  434. else if (r.empty()) {
  435. // create a nonce
  436. Utils::getSecureRandom(nonceBytes, 16);
  437. char nonceBuf[64] = { 0 };
  438. Utils::hex(nonceBytes, sizeof(nonceBytes), nonceBuf);
  439. nonce = std::string(nonceBuf);
  440. pqxx::result ir = w.exec_params0(
  441. "INSERT INTO ztc_sso_expiry "
  442. "(nonce, nonce_expiration, network_id, member_id) VALUES "
  443. "($1, TO_TIMESTAMP($2::double precision/1000), $3, $4)",
  444. nonce, OSUtils::now() + 300000, networkId, memberId);
  445. w.commit();
  446. }
  447. else {
  448. // > 1 ?!? Thats an error!
  449. fprintf(stderr, "> 1 unused nonce!\n");
  450. exit(6);
  451. }
  452. }
  453. else if (r.size() == 1) {
  454. nonce = r.at(0)[0].as<std::string>();
  455. Utils::unhex(nonce.c_str(), nonceBytes, sizeof(nonceBytes));
  456. }
  457. else {
  458. // more than 1 nonce in use? Uhhh...
  459. fprintf(stderr, "> 1 nonce in use for network member?!?\n");
  460. exit(7);
  461. }
  462. r = w.exec_params(
  463. "SELECT oc.client_id, oc.authorization_endpoint, oc.issuer, oc.provider, oc.sso_impl_version "
  464. "FROM ztc_network AS n "
  465. "INNER JOIN ztc_org o "
  466. " ON o.owner_id = n.owner_id "
  467. "LEFT OUTER JOIN ztc_network_oidc_config noc "
  468. " ON noc.network_id = n.id "
  469. "LEFT OUTER JOIN ztc_oidc_config oc "
  470. " ON noc.client_id = oc.client_id AND oc.org_id = o.org_id "
  471. "WHERE n.id = $1 AND n.sso_enabled = true",
  472. networkId);
  473. std::string client_id = "";
  474. std::string authorization_endpoint = "";
  475. std::string issuer = "";
  476. std::string provider = "";
  477. uint64_t sso_version = 0;
  478. if (r.size() == 1) {
  479. client_id = r.at(0)[0].as<std::optional<std::string> >().value_or("");
  480. authorization_endpoint = r.at(0)[1].as<std::optional<std::string> >().value_or("");
  481. issuer = r.at(0)[2].as<std::optional<std::string> >().value_or("");
  482. provider = r.at(0)[3].as<std::optional<std::string> >().value_or("");
  483. sso_version = r.at(0)[4].as<std::optional<uint64_t> >().value_or(1);
  484. }
  485. else if (r.size() > 1) {
  486. fprintf(
  487. stderr, "ERROR: More than one auth endpoint for an organization?!?!? NetworkID: %s\n",
  488. networkId.c_str());
  489. }
  490. else {
  491. fprintf(stderr, "No client or auth endpoint?!?\n");
  492. }
  493. info.version = sso_version;
  494. // no catch all else because we don't actually care if no records exist here. just continue as normal.
  495. if ((! client_id.empty()) && (! authorization_endpoint.empty())) {
  496. uint8_t state[48];
  497. HMACSHA384(_ssoPsk, nonceBytes, sizeof(nonceBytes), state);
  498. char state_hex[256];
  499. Utils::hex(state, 48, state_hex);
  500. if (info.version == 0) {
  501. char url[2048] = { 0 };
  502. OSUtils::ztsnprintf(
  503. url, sizeof(authenticationURL),
  504. "%s?response_type=id_token&response_mode=form_post&scope=openid+email+profile&redirect_uri="
  505. "%s&nonce=%s&state=%s&client_id=%s",
  506. authorization_endpoint.c_str(), url_encode(redirectURL).c_str(), nonce.c_str(), state_hex,
  507. client_id.c_str());
  508. info.authenticationURL = std::string(url);
  509. }
  510. else if (info.version == 1) {
  511. info.ssoClientID = client_id;
  512. info.issuerURL = issuer;
  513. info.ssoProvider = provider;
  514. info.ssoNonce = nonce;
  515. info.ssoState = std::string(state_hex) + "_" + networkId;
  516. info.centralAuthURL = redirectURL;
  517. #ifdef ZT_DEBUG
  518. fprintf(
  519. stderr,
  520. "ssoClientID: %s\nissuerURL: %s\nssoNonce: %s\nssoState: %s\ncentralAuthURL: %s\nprovider: "
  521. "%s\n",
  522. info.ssoClientID.c_str(), info.issuerURL.c_str(), info.ssoNonce.c_str(),
  523. info.ssoState.c_str(), info.centralAuthURL.c_str(), provider.c_str());
  524. #endif
  525. }
  526. }
  527. else {
  528. fprintf(
  529. stderr, "client_id: %s\nauthorization_endpoint: %s\n", client_id.c_str(),
  530. authorization_endpoint.c_str());
  531. }
  532. }
  533. _pool->unborrow(c);
  534. }
  535. catch (std::exception& e) {
  536. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  537. fprintf(stderr, "ERROR: Error updating member on load for network %s: %s\n", networkId.c_str(), e.what());
  538. }
  539. return info; // std::string(authenticationURL);
  540. }
  541. return AuthInfo();
  542. }
  543. void CentralDB::initializeNetworks()
  544. {
  545. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  546. auto tracer = provider->GetTracer("CentralDB");
  547. auto span = tracer->StartSpan("CentralDB::initializeNetworks");
  548. auto scope = tracer->WithActiveSpan(span);
  549. fprintf(stderr, "Initializing networks...\n");
  550. try {
  551. char qbuf[2048];
  552. sprintf(
  553. qbuf,
  554. "SELECT id, name, configuration , (EXTRACT(EPOCH FROM creation_time AT TIME ZONE 'UTC')*1000)::bigint, "
  555. "(EXTRACT(EPOCH FROM last_modified AT TIME ZONE 'UTC')*1000)::bigint, revision "
  556. "FROM networks_ctl WHERE controller_id = '%s'",
  557. _myAddressStr.c_str());
  558. auto c = _pool->borrow();
  559. pqxx::work w(*c->c);
  560. fprintf(stderr, "Load networks from psql...\n");
  561. auto stream = pqxx::stream_from::query(w, qbuf);
  562. std::tuple<
  563. std::string // network ID
  564. ,
  565. std::optional<std::string> // name
  566. ,
  567. std::string // configuration
  568. ,
  569. std::optional<uint64_t> // creation_time
  570. ,
  571. std::optional<uint64_t> // last_modified
  572. ,
  573. std::optional<uint64_t> // revision
  574. >
  575. row;
  576. uint64_t count = 0;
  577. uint64_t total = 0;
  578. while (stream >> row) {
  579. auto start = std::chrono::high_resolution_clock::now();
  580. json empty;
  581. json config;
  582. initNetwork(config);
  583. std::string nwid = std::get<0>(row);
  584. std::string name = std::get<1>(row).value_or("");
  585. json cfgtmp = json::parse(std::get<2>(row));
  586. std::optional<uint64_t> created_at = std::get<3>(row);
  587. std::optional<uint64_t> last_modified = std::get<4>(row);
  588. std::optional<uint64_t> revision = std::get<5>(row);
  589. config["id"] = nwid;
  590. config["name"] = name;
  591. config["creationTime"] = created_at.value_or(0);
  592. config["lastModified"] = last_modified.value_or(0);
  593. config["revision"] = revision.value_or(0);
  594. config["capabilities"] = cfgtmp["capabilities"].is_array() ? cfgtmp["capabilities"] : json::array();
  595. config["enableBroadcast"] =
  596. cfgtmp["enableBroadcast"].is_boolean() ? cfgtmp["enableBroadcast"].get<bool>() : false;
  597. config["mtu"] = cfgtmp["mtu"].is_number() ? cfgtmp["mtu"].get<int32_t>() : 2800;
  598. config["multicastLimit"] =
  599. cfgtmp["multicastLimit"].is_number() ? cfgtmp["multicastLimit"].get<int32_t>() : 64;
  600. config["private"] = cfgtmp["private"].is_boolean() ? cfgtmp["private"].get<bool>() : true;
  601. config["remoteTraceLevel"] =
  602. cfgtmp["remoteTraceLevel"].is_number() ? cfgtmp["remoteTraceLevel"].get<int32_t>() : 0;
  603. config["remoteTraceTarget"] =
  604. cfgtmp["remoteTraceTarget"].is_string() ? cfgtmp["remoteTraceTarget"].get<std::string>() : "";
  605. config["revision"] = revision.value_or(0);
  606. config["rules"] = cfgtmp["rules"].is_array() ? cfgtmp["rules"] : json::array();
  607. config["tags"] = cfgtmp["tags"].is_array() ? cfgtmp["tags"] : json::array();
  608. if (cfgtmp["v4AssignMode"].is_object()) {
  609. config["v4AssignMode"] = cfgtmp["v4AssignMode"];
  610. }
  611. else {
  612. config["v4AssignMode"] = json::object();
  613. config["v4AssignMode"]["zt"] = true;
  614. }
  615. if (cfgtmp["v6AssignMode"].is_object()) {
  616. config["v6AssignMode"] = cfgtmp["v6AssignMode"];
  617. }
  618. else {
  619. config["v6AssignMode"] = json::object();
  620. config["v6AssignMode"]["zt"] = true;
  621. config["v6AssignMode"]["6plane"] = true;
  622. config["v6AssignMode"]["rfc4193"] = false;
  623. }
  624. config["ssoEnabled"] = cfgtmp["ssoEnabled"].is_boolean() ? cfgtmp["ssoEnabled"].get<bool>() : false;
  625. config["objtype"] = "network";
  626. config["routes"] = cfgtmp["routes"].is_array() ? cfgtmp["routes"] : json::array();
  627. config["clientId"] = cfgtmp["clientId"].is_string() ? cfgtmp["clientId"].get<std::string>() : "";
  628. config["authorizationEndpoint"] = cfgtmp["authorizationEndpoint"].is_string()
  629. ? cfgtmp["authorizationEndpoint"].get<std::string>()
  630. : nullptr;
  631. config["provider"] = cfgtmp["ssoProvider"].is_string() ? cfgtmp["ssoProvider"].get<std::string>() : "";
  632. if (! cfgtmp["dns"].is_object()) {
  633. cfgtmp["dns"] = json::object();
  634. cfgtmp["dns"]["domain"] = "";
  635. cfgtmp["dns"]["servers"] = json::array();
  636. }
  637. else {
  638. config["dns"] = cfgtmp["dns"];
  639. }
  640. config["ipAssignmentPools"] =
  641. cfgtmp["ipAssignmentPools"].is_array() ? cfgtmp["ipAssignmentPools"] : json::array();
  642. Metrics::network_count++;
  643. _networkChanged(empty, config, false);
  644. auto end = std::chrono::high_resolution_clock::now();
  645. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
  646. ;
  647. total += dur.count();
  648. ++count;
  649. if (count > 0 && count % 10000 == 0) {
  650. fprintf(stderr, "Averaging %lu us per network\n", (total / count));
  651. }
  652. }
  653. w.commit();
  654. _pool->unborrow(c);
  655. fprintf(stderr, "done.\n");
  656. if (++this->_ready == 2) {
  657. if (_waitNoticePrinted) {
  658. fprintf(
  659. stderr, "[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S, _timestr(),
  660. (unsigned long long)_myAddress.toInt());
  661. }
  662. _readyLock.unlock();
  663. }
  664. fprintf(stderr, "network init done\n");
  665. }
  666. catch (std::exception& e) {
  667. fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
  668. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  669. std::this_thread::sleep_for(std::chrono::milliseconds(5000));
  670. exit(-1);
  671. }
  672. }
  673. void CentralDB::initializeMembers()
  674. {
  675. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  676. auto tracer = provider->GetTracer("CentralDB");
  677. auto span = tracer->StartSpan("CentralDB::initializeMembers");
  678. auto scope = tracer->WithActiveSpan(span);
  679. std::string memberId;
  680. std::string networkId;
  681. try {
  682. std::unordered_map<std::string, std::string> networkMembers;
  683. fprintf(stderr, "Initializing Members...\n");
  684. std::string setKeyBase = "network-nodes-all:{" + _myAddressStr + "}:";
  685. if (_redisMemberStatus) {
  686. fprintf(stderr, "Initialize Redis for members...\n");
  687. std::unique_lock<std::shared_mutex> l(_networks_l);
  688. std::unordered_set<std::string> deletes;
  689. for (auto it : _networks) {
  690. uint64_t nwid_i = it.first;
  691. char nwidTmp[64] = { 0 };
  692. OSUtils::ztsnprintf(nwidTmp, sizeof(nwidTmp), "%.16llx", nwid_i);
  693. std::string nwid(nwidTmp);
  694. std::string key = setKeyBase + nwid;
  695. deletes.insert(key);
  696. }
  697. if (! deletes.empty()) {
  698. try {
  699. if (_cc->redisConfig->clusterMode) {
  700. auto tx = _cluster->transaction(_myAddressStr, true, false);
  701. for (std::string k : deletes) {
  702. tx.del(k);
  703. }
  704. tx.exec();
  705. }
  706. else {
  707. auto tx = _redis->transaction(true, false);
  708. for (std::string k : deletes) {
  709. tx.del(k);
  710. }
  711. tx.exec();
  712. }
  713. }
  714. catch (sw::redis::Error& e) {
  715. // ignore
  716. }
  717. }
  718. }
  719. char qbuf[2048];
  720. sprintf(
  721. qbuf,
  722. "SELECT nm.device_id, nm.network_id, nm.authorized, nm.active_bridge, nm.ip_assignments, "
  723. "nm.no_auto_assign_ips, "
  724. "nm.sso_exempt, (EXTRACT(EPOCH FROM nm.authentication_expiry_time AT TIME ZONE 'UTC')*1000)::bigint, "
  725. "(EXTRACT(EPOCH FROM nm.creation_time AT TIME ZONE 'UTC')*1000)::bigint, nm.identity, "
  726. "(EXTRACT(EPOCH FROM nm.last_authorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  727. "(EXTRACT(EPOCH FROM nm.last_deauthorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  728. "nm.remote_trace_level, nm.remote_trace_target, nm.revision, nm.capabilities, nm.tags "
  729. "FROM network_memberships_ctl nm "
  730. "INNER JOIN networks_ctl n "
  731. " ON nm.network_id = n.id "
  732. "WHERE n.controller_id = '%s'",
  733. _myAddressStr.c_str());
  734. auto c = _pool->borrow();
  735. pqxx::work w(*c->c);
  736. fprintf(stderr, "Load members from psql...\n");
  737. auto stream = pqxx::stream_from::query(w, qbuf);
  738. std::tuple<
  739. std::string // device ID
  740. ,
  741. std::string // network ID
  742. ,
  743. bool // authorized
  744. ,
  745. std::optional<bool> // active_bridge
  746. ,
  747. std::optional<std::string> // ip_assignments
  748. ,
  749. std::optional<bool> // no_auto_assign_ips
  750. ,
  751. std::optional<bool> // sso_exempt
  752. ,
  753. std::optional<uint64_t> // authentication_expiry_time
  754. ,
  755. std::optional<uint64_t> // creation_time
  756. ,
  757. std::optional<std::string> // identity
  758. ,
  759. std::optional<uint64_t> // last_authorized_time
  760. ,
  761. std::optional<uint64_t> // last_deauthorized_time
  762. ,
  763. std::optional<int32_t> // remote_trace_level
  764. ,
  765. std::optional<std::string> // remote_trace_target
  766. ,
  767. std::optional<uint64_t> // revision
  768. ,
  769. std::optional<std::string> // capabilities
  770. ,
  771. std::optional<std::string> // tags
  772. >
  773. row;
  774. auto tmp = std::chrono::high_resolution_clock::now();
  775. uint64_t count = 0;
  776. uint64_t total = 0;
  777. while (stream >> row) {
  778. auto start = std::chrono::high_resolution_clock::now();
  779. json empty;
  780. json config;
  781. initMember(config);
  782. memberId = std::get<0>(row);
  783. networkId = std::get<1>(row);
  784. bool authorized = std::get<2>(row);
  785. std::optional<bool> active_bridge = std::get<3>(row);
  786. std::string ip_assignments = std::get<4>(row).value_or("");
  787. std::optional<bool> no_auto_assign_ips = std::get<5>(row);
  788. std::optional<bool> sso_exempt = std::get<6>(row);
  789. std::optional<uint64_t> authentication_expiry_time = std::get<7>(row);
  790. std::optional<uint64_t> creation_time = std::get<8>(row);
  791. std::optional<std::string> identity = std::get<9>(row);
  792. std::optional<uint64_t> last_authorized_time = std::get<10>(row);
  793. std::optional<uint64_t> last_deauthorized_time = std::get<11>(row);
  794. std::optional<int32_t> remote_trace_level = std::get<12>(row);
  795. std::optional<std::string> remote_trace_target = std::get<13>(row);
  796. std::optional<uint64_t> revision = std::get<14>(row);
  797. std::optional<std::string> capabilities = std::get<15>(row);
  798. std::optional<std::string> tags = std::get<16>(row);
  799. networkMembers.insert(std::pair<std::string, std::string>(setKeyBase + networkId, memberId));
  800. config["objtype"] = "member";
  801. config["id"] = memberId;
  802. config["address"] = identity.value_or("");
  803. config["nwid"] = networkId;
  804. config["authorized"] = authorized;
  805. config["activeBridge"] = active_bridge.value_or(false);
  806. config["ipAssignments"] = json::array();
  807. if (ip_assignments != "{}") {
  808. std::string tmp = ip_assignments.substr(1, ip_assignments.length() - 2);
  809. std::vector<std::string> addrs = split(tmp, ',');
  810. for (auto it = addrs.begin(); it != addrs.end(); ++it) {
  811. config["ipAssignments"].push_back(*it);
  812. }
  813. }
  814. config["capabilities"] = json::parse(capabilities.value_or("[]"));
  815. config["creationTime"] = creation_time.value_or(0);
  816. config["lastAuthorizedTime"] = last_authorized_time.value_or(0);
  817. config["lastDeauthorizedTime"] = last_deauthorized_time.value_or(0);
  818. config["noAutoAssignIPs"] = no_auto_assign_ips.value_or(false);
  819. config["remoteTraceLevel"] = remote_trace_level.value_or(0);
  820. config["remoteTraceTarget"] = remote_trace_target.value_or(nullptr);
  821. config["revision"] = revision.value_or(0);
  822. config["ssoExempt"] = sso_exempt.value_or(false);
  823. config["authenticationExpiryTime"] = authentication_expiry_time.value_or(0);
  824. config["tags"] = json::parse(tags.value_or("[]"));
  825. config["ipAssignments"] = json::array();
  826. Metrics::member_count++;
  827. _memberChanged(empty, config, false);
  828. memberId = "";
  829. networkId = "";
  830. auto end = std::chrono::high_resolution_clock::now();
  831. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
  832. total += dur.count();
  833. ++count;
  834. if (count > 0 && count % 10000 == 0) {
  835. fprintf(stderr, "Averaging %llu us per member\n", (total / count));
  836. }
  837. }
  838. if (count > 0) {
  839. fprintf(stderr, "Took %llu us per member to load\n", (total / count));
  840. }
  841. stream.complete();
  842. w.commit();
  843. _pool->unborrow(c);
  844. fprintf(stderr, "done.\n");
  845. if (_listenerMode == LISTENER_MODE_REDIS)
  846. if (! networkMembers.empty()) {
  847. if (_redisMemberStatus) {
  848. fprintf(stderr, "Load member data into redis...\n");
  849. if (_cc->redisConfig->clusterMode) {
  850. auto tx = _cluster->transaction(_myAddressStr, true, false);
  851. uint64_t count = 0;
  852. for (auto it : networkMembers) {
  853. tx.sadd(it.first, it.second);
  854. if (++count % 30000 == 0) {
  855. tx.exec();
  856. tx = _cluster->transaction(_myAddressStr, true, false);
  857. }
  858. }
  859. tx.exec();
  860. }
  861. else {
  862. auto tx = _redis->transaction(true, false);
  863. uint64_t count = 0;
  864. for (auto it : networkMembers) {
  865. tx.sadd(it.first, it.second);
  866. if (++count % 30000 == 0) {
  867. tx.exec();
  868. tx = _redis->transaction(true, false);
  869. }
  870. }
  871. tx.exec();
  872. }
  873. fprintf(stderr, "done.\n");
  874. }
  875. }
  876. fprintf(stderr, "Done loading members...\n");
  877. if (++this->_ready == 2) {
  878. if (_waitNoticePrinted) {
  879. fprintf(
  880. stderr, "[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S, _timestr(),
  881. (unsigned long long)_myAddress.toInt());
  882. }
  883. _readyLock.unlock();
  884. }
  885. }
  886. catch (sw::redis::Error& e) {
  887. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  888. fprintf(stderr, "ERROR: Error initializing members (redis): %s\n", e.what());
  889. exit(-1);
  890. }
  891. catch (std::exception& e) {
  892. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  893. fprintf(stderr, "ERROR: Error initializing member: %s-%s %s\n", networkId.c_str(), memberId.c_str(), e.what());
  894. exit(-1);
  895. }
  896. }
  897. void CentralDB::heartbeat()
  898. {
  899. char publicId[1024];
  900. char hostnameTmp[1024];
  901. _myId.toString(false, publicId);
  902. if (gethostname(hostnameTmp, sizeof(hostnameTmp)) != 0) {
  903. hostnameTmp[0] = (char)0;
  904. }
  905. else {
  906. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  907. if ((hostnameTmp[i] == '.') || (hostnameTmp[i] == 0)) {
  908. hostnameTmp[i] = (char)0;
  909. break;
  910. }
  911. }
  912. }
  913. const char* controllerId = _myAddressStr.c_str();
  914. const char* publicIdentity = publicId;
  915. const char* hostname = hostnameTmp;
  916. while (_run == 1) {
  917. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  918. auto tracer = provider->GetTracer("CentralDB");
  919. auto span = tracer->StartSpan("CentralDB::heartbeat");
  920. auto scope = tracer->WithActiveSpan(span);
  921. // fprintf(stderr, "%s: heartbeat\n", controllerId);
  922. auto c = _pool->borrow();
  923. int64_t ts = OSUtils::now();
  924. if (c->c) {
  925. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  926. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  927. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  928. std::string version = major + "." + minor + "." + rev;
  929. std::string versionStr = "v" + version;
  930. try {
  931. pqxx::work w { *c->c };
  932. w.exec_params0(
  933. "INSERT INTO controllers_ctl (id, hostname, last_heartbeat, public_identity, version) VALUES "
  934. "($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5) "
  935. "ON CONFLICT (id) DO UPDATE SET hostname = EXCLUDED.hostname, last_heartbeat = "
  936. "EXCLUDED.last_heartbeat, "
  937. "public_identity = EXCLUDED.public_identity, version = EXCLUDED.version",
  938. controllerId, hostname, ts, publicIdentity, versionStr);
  939. w.commit();
  940. }
  941. catch (std::exception& e) {
  942. fprintf(stderr, "%s: Heartbeat update failed: %s\n", controllerId, e.what());
  943. span->End();
  944. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  945. continue;
  946. }
  947. }
  948. _pool->unborrow(c);
  949. try {
  950. if (_listenerMode == LISTENER_MODE_REDIS && _redisMemberStatus) {
  951. if (_cc->redisConfig->clusterMode) {
  952. _cluster->zadd("controllers", "controllerId", ts);
  953. }
  954. else {
  955. _redis->zadd("controllers", "controllerId", ts);
  956. }
  957. }
  958. }
  959. catch (sw::redis::Error& e) {
  960. fprintf(stderr, "ERROR: Redis error in heartbeat thread: %s\n", e.what());
  961. }
  962. span->End();
  963. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  964. }
  965. fprintf(stderr, "Exited heartbeat thread\n");
  966. }
  967. void CentralDB::commitThread()
  968. {
  969. fprintf(stderr, "%s: commitThread start\n", _myAddressStr.c_str());
  970. std::pair<nlohmann::json, bool> qitem;
  971. while (_commitQueue.get(qitem) & (_run == 1)) {
  972. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  973. auto tracer = provider->GetTracer("CentralDB");
  974. auto span = tracer->StartSpan("CentralDB::commitThread");
  975. auto scope = tracer->WithActiveSpan(span);
  976. // fprintf(stderr, "commitThread tick\n");
  977. if (! qitem.first.is_object()) {
  978. fprintf(stderr, "not an object\n");
  979. continue;
  980. }
  981. std::shared_ptr<PostgresConnection> c;
  982. try {
  983. c = _pool->borrow();
  984. }
  985. catch (std::exception& e) {
  986. fprintf(stderr, "ERROR: %s\n", e.what());
  987. continue;
  988. }
  989. if (! c) {
  990. fprintf(stderr, "Error getting database connection\n");
  991. continue;
  992. }
  993. Metrics::pgsql_commit_ticks++;
  994. try {
  995. nlohmann::json& config = (qitem.first);
  996. const std::string objtype = config["objtype"];
  997. if (objtype == "member") {
  998. auto mspan = tracer->StartSpan("CentralDB::commitThread::member");
  999. auto mscope = tracer->WithActiveSpan(mspan);
  1000. // fprintf(stderr, "%s: commitThread: member\n", _myAddressStr.c_str());
  1001. std::string memberId;
  1002. std::string networkId;
  1003. try {
  1004. pqxx::work w(*c->c);
  1005. memberId = config["id"];
  1006. networkId = config["nwid"];
  1007. std::string target = "NULL";
  1008. if (! config["remoteTraceTarget"].is_null()) {
  1009. target = config["remoteTraceTarget"];
  1010. }
  1011. pqxx::row nwrow = w.exec_params1("SELECT COUNT(id) FROM networks_ctl WHERE id = $1", networkId);
  1012. int nwcount = nwrow[0].as<int>();
  1013. if (nwcount != 1) {
  1014. fprintf(stderr, "network %s does not exist. skipping member upsert\n", networkId.c_str());
  1015. w.abort();
  1016. _pool->unborrow(c);
  1017. continue;
  1018. }
  1019. pqxx::row mrow = w.exec_params1(
  1020. "SELECT COUNT(device_id) FROM network_memberships_ctl WHERE device_id = $1 AND network_id = $2",
  1021. memberId, networkId);
  1022. int membercount = mrow[0].as<int>();
  1023. bool isNewMember = (membercount == 0);
  1024. pqxx::result res = w.exec_params0(
  1025. "INSERT INTO network_memberships_ctl (device_id, network_id, authorized, active_bridge, "
  1026. "ip_assignments, "
  1027. "no_auto_assign_ips, sso_exempt, authentication_expiry_time, capabilities, creation_time, "
  1028. "identity, last_authorized_time, last_deauthorized_time, "
  1029. "remote_trace_level, remote_trace_target, revision, tags, version_major, version_minor, "
  1030. "version_revision, version_protocol) "
  1031. "VALUES ($1, $2, $3, $4, $5, $6, $7, TO_TIMESTAMP($8::double precision/1000), $9, "
  1032. "TO_TIMESTAMP($10::double precision/1000), $11, TO_TIMESTAMP($12::double precision/1000), "
  1033. "TO_TIMESTAMP($13::double precision/1000), $14, $15, $16, $17, $18, $19, $20, $21) "
  1034. "ON CONFLICT (device_id, network_id) DO UPDATE SET "
  1035. "authorized = EXCLUDED.authorized, active_bridge = EXCLUDED.active_bridge, "
  1036. "ip_assignments = EXCLUDED.ip_assignments, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  1037. "sso_exempt = EXCLUDED.sso_exempt, authentication_expiry_time = "
  1038. "EXCLUDED.authentication_expiry_time, "
  1039. "capabilities = EXCLUDED.capabilities, creation_time = EXCLUDED.creation_time, "
  1040. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  1041. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, "
  1042. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = "
  1043. "EXCLUDED.remote_trace_target, "
  1044. "revision = EXCLUDED.revision, tags = EXCLUDED.tags, version_major = EXCLUDED.version_major, "
  1045. "version_minor = EXCLUDED.version_minor, version_revision = EXCLUDED.version_revision, "
  1046. "version_protocol = EXCLUDED.version_protocol",
  1047. memberId, networkId, (bool)config["authorized"], (bool)config["activeBridge"],
  1048. config["ipAssignments"].get<std::vector<std::string> >(), (bool)config["noAutoAssignIps"],
  1049. (bool)config["ssoExempt"], (uint64_t)config["authenticationExpiryTime"],
  1050. OSUtils::jsonDump(config["capabilities"], -1), (uint64_t)config["creationTime"],
  1051. OSUtils::jsonString(config["identity"], ""), (uint64_t)config["lastAuthorizedTime"],
  1052. (uint64_t)config["lastDeauthorizedTime"], (int)config["remoteTraceLevel"], target,
  1053. (uint64_t)config["revision"], OSUtils::jsonDump(config["tags"], -1), (int)config["vMajor"],
  1054. (int)config["vMinor"], (int)config["vRev"], (int)config["vProto"]);
  1055. w.commit();
  1056. if (_smee != NULL && isNewMember) {
  1057. // TODO: Smee Notifications for New Members
  1058. // pqxx::row row = w.exec_params1(
  1059. // "SELECT "
  1060. // " count(h.hook_id) "
  1061. // "FROM "
  1062. // " ztc_hook h "
  1063. // " INNER JOIN ztc_org o ON o.org_id = h.org_id "
  1064. // " INNER JOIN ztc_network n ON n.owner_id = o.owner_id "
  1065. // " WHERE "
  1066. // "n.id = $1 ",
  1067. // networkId);
  1068. // int64_t hookCount = row[0].as<int64_t>();
  1069. // if (hookCount > 0) {
  1070. // notifyNewMember(networkId, memberId);
  1071. // }
  1072. }
  1073. const uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  1074. const uint64_t memberidInt = OSUtils::jsonIntHex(config["id"], 0ULL);
  1075. if (nwidInt && memberidInt) {
  1076. nlohmann::json nwOrig;
  1077. nlohmann::json memOrig;
  1078. nlohmann::json memNew(config);
  1079. get(nwidInt, nwOrig, memberidInt, memOrig);
  1080. _memberChanged(memOrig, memNew, qitem.second);
  1081. }
  1082. else {
  1083. fprintf(
  1084. stderr, "%s: Can't notify of change. Error parsing nwid or memberid: %llu-%llu\n",
  1085. _myAddressStr.c_str(), (unsigned long long)nwidInt, (unsigned long long)memberidInt);
  1086. }
  1087. }
  1088. catch (std::exception& e) {
  1089. fprintf(
  1090. stderr, "%s ERROR: Error updating member %s-%s: %s\n", _myAddressStr.c_str(), networkId.c_str(),
  1091. memberId.c_str(), e.what());
  1092. mspan->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  1093. }
  1094. }
  1095. else if (objtype == "network") {
  1096. auto nspan = tracer->StartSpan("CentralDB::commitThread::network");
  1097. auto nscope = tracer->WithActiveSpan(nspan);
  1098. try {
  1099. // fprintf(stderr, "%s: commitThread: network\n", _myAddressStr.c_str());
  1100. pqxx::work w(*c->c);
  1101. std::string id = config["id"];
  1102. pqxx::result res = w.exec_params0(
  1103. "INSERT INTO networks_ctl (id, name, configuration, controller_id, revision) "
  1104. "VALUES ($1, $2, $3, $4, $5) "
  1105. "ON CONFLICT (id) DO UPDATE SET "
  1106. "name = EXCLUDED.name, configuration = EXCLUDED.configuration, revision = EXCLUDED.revision+1",
  1107. id, OSUtils::jsonString(config["name"], ""), OSUtils::jsonDump(config, -1), _myAddressStr,
  1108. ((uint64_t)config["revision"]));
  1109. w.commit();
  1110. // res = w.exec_params0("DELETE FROM ztc_network_assignment_pool WHERE network_id = $1", 0);
  1111. // auto pool = config["ipAssignmentPools"];
  1112. // bool err = false;
  1113. // for (auto i = pool.begin(); i != pool.end(); ++i) {
  1114. // std::string start = (*i)["ipRangeStart"];
  1115. // std::string end = (*i)["ipRangeEnd"];
  1116. // res = w.exec_params0(
  1117. // "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  1118. // "VALUES ($1, $2, $3)",
  1119. // id, start, end);
  1120. // }
  1121. const uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  1122. if (nwidInt) {
  1123. nlohmann::json nwOrig;
  1124. nlohmann::json nwNew(config);
  1125. get(nwidInt, nwOrig);
  1126. _networkChanged(nwOrig, nwNew, qitem.second);
  1127. }
  1128. else {
  1129. fprintf(
  1130. stderr, "%s: Can't notify network changed: %llu\n", _myAddressStr.c_str(),
  1131. (unsigned long long)nwidInt);
  1132. }
  1133. }
  1134. catch (std::exception& e) {
  1135. nspan->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  1136. fprintf(stderr, "%s ERROR: Error updating network: %s\n", _myAddressStr.c_str(), e.what());
  1137. }
  1138. if (_listenerMode == LISTENER_MODE_REDIS && _redisMemberStatus) {
  1139. try {
  1140. std::string id = config["id"];
  1141. std::string controllerId = _myAddressStr.c_str();
  1142. std::string key = "networks:{" + controllerId + "}";
  1143. if (_cc->redisConfig->clusterMode) {
  1144. _cluster->sadd(key, id);
  1145. }
  1146. else {
  1147. _redis->sadd(key, id);
  1148. }
  1149. }
  1150. catch (sw::redis::Error& e) {
  1151. nspan->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  1152. fprintf(stderr, "ERROR: Error adding network to Redis: %s\n", e.what());
  1153. }
  1154. }
  1155. }
  1156. else if (objtype == "_delete_network") {
  1157. auto dspan = tracer->StartSpan("CentralDB::commitThread::_delete_network");
  1158. auto dscope = tracer->WithActiveSpan(dspan);
  1159. // fprintf(stderr, "%s: commitThread: delete network\n", _myAddressStr.c_str());
  1160. try {
  1161. pqxx::work w(*c->c);
  1162. std::string networkId = config["id"];
  1163. fprintf(stderr, "Deleting network %s\n", networkId.c_str());
  1164. w.exec_params0("DELETE FROM network_memberships_ctl WHERE network_id = $1", networkId);
  1165. w.exec_params0("DELETE FROM networks_ctl WHERE id = $1", networkId);
  1166. w.commit();
  1167. uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  1168. json oldConfig;
  1169. get(nwidInt, oldConfig);
  1170. json empty;
  1171. _networkChanged(oldConfig, empty, qitem.second);
  1172. }
  1173. catch (std::exception& e) {
  1174. dspan->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  1175. fprintf(stderr, "%s ERROR: Error deleting network: %s\n", _myAddressStr.c_str(), e.what());
  1176. }
  1177. if (_listenerMode == LISTENER_MODE_REDIS && _redisMemberStatus) {
  1178. try {
  1179. std::string id = config["id"];
  1180. std::string controllerId = _myAddressStr.c_str();
  1181. std::string key = "networks:{" + controllerId + "}";
  1182. if (_cc->redisConfig->clusterMode) {
  1183. _cluster->srem(key, id);
  1184. _cluster->del("network-nodes-online:{" + controllerId + "}:" + id);
  1185. }
  1186. else {
  1187. _redis->srem(key, id);
  1188. _redis->del("network-nodes-online:{" + controllerId + "}:" + id);
  1189. }
  1190. }
  1191. catch (sw::redis::Error& e) {
  1192. dspan->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  1193. fprintf(stderr, "ERROR: Error adding network to Redis: %s\n", e.what());
  1194. }
  1195. }
  1196. }
  1197. else if (objtype == "_delete_member") {
  1198. auto mspan = tracer->StartSpan("CentralDB::commitThread::_delete_member");
  1199. auto mscope = tracer->WithActiveSpan(mspan);
  1200. // fprintf(stderr, "%s commitThread: delete member\n", _myAddressStr.c_str());
  1201. try {
  1202. pqxx::work w(*c->c);
  1203. std::string memberId = config["id"];
  1204. std::string networkId = config["nwid"];
  1205. pqxx::result res = w.exec_params0(
  1206. "DELETE FROM network_memberships_ctl WHERE device_id = $1 AND network_id = $2", memberId,
  1207. networkId);
  1208. w.commit();
  1209. uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  1210. uint64_t memberidInt = OSUtils::jsonIntHex(config["id"], 0ULL);
  1211. nlohmann::json networkConfig;
  1212. nlohmann::json oldConfig;
  1213. get(nwidInt, networkConfig, memberidInt, oldConfig);
  1214. json empty;
  1215. _memberChanged(oldConfig, empty, qitem.second);
  1216. }
  1217. catch (std::exception& e) {
  1218. mspan->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  1219. fprintf(stderr, "%s ERROR: Error deleting member: %s\n", _myAddressStr.c_str(), e.what());
  1220. }
  1221. if (_listenerMode == LISTENER_MODE_REDIS && _redisMemberStatus) {
  1222. try {
  1223. std::string memberId = config["id"];
  1224. std::string networkId = config["nwid"];
  1225. std::string controllerId = _myAddressStr.c_str();
  1226. std::string key = "network-nodes-all:{" + controllerId + "}:" + networkId;
  1227. if (_cc->redisConfig->clusterMode) {
  1228. _cluster->srem(key, memberId);
  1229. _cluster->del("member:{" + controllerId + "}:" + networkId + ":" + memberId);
  1230. }
  1231. else {
  1232. _redis->srem(key, memberId);
  1233. _redis->del("member:{" + controllerId + "}:" + networkId + ":" + memberId);
  1234. }
  1235. }
  1236. catch (sw::redis::Error& e) {
  1237. mspan->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  1238. fprintf(stderr, "ERROR: Error deleting member from Redis: %s\n", e.what());
  1239. }
  1240. }
  1241. }
  1242. else {
  1243. fprintf(stderr, "%s ERROR: unknown objtype\n", _myAddressStr.c_str());
  1244. }
  1245. }
  1246. catch (std::exception& e) {
  1247. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  1248. fprintf(stderr, "%s ERROR: Error getting objtype: %s\n", _myAddressStr.c_str(), e.what());
  1249. }
  1250. _pool->unborrow(c);
  1251. c.reset();
  1252. }
  1253. fprintf(stderr, "%s commitThread finished\n", _myAddressStr.c_str());
  1254. }
  1255. void CentralDB::notifyNewMember(const std::string& networkID, const std::string& memberID)
  1256. {
  1257. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1258. auto tracer = provider->GetTracer("CentralDB");
  1259. auto span = tracer->StartSpan("CentralDB::notifyNewMember");
  1260. auto scope = tracer->WithActiveSpan(span);
  1261. rustybits::smee_client_notify_network_joined(_smee, networkID.c_str(), memberID.c_str());
  1262. }
  1263. void CentralDB::onlineNotificationThread()
  1264. {
  1265. waitForReady();
  1266. while (_run == 1) {
  1267. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1268. auto tracer = provider->GetTracer("CentralDB");
  1269. auto span = tracer->StartSpan("CentralDB::onlineNotificationThread");
  1270. auto scope = tracer->WithActiveSpan(span);
  1271. try {
  1272. std::unordered_map<std::pair<uint64_t, uint64_t>, NodeOnlineRecord, _PairHasher> lastOnline;
  1273. {
  1274. std::lock_guard<std::mutex> l(_lastOnline_l);
  1275. lastOnline.swap(_lastOnline);
  1276. }
  1277. uint64_t updateCount = 0;
  1278. auto c = _pool->borrow();
  1279. pqxx::work w(*c->c);
  1280. for (auto i = lastOnline.begin(); i != lastOnline.end(); ++i) {
  1281. updateCount += 1;
  1282. uint64_t nwid_i = i->first.first;
  1283. char nwidTmp[64];
  1284. char memTmp[64];
  1285. char ipTmp[64];
  1286. OSUtils::ztsnprintf(nwidTmp, sizeof(nwidTmp), "%.16llx", nwid_i);
  1287. OSUtils::ztsnprintf(memTmp, sizeof(memTmp), "%.10llx", i->first.second);
  1288. nlohmann::json jtmp1, jtmp2;
  1289. if (! get(nwid_i, jtmp1, i->first.second, jtmp2)) {
  1290. continue; // skip non existent networks/members
  1291. }
  1292. std::string networkId(nwidTmp);
  1293. std::string memberId(memTmp);
  1294. try {
  1295. pqxx::row r = w.exec_params1(
  1296. "SELECT device_id, network_id FROM network_memberships_ctl WHERE network_id = $1 AND device_id "
  1297. "= $2",
  1298. networkId, memberId);
  1299. }
  1300. catch (pqxx::unexpected_rows& e) {
  1301. continue;
  1302. }
  1303. int64_t ts = i->second.lastSeen;
  1304. std::string ipAddr = i->second.physicalAddress.toIpString(ipTmp);
  1305. std::string timestamp = std::to_string(ts);
  1306. std::string osArch = i->second.osArch;
  1307. std::vector<std::string> osArchSplit = split(osArch, '/');
  1308. std::string os = "unknown";
  1309. std::string arch = "unknown";
  1310. if (osArchSplit.size() == 2) {
  1311. os = osArchSplit[0];
  1312. arch = osArchSplit[1];
  1313. }
  1314. _statusWriter->updateNodeStatus(networkId, memberId, os, arch, "", i->second.physicalAddress, ts);
  1315. }
  1316. _statusWriter->writePending();
  1317. w.commit();
  1318. _pool->unborrow(c);
  1319. }
  1320. catch (std::exception& e) {
  1321. fprintf(stderr, "%s: error in onlinenotification thread: %s\n", _myAddressStr.c_str(), e.what());
  1322. }
  1323. std::this_thread::sleep_for(std::chrono::seconds(10));
  1324. }
  1325. }
  1326. #endif // ZT_CONTROLLER_USE_LIBPQ