CV2.cpp 43 KB

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