2
0

CV2.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. /*
  2. * Copyright (c)2025 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 "CV2.hpp"
  14. #ifdef ZT_CONTROLLER_USE_LIBPQ
  15. #include "../node/Constants.hpp"
  16. #include "../node/SHA512.hpp"
  17. #include "../version.h"
  18. #include "CtlUtil.hpp"
  19. #include "EmbeddedNetworkController.hpp"
  20. #include "opentelemetry/trace/provider.h"
  21. #include <chrono>
  22. #include <climits>
  23. #include <iomanip>
  24. #include <libpq-fe.h>
  25. #include <sstream>
  26. using json = nlohmann::json;
  27. namespace {
  28. }
  29. using namespace ZeroTier;
  30. CV2::CV2(const Identity& myId, const char* path, int listenPort) : DB(), _pool(), _myId(myId), _myAddress(myId.address()), _ready(0), _connected(1), _run(1), _waitNoticePrinted(false), _listenPort(listenPort)
  31. {
  32. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  33. auto tracer = provider->GetTracer("cv2");
  34. auto span = tracer->StartSpan("cv2::CV2");
  35. auto scope = tracer->WithActiveSpan(span);
  36. fprintf(stderr, "CV2::CV2\n");
  37. char myAddress[64];
  38. _myAddressStr = myId.address().toString(myAddress);
  39. _connString = std::string(path);
  40. auto f = std::make_shared<PostgresConnFactory>(_connString);
  41. _pool = std::make_shared<ConnectionPool<PostgresConnection> >(15, 5, std::static_pointer_cast<ConnectionFactory>(f));
  42. memset(_ssoPsk, 0, sizeof(_ssoPsk));
  43. char* const ssoPskHex = getenv("ZT_SSO_PSK");
  44. #ifdef ZT_TRACE
  45. fprintf(stderr, "ZT_SSO_PSK: %s\n", ssoPskHex);
  46. #endif
  47. if (ssoPskHex) {
  48. // SECURITY: note that ssoPskHex will always be null-terminated if libc actually
  49. // returns something non-NULL. If the hex encodes something shorter than 48 bytes,
  50. // it will be padded at the end with zeroes. If longer, it'll be truncated.
  51. Utils::unhex(ssoPskHex, _ssoPsk, sizeof(_ssoPsk));
  52. }
  53. _readyLock.lock();
  54. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S, ::_timestr(), (unsigned long long)_myAddress.toInt());
  55. _waitNoticePrinted = true;
  56. initializeNetworks();
  57. initializeMembers();
  58. _heartbeatThread = std::thread(&CV2::heartbeat, this);
  59. _membersDbWatcher = std::thread(&CV2::membersDbWatcher, this);
  60. _networksDbWatcher = std::thread(&CV2::networksDbWatcher, this);
  61. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  62. _commitThread[i] = std::thread(&CV2::commitThread, this);
  63. }
  64. _onlineNotificationThread = std::thread(&CV2::onlineNotificationThread, this);
  65. }
  66. CV2::~CV2()
  67. {
  68. _run = 0;
  69. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  70. _heartbeatThread.join();
  71. _membersDbWatcher.join();
  72. _networksDbWatcher.join();
  73. _commitQueue.stop();
  74. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  75. _commitThread[i].join();
  76. }
  77. _onlineNotificationThread.join();
  78. }
  79. bool CV2::waitForReady()
  80. {
  81. while (_ready < 2) {
  82. _readyLock.lock();
  83. _readyLock.unlock();
  84. }
  85. return true;
  86. }
  87. bool CV2::isReady()
  88. {
  89. return (_ready == 2) && _connected;
  90. }
  91. bool CV2::save(nlohmann::json& record, bool notifyListeners)
  92. {
  93. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  94. auto tracer = provider->GetTracer("cv2");
  95. auto span = tracer->StartSpan("cv2::save");
  96. auto scope = tracer->WithActiveSpan(span);
  97. bool modified = false;
  98. try {
  99. if (! record.is_object()) {
  100. fprintf(stderr, "record is not an object?!?\n");
  101. return false;
  102. }
  103. const std::string objtype = record["objtype"];
  104. if (objtype == "network") {
  105. auto nspan = tracer->StartSpan("cv2::save::network");
  106. auto nscope = tracer->WithActiveSpan(nspan);
  107. // fprintf(stderr, "network save\n");
  108. const uint64_t nwid = OSUtils::jsonIntHex(record["id"], 0ULL);
  109. if (nwid) {
  110. nlohmann::json old;
  111. get(nwid, old);
  112. if ((! old.is_object()) || (! _compareRecords(old, record))) {
  113. record["revision"] = OSUtils::jsonInt(record["revision"], 0ULL) + 1ULL;
  114. _commitQueue.post(std::pair<nlohmann::json, bool>(record, notifyListeners));
  115. modified = true;
  116. }
  117. }
  118. }
  119. else if (objtype == "member") {
  120. auto mspan = tracer->StartSpan("cv2::save::member");
  121. auto mscope = tracer->WithActiveSpan(mspan);
  122. std::string networkId = record["nwid"];
  123. std::string memberId = record["id"];
  124. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"], 0ULL);
  125. const uint64_t id = OSUtils::jsonIntHex(record["id"], 0ULL);
  126. // fprintf(stderr, "member save %s-%s\n", networkId.c_str(), memberId.c_str());
  127. if ((id) && (nwid)) {
  128. nlohmann::json network, old;
  129. get(nwid, network, id, old);
  130. if ((! old.is_object()) || (! _compareRecords(old, record))) {
  131. // fprintf(stderr, "commit queue post\n");
  132. record["revision"] = OSUtils::jsonInt(record["revision"], 0ULL) + 1ULL;
  133. _commitQueue.post(std::pair<nlohmann::json, bool>(record, notifyListeners));
  134. modified = true;
  135. }
  136. else {
  137. // fprintf(stderr, "no change\n");
  138. }
  139. }
  140. }
  141. else {
  142. fprintf(stderr, "uhh waaat\n");
  143. }
  144. }
  145. catch (std::exception& e) {
  146. fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what());
  147. }
  148. catch (...) {
  149. fprintf(stderr, "Unknown error on PostgreSQL::save\n");
  150. }
  151. return modified;
  152. }
  153. void CV2::eraseNetwork(const uint64_t networkId)
  154. {
  155. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  156. auto tracer = provider->GetTracer("cv2");
  157. auto span = tracer->StartSpan("cv2::eraseNetwork");
  158. auto scope = tracer->WithActiveSpan(span);
  159. char networkIdStr[17];
  160. span->SetAttribute("network_id", Utils::hex(networkId, networkIdStr));
  161. fprintf(stderr, "PostgreSQL::eraseNetwork\n");
  162. char tmp2[24];
  163. waitForReady();
  164. Utils::hex(networkId, tmp2);
  165. std::pair<nlohmann::json, bool> tmp;
  166. tmp.first["id"] = tmp2;
  167. tmp.first["objtype"] = "_delete_network";
  168. tmp.second = true;
  169. _commitQueue.post(tmp);
  170. nlohmann::json nullJson;
  171. _networkChanged(tmp.first, nullJson, true);
  172. }
  173. void CV2::eraseMember(const uint64_t networkId, const uint64_t memberId)
  174. {
  175. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  176. auto tracer = provider->GetTracer("cv2");
  177. auto span = tracer->StartSpan("cv2::eraseMember");
  178. auto scope = tracer->WithActiveSpan(span);
  179. char networkIdStr[17];
  180. char memberIdStr[11];
  181. span->SetAttribute("network_id", Utils::hex(networkId, networkIdStr));
  182. span->SetAttribute("member_id", Utils::hex10(memberId, memberIdStr));
  183. fprintf(stderr, "PostgreSQL::eraseMember\n");
  184. char tmp2[24];
  185. waitForReady();
  186. std::pair<nlohmann::json, bool> tmp, nw;
  187. Utils::hex(networkId, tmp2);
  188. tmp.first["nwid"] = tmp2;
  189. Utils::hex(memberId, tmp2);
  190. tmp.first["id"] = tmp2;
  191. tmp.first["objtype"] = "_delete_member";
  192. tmp.second = true;
  193. _commitQueue.post(tmp);
  194. nlohmann::json nullJson;
  195. _memberChanged(tmp.first, nullJson, true);
  196. }
  197. void CV2::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress, const char* osArch)
  198. {
  199. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  200. auto tracer = provider->GetTracer("cv2");
  201. auto span = tracer->StartSpan("cv2::nodeIsOnline");
  202. auto scope = tracer->WithActiveSpan(span);
  203. char networkIdStr[17];
  204. char memberIdStr[11];
  205. char ipAddressStr[INET6_ADDRSTRLEN];
  206. span->SetAttribute("network_id", Utils::hex(networkId, networkIdStr));
  207. span->SetAttribute("member_id", Utils::hex10(memberId, memberIdStr));
  208. span->SetAttribute("physical_address", ipAddressStr);
  209. span->SetAttribute("os_arch", osArch);
  210. std::lock_guard<std::mutex> l(_lastOnline_l);
  211. NodeOnlineRecord& i = _lastOnline[std::pair<uint64_t, uint64_t>(networkId, memberId)];
  212. i.lastSeen = OSUtils::now();
  213. if (physicalAddress) {
  214. i.physicalAddress = physicalAddress;
  215. }
  216. i.osArch = std::string(osArch);
  217. }
  218. void CV2::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress)
  219. {
  220. this->nodeIsOnline(networkId, memberId, physicalAddress, "unknown/unknown");
  221. }
  222. AuthInfo CV2::getSSOAuthInfo(const nlohmann::json& member, const std::string& redirectURL)
  223. {
  224. // TODO: Redo this for CV2
  225. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  226. auto tracer = provider->GetTracer("cv2");
  227. auto span = tracer->StartSpan("cv2::getSSOAuthInfo");
  228. auto scope = tracer->WithActiveSpan(span);
  229. Metrics::db_get_sso_info++;
  230. // NONCE is just a random character string. no semantic meaning
  231. // state = HMAC SHA384 of Nonce based on shared sso key
  232. //
  233. // need nonce timeout in database? make sure it's used within X time
  234. // X is 5 minutes for now. Make configurable later?
  235. //
  236. // how do we tell when a nonce is used? if auth_expiration_time is set
  237. std::string networkId = member["nwid"];
  238. std::string memberId = member["id"];
  239. char authenticationURL[4096] = { 0 };
  240. AuthInfo info;
  241. info.enabled = true;
  242. // if (memberId == "a10dccea52" && networkId == "8056c2e21c24673d") {
  243. // fprintf(stderr, "invalid authinfo for grant's machine\n");
  244. // info.version=1;
  245. // return info;
  246. // }
  247. // fprintf(stderr, "PostgreSQL::updateMemberOnLoad: %s-%s\n", networkId.c_str(), memberId.c_str());
  248. std::shared_ptr<PostgresConnection> c;
  249. try {
  250. // c = _pool->borrow();
  251. // pqxx::work w(*c->c);
  252. // char nonceBytes[16] = {0};
  253. // std::string nonce = "";
  254. // // check if the member exists first.
  255. // pqxx::row count = w.exec_params1("SELECT count(id) FROM ztc_member WHERE id = $1 AND network_id = $2 AND deleted = false", memberId, networkId);
  256. // if (count[0].as<int>() == 1) {
  257. // // get active nonce, if exists.
  258. // pqxx::result r = w.exec_params("SELECT nonce FROM ztc_sso_expiry "
  259. // "WHERE network_id = $1 AND member_id = $2 "
  260. // "AND ((NOW() AT TIME ZONE 'UTC') <= authentication_expiry_time) AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  261. // networkId, memberId);
  262. // if (r.size() == 0) {
  263. // // no active nonce.
  264. // // find an unused nonce, if one exists.
  265. // pqxx::result r = w.exec_params("SELECT nonce FROM ztc_sso_expiry "
  266. // "WHERE network_id = $1 AND member_id = $2 "
  267. // "AND authentication_expiry_time IS NULL AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  268. // networkId, memberId);
  269. // if (r.size() == 1) {
  270. // // we have an existing nonce. Use it
  271. // nonce = r.at(0)[0].as<std::string>();
  272. // Utils::unhex(nonce.c_str(), nonceBytes, sizeof(nonceBytes));
  273. // } else if (r.empty()) {
  274. // // create a nonce
  275. // Utils::getSecureRandom(nonceBytes, 16);
  276. // char nonceBuf[64] = {0};
  277. // Utils::hex(nonceBytes, sizeof(nonceBytes), nonceBuf);
  278. // nonce = std::string(nonceBuf);
  279. // pqxx::result ir = w.exec_params0("INSERT INTO ztc_sso_expiry "
  280. // "(nonce, nonce_expiration, network_id, member_id) VALUES "
  281. // "($1, TO_TIMESTAMP($2::double precision/1000), $3, $4)",
  282. // nonce, OSUtils::now() + 300000, networkId, memberId);
  283. // w.commit();
  284. // } else {
  285. // // > 1 ?!? Thats an error!
  286. // fprintf(stderr, "> 1 unused nonce!\n");
  287. // exit(6);
  288. // }
  289. // } else if (r.size() == 1) {
  290. // nonce = r.at(0)[0].as<std::string>();
  291. // Utils::unhex(nonce.c_str(), nonceBytes, sizeof(nonceBytes));
  292. // } else {
  293. // // more than 1 nonce in use? Uhhh...
  294. // fprintf(stderr, "> 1 nonce in use for network member?!?\n");
  295. // exit(7);
  296. // }
  297. // r = w.exec_params(
  298. // "SELECT oc.client_id, oc.authorization_endpoint, oc.issuer, oc.provider, oc.sso_impl_version "
  299. // "FROM ztc_network AS n "
  300. // "INNER JOIN ztc_org o "
  301. // " ON o.owner_id = n.owner_id "
  302. // "LEFT OUTER JOIN ztc_network_oidc_config noc "
  303. // " ON noc.network_id = n.id "
  304. // "LEFT OUTER JOIN ztc_oidc_config oc "
  305. // " ON noc.client_id = oc.client_id AND oc.org_id = o.org_id "
  306. // "WHERE n.id = $1 AND n.sso_enabled = true", networkId);
  307. // std::string client_id = "";
  308. // std::string authorization_endpoint = "";
  309. // std::string issuer = "";
  310. // std::string provider = "";
  311. // uint64_t sso_version = 0;
  312. // if (r.size() == 1) {
  313. // client_id = r.at(0)[0].as<std::optional<std::string>>().value_or("");
  314. // authorization_endpoint = r.at(0)[1].as<std::optional<std::string>>().value_or("");
  315. // issuer = r.at(0)[2].as<std::optional<std::string>>().value_or("");
  316. // provider = r.at(0)[3].as<std::optional<std::string>>().value_or("");
  317. // sso_version = r.at(0)[4].as<std::optional<uint64_t>>().value_or(1);
  318. // } else if (r.size() > 1) {
  319. // fprintf(stderr, "ERROR: More than one auth endpoint for an organization?!?!? NetworkID: %s\n", networkId.c_str());
  320. // } else {
  321. // fprintf(stderr, "No client or auth endpoint?!?\n");
  322. // }
  323. // info.version = sso_version;
  324. // // no catch all else because we don't actually care if no records exist here. just continue as normal.
  325. // if ((!client_id.empty())&&(!authorization_endpoint.empty())) {
  326. // uint8_t state[48];
  327. // HMACSHA384(_ssoPsk, nonceBytes, sizeof(nonceBytes), state);
  328. // char state_hex[256];
  329. // Utils::hex(state, 48, state_hex);
  330. // if (info.version == 0) {
  331. // char url[2048] = {0};
  332. // OSUtils::ztsnprintf(url, sizeof(authenticationURL),
  333. // "%s?response_type=id_token&response_mode=form_post&scope=openid+email+profile&redirect_uri=%s&nonce=%s&state=%s&client_id=%s",
  334. // authorization_endpoint.c_str(),
  335. // url_encode(redirectURL).c_str(),
  336. // nonce.c_str(),
  337. // state_hex,
  338. // client_id.c_str());
  339. // info.authenticationURL = std::string(url);
  340. // } else if (info.version == 1) {
  341. // info.ssoClientID = client_id;
  342. // info.issuerURL = issuer;
  343. // info.ssoProvider = provider;
  344. // info.ssoNonce = nonce;
  345. // info.ssoState = std::string(state_hex) + "_" +networkId;
  346. // info.centralAuthURL = redirectURL;
  347. // #ifdef ZT_DEBUG
  348. // fprintf(
  349. // stderr,
  350. // "ssoClientID: %s\nissuerURL: %s\nssoNonce: %s\nssoState: %s\ncentralAuthURL: %s\nprovider: %s\n",
  351. // info.ssoClientID.c_str(),
  352. // info.issuerURL.c_str(),
  353. // info.ssoNonce.c_str(),
  354. // info.ssoState.c_str(),
  355. // info.centralAuthURL.c_str(),
  356. // provider.c_str());
  357. // #endif
  358. // }
  359. // } else {
  360. // fprintf(stderr, "client_id: %s\nauthorization_endpoint: %s\n", client_id.c_str(), authorization_endpoint.c_str());
  361. // }
  362. // }
  363. // _pool->unborrow(c);
  364. }
  365. catch (std::exception& e) {
  366. fprintf(stderr, "ERROR: Error updating member on load for network %s: %s\n", networkId.c_str(), e.what());
  367. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  368. }
  369. return info; // std::string(authenticationURL);
  370. }
  371. void CV2::initializeNetworks()
  372. {
  373. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  374. auto tracer = provider->GetTracer("cv2");
  375. auto span = tracer->StartSpan("cv2::initializeNetworks");
  376. auto scope = tracer->WithActiveSpan(span);
  377. fprintf(stderr, "Initializing networks...\n");
  378. try {
  379. char qbuf[2048];
  380. sprintf(
  381. qbuf,
  382. "SELECT id, name, configuration , (EXTRACT(EPOCH FROM creation_time AT TIME ZONE 'UTC')*1000)::bigint, "
  383. "(EXTRACT(EPOCH FROM last_modified AT TIME ZONE 'UTC')*1000)::bigint, revision "
  384. "FROM networks_ctl WHERE controller_id = '%s'",
  385. _myAddressStr.c_str());
  386. auto c = _pool->borrow();
  387. pqxx::work w(*c->c);
  388. fprintf(stderr, "Load networks from psql...\n");
  389. auto stream = pqxx::stream_from::query(w, qbuf);
  390. std::tuple<
  391. std::string // network ID
  392. ,
  393. std::optional<std::string> // name
  394. ,
  395. std::string // configuration
  396. ,
  397. std::optional<uint64_t> // creation_time
  398. ,
  399. std::optional<uint64_t> // last_modified
  400. ,
  401. std::optional<uint64_t> // revision
  402. >
  403. row;
  404. uint64_t count = 0;
  405. uint64_t total = 0;
  406. while (stream >> row) {
  407. auto start = std::chrono::high_resolution_clock::now();
  408. json empty;
  409. json config;
  410. initNetwork(config);
  411. std::string nwid = std::get<0>(row);
  412. std::string name = std::get<1>(row).value_or("");
  413. json cfgtmp = json::parse(std::get<2>(row));
  414. std::optional<uint64_t> created_at = std::get<3>(row);
  415. std::optional<uint64_t> last_modified = std::get<4>(row);
  416. std::optional<uint64_t> revision = std::get<5>(row);
  417. config["id"] = nwid;
  418. config["name"] = name;
  419. config["creationTime"] = created_at.value_or(0);
  420. config["lastModified"] = last_modified.value_or(0);
  421. config["revision"] = revision.value_or(0);
  422. config["capabilities"] = cfgtmp["capabilities"].is_array() ? cfgtmp["capabilities"] : json::array();
  423. config["enableBroadcast"] = cfgtmp["enableBroadcast"].is_boolean() ? cfgtmp["enableBroadcast"].get<bool>() : false;
  424. config["mtu"] = cfgtmp["mtu"].is_number() ? cfgtmp["mtu"].get<int32_t>() : 2800;
  425. config["multicastLimit"] = cfgtmp["multicastLimit"].is_number() ? cfgtmp["multicastLimit"].get<int32_t>() : 64;
  426. config["private"] = cfgtmp["private"].is_boolean() ? cfgtmp["private"].get<bool>() : true;
  427. config["remoteTraceLevel"] = cfgtmp["remoteTraceLevel"].is_number() ? cfgtmp["remoteTraceLevel"].get<int32_t>() : 0;
  428. config["remoteTraceTarget"] = cfgtmp["remoteTraceTarget"].is_string() ? cfgtmp["remoteTraceTarget"].get<std::string>() : "";
  429. config["revision"] = revision.value_or(0);
  430. config["rules"] = cfgtmp["rules"].is_array() ? cfgtmp["rules"] : json::array();
  431. config["tags"] = cfgtmp["tags"].is_array() ? cfgtmp["tags"] : json::array();
  432. if (cfgtmp["v4AssignMode"].is_object()) {
  433. config["v4AssignMode"] = cfgtmp["v4AssignMode"];
  434. }
  435. else {
  436. config["v4AssignMode"] = json::object();
  437. config["v4AssignMode"]["zt"] = true;
  438. }
  439. if (cfgtmp["v6AssignMode"].is_object()) {
  440. config["v6AssignMode"] = cfgtmp["v6AssignMode"];
  441. }
  442. else {
  443. config["v6AssignMode"] = json::object();
  444. config["v6AssignMode"]["zt"] = true;
  445. config["v6AssignMode"]["6plane"] = true;
  446. config["v6AssignMode"]["rfc4193"] = false;
  447. }
  448. config["ssoEnabled"] = cfgtmp["ssoEnabled"].is_boolean() ? cfgtmp["ssoEnabled"].get<bool>() : false;
  449. config["objtype"] = "network";
  450. config["routes"] = cfgtmp["routes"].is_array() ? cfgtmp["routes"] : json::array();
  451. config["clientId"] = cfgtmp["clientId"].is_string() ? cfgtmp["clientId"].get<std::string>() : "";
  452. config["authorizationEndpoint"] = cfgtmp["authorizationEndpoint"].is_string() ? cfgtmp["authorizationEndpoint"].get<std::string>() : nullptr;
  453. config["provider"] = cfgtmp["ssoProvider"].is_string() ? cfgtmp["ssoProvider"].get<std::string>() : "";
  454. if (! cfgtmp["dns"].is_object()) {
  455. cfgtmp["dns"] = json::object();
  456. cfgtmp["dns"]["domain"] = "";
  457. cfgtmp["dns"]["servers"] = json::array();
  458. }
  459. else {
  460. config["dns"] = cfgtmp["dns"];
  461. }
  462. config["ipAssignmentPools"] = cfgtmp["ipAssignmentPools"].is_array() ? cfgtmp["ipAssignmentPools"] : json::array();
  463. Metrics::network_count++;
  464. _networkChanged(empty, config, false);
  465. auto end = std::chrono::high_resolution_clock::now();
  466. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
  467. ;
  468. total += dur.count();
  469. ++count;
  470. if (count > 0 && count % 10000 == 0) {
  471. fprintf(stderr, "Averaging %lu us per network\n", (total / count));
  472. }
  473. }
  474. w.commit();
  475. _pool->unborrow(c);
  476. fprintf(stderr, "done.\n");
  477. if (++this->_ready == 2) {
  478. if (_waitNoticePrinted) {
  479. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S, _timestr(), (unsigned long long)_myAddress.toInt());
  480. }
  481. _readyLock.unlock();
  482. }
  483. fprintf(stderr, "network init done\n");
  484. }
  485. catch (std::exception& e) {
  486. fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
  487. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  488. std::this_thread::sleep_for(std::chrono::milliseconds(5000));
  489. exit(-1);
  490. }
  491. }
  492. void CV2::initializeMembers()
  493. {
  494. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  495. auto tracer = provider->GetTracer("cv2");
  496. auto span = tracer->StartSpan("cv2::initializeMembers");
  497. auto scope = tracer->WithActiveSpan(span);
  498. std::string memberId;
  499. std::string networkId;
  500. try {
  501. char qbuf[2048];
  502. sprintf(
  503. qbuf,
  504. "SELECT nm.device_id, nm.network_id, nm.authorized, nm.active_bridge, nm.ip_assignments, nm.no_auto_assign_ips, "
  505. "nm.sso_exempt, (EXTRACT(EPOCH FROM nm.authentication_expiry_time AT TIME ZONE 'UTC')*1000)::bigint, "
  506. "(EXTRACT(EPOCH FROM nm.creation_time AT TIME ZONE 'UTC')*1000)::bigint, nm.identity, "
  507. "(EXTRACT(EPOCH FROM nm.last_authorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  508. "(EXTRACT(EPOCH FROM nm.last_deauthorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  509. "nm.remote_trace_level, nm.remote_trace_target, nm.revision, nm.capabilities, nm.tags "
  510. "FROM network_memberships_ctl nm "
  511. "INNER JOIN networks_ctl n "
  512. " ON nm.network_id = n.id "
  513. "WHERE n.controller_id = '%s'",
  514. _myAddressStr.c_str());
  515. auto c = _pool->borrow();
  516. pqxx::work w(*c->c);
  517. fprintf(stderr, "Load members from psql...\n");
  518. auto stream = pqxx::stream_from::query(w, qbuf);
  519. std::tuple<
  520. std::string // device ID
  521. ,
  522. std::string // network ID
  523. ,
  524. bool // authorized
  525. ,
  526. std::optional<bool> // active_bridge
  527. ,
  528. std::optional<std::string> // ip_assignments
  529. ,
  530. std::optional<bool> // no_auto_assign_ips
  531. ,
  532. std::optional<bool> // sso_exempt
  533. ,
  534. std::optional<uint64_t> // authentication_expiry_time
  535. ,
  536. std::optional<uint64_t> // creation_time
  537. ,
  538. std::optional<std::string> // identity
  539. ,
  540. std::optional<uint64_t> // last_authorized_time
  541. ,
  542. std::optional<uint64_t> // last_deauthorized_time
  543. ,
  544. std::optional<int32_t> // remote_trace_level
  545. ,
  546. std::optional<std::string> // remote_trace_target
  547. ,
  548. std::optional<uint64_t> // revision
  549. ,
  550. std::optional<std::string> // capabilities
  551. ,
  552. std::optional<std::string> // tags
  553. >
  554. row;
  555. uint64_t count = 0;
  556. uint64_t total = 0;
  557. while (stream >> row) {
  558. auto start = std::chrono::high_resolution_clock::now();
  559. json empty;
  560. json config;
  561. initMember(config);
  562. memberId = std::get<0>(row);
  563. networkId = std::get<1>(row);
  564. bool authorized = std::get<2>(row);
  565. std::optional<bool> active_bridge = std::get<3>(row);
  566. std::string ip_assignments = std::get<4>(row).value_or("");
  567. std::optional<bool> no_auto_assign_ips = std::get<5>(row);
  568. std::optional<bool> sso_exempt = std::get<6>(row);
  569. std::optional<uint64_t> authentication_expiry_time = std::get<7>(row);
  570. std::optional<uint64_t> creation_time = std::get<8>(row);
  571. std::optional<std::string> identity = std::get<9>(row);
  572. std::optional<uint64_t> last_authorized_time = std::get<10>(row);
  573. std::optional<uint64_t> last_deauthorized_time = std::get<11>(row);
  574. std::optional<int32_t> remote_trace_level = std::get<12>(row);
  575. std::optional<std::string> remote_trace_target = std::get<13>(row);
  576. std::optional<uint64_t> revision = std::get<14>(row);
  577. std::optional<std::string> capabilities = std::get<15>(row);
  578. std::optional<std::string> tags = std::get<16>(row);
  579. config["objtype"] = "member";
  580. config["id"] = memberId;
  581. config["address"] = identity.value_or("");
  582. config["nwid"] = networkId;
  583. config["authorized"] = authorized;
  584. config["activeBridge"] = active_bridge.value_or(false);
  585. config["ipAssignments"] = json::array();
  586. if (ip_assignments != "{}") {
  587. std::string tmp = ip_assignments.substr(1, ip_assignments.length() - 2);
  588. std::vector<std::string> addrs = split(tmp, ',');
  589. for (auto it = addrs.begin(); it != addrs.end(); ++it) {
  590. config["ipAssignments"].push_back(*it);
  591. }
  592. }
  593. config["capabilities"] = json::parse(capabilities.value_or("[]"));
  594. config["creationTime"] = creation_time.value_or(0);
  595. config["lastAuthorizedTime"] = last_authorized_time.value_or(0);
  596. config["lastDeauthorizedTime"] = last_deauthorized_time.value_or(0);
  597. config["noAutoAssignIPs"] = no_auto_assign_ips.value_or(false);
  598. config["remoteTraceLevel"] = remote_trace_level.value_or(0);
  599. config["remoteTraceTarget"] = remote_trace_target.value_or(nullptr);
  600. config["revision"] = revision.value_or(0);
  601. config["ssoExempt"] = sso_exempt.value_or(false);
  602. config["authenticationExpiryTime"] = authentication_expiry_time.value_or(0);
  603. config["tags"] = json::parse(tags.value_or("[]"));
  604. Metrics::member_count++;
  605. _memberChanged(empty, config, false);
  606. memberId = "";
  607. networkId = "";
  608. auto end = std::chrono::high_resolution_clock::now();
  609. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
  610. total += dur.count();
  611. ++count;
  612. if (count > 0 && count % 10000 == 0) {
  613. fprintf(stderr, "Averaging %lu us per member\n", (total / count));
  614. }
  615. }
  616. if (count > 0) {
  617. fprintf(stderr, "Took %lu us per member to load\n", (total / count));
  618. }
  619. stream.complete();
  620. w.commit();
  621. _pool->unborrow(c);
  622. fprintf(stderr, "done.\n");
  623. if (++this->_ready == 2) {
  624. if (_waitNoticePrinted) {
  625. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S, _timestr(), (unsigned long long)_myAddress.toInt());
  626. }
  627. _readyLock.unlock();
  628. }
  629. fprintf(stderr, "member init done\n");
  630. }
  631. catch (std::exception& e) {
  632. fprintf(stderr, "ERROR: Error initializing member: %s-%s %s\n", networkId.c_str(), memberId.c_str(), e.what());
  633. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  634. exit(-1);
  635. }
  636. }
  637. void CV2::heartbeat()
  638. {
  639. char publicId[1024];
  640. char hostnameTmp[1024];
  641. _myId.toString(false, publicId);
  642. if (gethostname(hostnameTmp, sizeof(hostnameTmp)) != 0) {
  643. hostnameTmp[0] = (char)0;
  644. }
  645. else {
  646. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  647. if ((hostnameTmp[i] == '.') || (hostnameTmp[i] == 0)) {
  648. hostnameTmp[i] = (char)0;
  649. break;
  650. }
  651. }
  652. }
  653. const char* controllerId = _myAddressStr.c_str();
  654. const char* publicIdentity = publicId;
  655. const char* hostname = hostnameTmp;
  656. while (_run == 1) {
  657. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  658. auto tracer = provider->GetTracer("cv2");
  659. auto span = tracer->StartSpan("cv2::heartbeat");
  660. auto scope = tracer->WithActiveSpan(span);
  661. auto c = _pool->borrow();
  662. int64_t ts = OSUtils::now();
  663. if (c->c) {
  664. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  665. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  666. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  667. std::string version = major + "." + minor + "." + rev;
  668. std::string versionStr = "v" + version;
  669. try {
  670. pqxx::work w { *c->c };
  671. w.exec_params0(
  672. "INSERT INTO controllers_ctl (id, hostname, last_heartbeat, public_identity, version) VALUES "
  673. "($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5) "
  674. "ON CONFLICT (id) DO UPDATE SET hostname = EXCLUDED.hostname, last_heartbeat = EXCLUDED.last_heartbeat, "
  675. "public_identity = EXCLUDED.public_identity, version = EXCLUDED.version",
  676. controllerId,
  677. hostname,
  678. ts,
  679. publicIdentity,
  680. versionStr);
  681. w.commit();
  682. }
  683. catch (std::exception& e) {
  684. fprintf(stderr, "ERROR: Error in heartbeat: %s\n", e.what());
  685. span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
  686. continue;
  687. }
  688. catch (...) {
  689. fprintf(stderr, "ERROR: Unknown error in heartbeat\n");
  690. span->SetStatus(opentelemetry::trace::StatusCode::kError, "Unknown error in heartbeat");
  691. continue;
  692. }
  693. }
  694. _pool->unborrow(c);
  695. span->End();
  696. std::this_thread::sleep_for(std::chrono::seconds(1));
  697. }
  698. fprintf(stderr, "Exited heartbeat thread\n");
  699. }
  700. void CV2::membersDbWatcher()
  701. {
  702. auto c = _pool->borrow();
  703. std::string stream = "member_" + _myAddressStr;
  704. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  705. MemberNotificationReceiver m(this, *c->c, stream);
  706. while (_run == 1) {
  707. c->c->await_notification(5, 0);
  708. }
  709. _pool->unborrow(c);
  710. fprintf(stderr, "Exited membersDbWatcher\n");
  711. }
  712. void CV2::networksDbWatcher()
  713. {
  714. std::string stream = "network_" + _myAddressStr;
  715. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  716. auto c = _pool->borrow();
  717. NetworkNotificationReceiver n(this, *c->c, stream);
  718. while (_run == 1) {
  719. c->c->await_notification(5, 0);
  720. }
  721. _pool->unborrow(c);
  722. fprintf(stderr, "Exited networksDbWatcher\n");
  723. }
  724. void CV2::commitThread()
  725. {
  726. fprintf(stderr, "%s: commitThread start\n", _myAddressStr.c_str());
  727. std::pair<nlohmann::json, bool> qitem;
  728. while (_commitQueue.get(qitem) && (_run == 1)) {
  729. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  730. auto tracer = provider->GetTracer("cv2");
  731. auto span = tracer->StartSpan("cv2::commitThread");
  732. auto scope = tracer->WithActiveSpan(span);
  733. // fprintf(stderr, "commitThread tick\n");
  734. if (! qitem.first.is_object()) {
  735. fprintf(stderr, "not an object\n");
  736. continue;
  737. }
  738. std::shared_ptr<PostgresConnection> c;
  739. try {
  740. c = _pool->borrow();
  741. }
  742. catch (std::exception& e) {
  743. fprintf(stderr, "ERROR: %s\n", e.what());
  744. continue;
  745. }
  746. if (! c) {
  747. fprintf(stderr, "Error getting database connection\n");
  748. continue;
  749. }
  750. Metrics::pgsql_commit_ticks++;
  751. try {
  752. nlohmann::json& config = (qitem.first);
  753. const std::string objtype = config["objtype"];
  754. if (objtype == "member") {
  755. auto mspan = tracer->StartSpan("cv2::commitThread::member");
  756. auto mscope = tracer->WithActiveSpan(span);
  757. // fprintf(stderr, "%s: commitThread: member\n", _myAddressStr.c_str());
  758. std::string memberId;
  759. std::string networkId;
  760. try {
  761. pqxx::work w(*c->c);
  762. memberId = config["id"];
  763. networkId = config["nwid"];
  764. std::string target = "NULL";
  765. if (! config["remoteTraceTarget"].is_null()) {
  766. target = config["remoteTraceTarget"];
  767. }
  768. pqxx::row nwrow = w.exec_params1("SELECT COUNT(id) FROM networks WHERE id = $1", networkId);
  769. int nwcount = nwrow[0].as<int>();
  770. if (nwcount != 1) {
  771. fprintf(stderr, "network %s does not exist. skipping member upsert\n", networkId.c_str());
  772. w.abort();
  773. _pool->unborrow(c);
  774. continue;
  775. }
  776. // only needed for hooks, and no hooks for now
  777. // pqxx::row mrow = w.exec_params1("SELECT COUNT(id) FROM device_networks WHERE device_id = $1 AND network_id = $2", memberId, networkId);
  778. // int membercount = mrow[0].as<int>();
  779. // bool isNewMember = (membercount == 0);
  780. pqxx::result res = w.exec_params0(
  781. "INSERT INTO network_memberships_ctl (device_id, network_id, authorized, active_bridge, ip_assignments, "
  782. "no_auto_assign_ips, sso_exempt, authentication_expiry_time, capabilities, creation_time, "
  783. "identity, last_authorized_time, last_deauthorized_time, "
  784. "remote_trace_level, remote_trace_target, revision, tags, version_major, version_minor, "
  785. "version_revision, version_protocol) "
  786. "VALUES ($1, $2, $3, $4, $5, $6, $7, TO_TIMESTAMP($8::double precision/1000), $9, "
  787. "TO_TIMESTAMP($10::double precision/1000), $11, TO_TIMESTAMP($12::double precision/1000), "
  788. "TO_TIMESTAMP($13::double precision/1000), $14, $15, $16, $17, $18, $19, $20, $21) "
  789. "ON CONFLICT (device_id, network_id) DO UPDATE SET "
  790. "authorized = EXCLUDED.authorized, active_bridge = EXCLUDED.active_bridge, "
  791. "ip_assignments = EXCLUDED.ip_assignments, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  792. "sso_exempt = EXCLUDED.sso_exempt, authentication_expiry_time = EXCLUDED.authentication_expiry_time, "
  793. "capabilities = EXCLUDED.capabilities, creation_time = EXCLUDED.creation_time, "
  794. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  795. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, "
  796. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  797. "revision = EXCLUDED.revision, tags = EXCLUDED.tags, version_major = EXCLUDED.version_major, "
  798. "version_minor = EXCLUDED.version_minor, version_revision = EXCLUDED.version_revision, "
  799. "version_protocol = EXCLUDED.version_protocol",
  800. memberId,
  801. networkId,
  802. (bool)config["authorized"],
  803. (bool)config["activeBridge"],
  804. config["ipAssignments"].get<std::vector<std::string> >(),
  805. (bool)config["noAutoAssignIps"],
  806. (bool)config["ssoExempt"],
  807. (uint64_t)config["authenticationExpiryTime"],
  808. OSUtils::jsonDump(config["capabilities"], -1),
  809. (uint64_t)config["creationTime"],
  810. OSUtils::jsonString(config["identity"], ""),
  811. (uint64_t)config["lastAuthorizedTime"],
  812. (uint64_t)config["lastDeauthorizedTime"],
  813. (int)config["remoteTraceLevel"],
  814. target,
  815. (uint64_t)config["revision"],
  816. OSUtils::jsonDump(config["tags"], -1),
  817. (int)config["vMajor"],
  818. (int)config["vMinor"],
  819. (int)config["vRev"],
  820. (int)config["vProto"]);
  821. w.commit();
  822. // No hooks for now
  823. // if (_smee != NULL && isNewMember) {
  824. // pqxx::row row = w.exec_params1(
  825. // "SELECT "
  826. // " count(h.hook_id) "
  827. // "FROM "
  828. // " ztc_hook h "
  829. // " INNER JOIN ztc_org o ON o.org_id = h.org_id "
  830. // " INNER JOIN ztc_network n ON n.owner_id = o.owner_id "
  831. // " WHERE "
  832. // "n.id = $1 ",
  833. // networkId
  834. // );
  835. // int64_t hookCount = row[0].as<int64_t>();
  836. // if (hookCount > 0) {
  837. // notifyNewMember(networkId, memberId);
  838. // }
  839. // }
  840. const uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  841. const uint64_t memberidInt = OSUtils::jsonIntHex(config["id"], 0ULL);
  842. if (nwidInt && memberidInt) {
  843. nlohmann::json nwOrig;
  844. nlohmann::json memOrig;
  845. nlohmann::json memNew(config);
  846. get(nwidInt, nwOrig, memberidInt, memOrig);
  847. _memberChanged(memOrig, memNew, qitem.second);
  848. }
  849. else {
  850. fprintf(stderr, "%s: Can't notify of change. Error parsing nwid or memberid: %llu-%llu\n", _myAddressStr.c_str(), (unsigned long long)nwidInt, (unsigned long long)memberidInt);
  851. }
  852. }
  853. catch (pqxx::data_exception& e) {
  854. std::string cfgDump = OSUtils::jsonDump(config, 2);
  855. fprintf(stderr, "Member save %s-%s: %s\n", networkId.c_str(), memberId.c_str(), cfgDump.c_str());
  856. const pqxx::sql_error* s = dynamic_cast<const pqxx::sql_error*>(&e);
  857. fprintf(stderr, "%s ERROR: Error updating member: %s\n", _myAddressStr.c_str(), e.what());
  858. if (s) {
  859. fprintf(stderr, "%s ERROR: SQL error: %s\n", _myAddressStr.c_str(), s->query().c_str());
  860. }
  861. mspan->SetStatus(opentelemetry::trace::StatusCode::kError, "pqxx::data_exception");
  862. mspan->SetAttribute("error", e.what());
  863. mspan->SetAttribute("config", cfgDump);
  864. }
  865. catch (std::exception& e) {
  866. std::string cfgDump = OSUtils::jsonDump(config, 2);
  867. fprintf(stderr, "%s ERROR: Error updating member %s-%s: %s\njsonDump: %s\n", _myAddressStr.c_str(), networkId.c_str(), memberId.c_str(), e.what(), cfgDump.c_str());
  868. mspan->SetStatus(opentelemetry::trace::StatusCode::kError, "std::exception");
  869. mspan->SetAttribute("error", e.what());
  870. mspan->SetAttribute("config", cfgDump);
  871. }
  872. }
  873. else if (objtype == "network") {
  874. auto nspan = tracer->StartSpan("cv2::commitThread::network");
  875. auto nscope = tracer->WithActiveSpan(span);
  876. try {
  877. // fprintf(stderr, "%s: commitThread: network\n", _myAddressStr.c_str());
  878. pqxx::work w(*c->c);
  879. std::string id = config["id"];
  880. // network must already exist
  881. pqxx::result res = w.exec_params0(
  882. "INSERT INTO networks_ctl (id, name, configuration, controller_id, revision) "
  883. "VALUES ($1, $2, $3, $4, $5) "
  884. "ON CONFLICT (id) DO UPDATE SET "
  885. "name = EXCLUDED.name, configuration = EXCLUDED.configuration, revision = EXCLUDED.revision+1",
  886. id,
  887. OSUtils::jsonString(config["name"], ""),
  888. OSUtils::jsonDump(config, -1),
  889. _myAddressStr,
  890. ((uint64_t)config["revision"]));
  891. w.commit();
  892. const uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  893. if (nwidInt) {
  894. nlohmann::json nwOrig;
  895. nlohmann::json nwNew(config);
  896. get(nwidInt, nwOrig);
  897. _networkChanged(nwOrig, nwNew, qitem.second);
  898. }
  899. else {
  900. fprintf(stderr, "%s: Can't notify network changed: %llu\n", _myAddressStr.c_str(), (unsigned long long)nwidInt);
  901. }
  902. }
  903. catch (pqxx::data_exception& e) {
  904. const pqxx::sql_error* s = dynamic_cast<const pqxx::sql_error*>(&e);
  905. fprintf(stderr, "%s ERROR: Error updating network: %s\n", _myAddressStr.c_str(), e.what());
  906. if (s) {
  907. fprintf(stderr, "%s ERROR: SQL error: %s\n", _myAddressStr.c_str(), s->query().c_str());
  908. }
  909. nspan->SetStatus(opentelemetry::trace::StatusCode::kError, "pqxx::data_exception");
  910. nspan->SetAttribute("error", e.what());
  911. nspan->SetAttribute("config", OSUtils::jsonDump(config, 2));
  912. }
  913. catch (std::exception& e) {
  914. fprintf(stderr, "%s ERROR: Error updating network: %s\n", _myAddressStr.c_str(), e.what());
  915. nspan->SetStatus(opentelemetry::trace::StatusCode::kError, "std::exception");
  916. nspan->SetAttribute("error", e.what());
  917. nspan->SetAttribute("config", OSUtils::jsonDump(config, 2));
  918. }
  919. }
  920. else if (objtype == "_delete_network") {
  921. auto dspan = tracer->StartSpan("cv2::commitThread::delete_network");
  922. auto dscope = tracer->WithActiveSpan(span);
  923. // fprintf(stderr, "%s: commitThread: delete network\n", _myAddressStr.c_str());
  924. try {
  925. pqxx::work w(*c->c);
  926. std::string networkId = config["id"];
  927. w.exec_params0("DELETE FROM network_memberships_ctl WHERE network_id = $1", networkId);
  928. w.exec_params0("DELETE FROM networks_ctl WHERE id = $1", networkId);
  929. w.commit();
  930. }
  931. catch (std::exception& e) {
  932. fprintf(stderr, "%s ERROR: Error deleting network: %s\n", _myAddressStr.c_str(), e.what());
  933. dspan->SetStatus(opentelemetry::trace::StatusCode::kError, "std::exception");
  934. dspan->SetAttribute("error", e.what());
  935. dspan->SetAttribute("config", OSUtils::jsonDump(config, 2));
  936. }
  937. }
  938. else if (objtype == "_delete_member") {
  939. auto dspan = tracer->StartSpan("cv2::commitThread::delete_member");
  940. auto dscope = tracer->WithActiveSpan(span);
  941. // fprintf(stderr, "%s commitThread: delete member\n", _myAddressStr.c_str());
  942. try {
  943. pqxx::work w(*c->c);
  944. std::string memberId = config["id"];
  945. std::string networkId = config["nwid"];
  946. pqxx::result res = w.exec_params0("DELETE FROM network_memberships_ctl WHERE device_id = $1 AND network_id = $2", memberId, networkId);
  947. w.commit();
  948. }
  949. catch (std::exception& e) {
  950. fprintf(stderr, "%s ERROR: Error deleting member: %s\n", _myAddressStr.c_str(), e.what());
  951. dspan->SetStatus(opentelemetry::trace::StatusCode::kError, "std::exception");
  952. dspan->SetAttribute("error", e.what());
  953. dspan->SetAttribute("config", OSUtils::jsonDump(config, 2));
  954. }
  955. }
  956. else {
  957. fprintf(stderr, "%s ERROR: unknown objtype\n", _myAddressStr.c_str());
  958. }
  959. }
  960. catch (std::exception& e) {
  961. fprintf(stderr, "%s ERROR: Error getting objtype: %s\n", _myAddressStr.c_str(), e.what());
  962. span->SetStatus(opentelemetry::trace::StatusCode::kError, "std::exception");
  963. span->SetAttribute("error", e.what());
  964. }
  965. _pool->unborrow(c);
  966. c.reset();
  967. }
  968. fprintf(stderr, "%s commitThread finished\n", _myAddressStr.c_str());
  969. }
  970. void CV2::onlineNotificationThread()
  971. {
  972. waitForReady();
  973. _connected = 1;
  974. nlohmann::json jtmp1, jtmp2;
  975. while (_run == 1) {
  976. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  977. auto tracer = provider->GetTracer("cv2");
  978. auto span = tracer->StartSpan("cv2::onlineNotificationThread");
  979. auto scope = tracer->WithActiveSpan(span);
  980. auto c = _pool->borrow();
  981. auto c2 = _pool->borrow();
  982. try {
  983. fprintf(stderr, "%s onlineNotificationThread\n", _myAddressStr.c_str());
  984. std::unordered_map<std::pair<uint64_t, uint64_t>, NodeOnlineRecord, _PairHasher> lastOnline;
  985. {
  986. std::lock_guard<std::mutex> l(_lastOnline_l);
  987. lastOnline.swap(_lastOnline);
  988. }
  989. pqxx::work w(*c->c);
  990. pqxx::work w2(*c2->c);
  991. bool firstRun = true;
  992. bool memberAdded = false;
  993. uint64_t updateCount = 0;
  994. pqxx::pipeline pipe(w);
  995. for (auto i = lastOnline.begin(); i != lastOnline.end(); ++i) {
  996. updateCount++;
  997. uint64_t nwid_i = i->first.first;
  998. char nwidTmp[64];
  999. char memTmp[64];
  1000. char ipTmp[64];
  1001. OSUtils::ztsnprintf(nwidTmp, sizeof(nwidTmp), "%.16llx", nwid_i);
  1002. OSUtils::ztsnprintf(memTmp, sizeof(memTmp), "%.10llx", i->first.second);
  1003. if (! get(nwid_i, jtmp1, i->first.second, jtmp2)) {
  1004. continue; // skip non existent networks/members
  1005. }
  1006. std::string networkId(nwidTmp);
  1007. std::string memberId(memTmp);
  1008. try {
  1009. pqxx::row r = w2.exec_params1("SELECT device_id, network_id FROM network_memberships_ctl WHERE network_id = $1 AND device_id = $2", networkId, memberId);
  1010. }
  1011. catch (pqxx::unexpected_rows& e) {
  1012. continue;
  1013. }
  1014. int64_t ts = i->second.lastSeen;
  1015. std::string ipAddr = i->second.physicalAddress.toIpString(ipTmp);
  1016. std::string timestamp = std::to_string(ts);
  1017. std::string osArch = i->second.osArch;
  1018. std::vector<std::string> osArchSplit = split(osArch, '/');
  1019. std::string os = osArchSplit[0];
  1020. std::string arch = osArchSplit[1];
  1021. if (ipAddr.empty()) {
  1022. ipAddr = "relayed";
  1023. }
  1024. json record = {
  1025. { ipAddr, ts },
  1026. };
  1027. std::string device_network_insert = "INSERT INTO network_memberships_ctl (device_id, network_id, last_seen, os, arch) "
  1028. "VALUES ('"
  1029. + w2.esc(memberId) + "', '" + w2.esc(networkId) + "', '" + w2.esc(record.dump())
  1030. + "'::JSONB, "
  1031. "'"
  1032. + w2.esc(os) + "', '" + w2.esc(arch)
  1033. + "') "
  1034. "ON CONFLICT (device_id, network_id) DO UPDATE SET os = EXCLUDED.os, arch = EXCLUDED.arch, "
  1035. "last_seen = network_memberships_ctl.last_seen || EXCLUDED.last_seen";
  1036. pipe.insert(device_network_insert);
  1037. Metrics::pgsql_node_checkin++;
  1038. }
  1039. pipe.complete();
  1040. ;
  1041. w2.commit();
  1042. w.commit();
  1043. fprintf(stderr, "%s: Updated online status of %lu members\n", _myAddressStr.c_str(), updateCount);
  1044. }
  1045. catch (std::exception& e) {
  1046. fprintf(stderr, "%s ERROR: Error in onlineNotificationThread: %s\n", _myAddressStr.c_str(), e.what());
  1047. span->SetStatus(opentelemetry::trace::StatusCode::kError, "std::exception");
  1048. span->SetAttribute("error", e.what());
  1049. }
  1050. catch (...) {
  1051. fprintf(stderr, "%s ERROR: Unknown error in onlineNotificationThread\n", _myAddressStr.c_str());
  1052. span->SetStatus(opentelemetry::trace::StatusCode::kError, "unknown");
  1053. }
  1054. _pool->unborrow(c2);
  1055. _pool->unborrow(c);
  1056. span->End();
  1057. std::this_thread::sleep_for(std::chrono::seconds(10));
  1058. }
  1059. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  1060. if (_run == 1) {
  1061. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1062. exit(6);
  1063. }
  1064. }
  1065. #endif // ZT_CONTROLLER_USE_LIBPQ