CV2.cpp 37 KB

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