CV2.cpp 43 KB

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