CentralDB.cpp 50 KB

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