PostgreSQL.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifdef ZT_CONTROLLER_USE_LIBPQ
  19. #include "PostgreSQL.hpp"
  20. #include "EmbeddedNetworkController.hpp"
  21. #include "../version.h"
  22. #include <libpq-fe.h>
  23. using json = nlohmann::json;
  24. namespace {
  25. static const char *_timestr()
  26. {
  27. time_t t = time(0);
  28. char *ts = ctime(&t);
  29. char *p = ts;
  30. if (!p)
  31. return "";
  32. while (*p) {
  33. if (*p == '\n') {
  34. *p = (char)0;
  35. break;
  36. }
  37. ++p;
  38. }
  39. return ts;
  40. }
  41. }
  42. using namespace ZeroTier;
  43. PostgreSQL::PostgreSQL(EmbeddedNetworkController *const nc, const Identity &myId, const char *path)
  44. : DB(nc, myId, path)
  45. , _ready(0)
  46. , _connected(1)
  47. , _run(1)
  48. , _waitNoticePrinted(false)
  49. {
  50. _connString = std::string(path);
  51. _readyLock.lock();
  52. _heartbeatThread = std::thread(&PostgreSQL::heartbeat, this);
  53. _membersDbWatcher = std::thread(&PostgreSQL::membersDbWatcher, this);
  54. _networksDbWatcher = std::thread(&PostgreSQL::networksDbWatcher, this);
  55. for (int i = 0; i < ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS; ++i) {
  56. _commitThread[i] = std::thread(&PostgreSQL::commitThread, this);
  57. }
  58. _onlineNotificationThread = std::thread(&PostgreSQL::onlineNotificationThread, this);
  59. }
  60. PostgreSQL::~PostgreSQL()
  61. {
  62. _run = 0;
  63. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  64. _heartbeatThread.join();
  65. _membersDbWatcher.join();
  66. _networksDbWatcher.join();
  67. for (int i = 0; i < ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS; ++i) {
  68. _commitThread[i].join();
  69. }
  70. _onlineNotificationThread.join();
  71. }
  72. bool PostgreSQL::waitForReady()
  73. {
  74. while (_ready < 2) {
  75. if (!_waitNoticePrinted) {
  76. _waitNoticePrinted = true;
  77. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S, ::_timestr(), (unsigned long long)_myAddress.toInt());
  78. }
  79. _readyLock.lock();
  80. _readyLock.unlock();
  81. }
  82. return true;
  83. }
  84. bool PostgreSQL::isReady()
  85. {
  86. return ((_ready == 2)&&(_connected));
  87. }
  88. void PostgreSQL::save(nlohmann::json *orig, nlohmann::json &record)
  89. {
  90. if (!record.is_object()) {
  91. return;
  92. }
  93. waitForReady();
  94. if (orig) {
  95. if (*orig != record) {
  96. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  97. _commitQueue.post(new nlohmann::json(record));
  98. }
  99. } else {
  100. record["revision"] = 1;
  101. _commitQueue.post(new nlohmann::json(record));
  102. }
  103. }
  104. void PostgreSQL::eraseNetwork(const uint64_t networkId)
  105. {
  106. char tmp2[24];
  107. waitForReady();
  108. Utils::hex(networkId, tmp2);
  109. json *tmp = new json();
  110. (*tmp)["id"] = tmp2;
  111. (*tmp)["objtype"] = "_delete_network";
  112. _commitQueue.post(tmp);
  113. }
  114. void PostgreSQL::eraseMember(const uint64_t networkId, const uint64_t memberId)
  115. {
  116. char tmp2[24];
  117. json *tmp = new json();
  118. Utils::hex(networkId, tmp2);
  119. (*tmp)["nwid"] = tmp2;
  120. Utils::hex(memberId, tmp2);
  121. (*tmp)["id"] = tmp2;
  122. (*tmp)["objtype"] = "_delete_member";
  123. _commitQueue.post(tmp);
  124. }
  125. void PostgreSQL::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress)
  126. {
  127. std::lock_guard<std::mutex> l(_lastOnline_l);
  128. std::pair<int64_t, InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId, memberId)];
  129. i.first = OSUtils::now();
  130. if (physicalAddress) {
  131. i.second = physicalAddress;
  132. }
  133. }
  134. void PostgreSQL::initializeNetworks(PGconn *conn)
  135. {
  136. if (PQstatus(conn) != CONNECTION_OK) {
  137. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  138. exit(1);
  139. }
  140. const char *params[1] = {
  141. _myAddressStr.c_str()
  142. };
  143. PGresult *res = PQexecParams(conn, "SELECT id, EXTRACT(EPOCH FROM creation_time AT TIME ZONE 'UTC')*1000, capabilities, "
  144. "enable_broadcast, EXTRACT(EPOCH FROM last_modified AT TIME ZONE 'UTC')*1000, mtu, multicast_limit, name, private, remote_trace_level, "
  145. "remote_trace_target, revision, rules, tags, v4_assign_mode, v6_assign_mode FROM ztc_network "
  146. "WHERE deleted = false AND controller_id = $1",
  147. 1,
  148. NULL,
  149. params,
  150. NULL,
  151. NULL,
  152. 0);
  153. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  154. fprintf(stderr, "Networks Initialization Failed: %s", PQerrorMessage(conn));
  155. PQclear(res);
  156. exit(1);
  157. }
  158. int numRows = PQntuples(res);
  159. for (int i = 0; i < numRows; ++i) {
  160. json empty;
  161. json config;
  162. config["nwid"] = PQgetvalue(res, i, 0);
  163. config["creationTime"] = std::stoull(PQgetvalue(res, i, 1));
  164. config["capabilities"] = json::parse(PQgetvalue(res, i, 2));
  165. config["enableBroadcast"] = (strcmp(PQgetvalue(res, i, 3),"true")==0);
  166. config["lastModified"] = std::stoull(PQgetvalue(res, i, 4));
  167. config["mtu"] = std::stoi(PQgetvalue(res, i, 5));
  168. config["multicastLimit"] = std::stoi(PQgetvalue(res, i, 6));
  169. config["name"] = PQgetvalue(res, i, 7);
  170. config["private"] = (strcmp(PQgetvalue(res, i, 8),"true")==0);
  171. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
  172. config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
  173. config["revision"] = std::stoull(PQgetvalue(res, i, 11));
  174. config["rules"] = json::parse(PQgetvalue(res, i, 12));
  175. config["tags"] = json::parse(PQgetvalue(res, i, 13));
  176. config["v4AssignMode"] = json::parse(PQgetvalue(res, i, 14));
  177. config["v6AssignMode"] = json::parse(PQgetvalue(res, i, 15));
  178. _networkChanged(empty, config, false);
  179. }
  180. PQclear(res);
  181. if (++this->_ready == 2) {
  182. if (_waitNoticePrinted) {
  183. fprintf(stderr,"[%s] NOTICE: %.10llx controller RethinkDB data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  184. }
  185. _readyLock.unlock();
  186. }
  187. }
  188. void PostgreSQL::initializeMembers(PGconn *conn)
  189. {
  190. // TODO: do stuff here
  191. if (++this->_ready == 2) {
  192. if (_waitNoticePrinted) {
  193. fprintf(stderr,"[%s] NOTICE: %.10llx controller RethinkDB data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  194. }
  195. _readyLock.unlock();
  196. }
  197. }
  198. void PostgreSQL::heartbeat()
  199. {
  200. char publicId[1024];
  201. char hostnameTmp[1024];
  202. _myId.toString(false,publicId);
  203. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  204. hostnameTmp[0] = (char)0;
  205. } else {
  206. for (int i = 0; i < sizeof(hostnameTmp); ++i) {
  207. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  208. hostnameTmp[i] = (char)0;
  209. break;
  210. }
  211. }
  212. }
  213. const char *controllerId = _myAddressStr.c_str();
  214. const char *publicIdentity = publicId;
  215. const char *hostname = hostnameTmp;
  216. PGconn *conn = PQconnectdb(_path.c_str());
  217. if (PQstatus(conn) == CONNECTION_BAD) {
  218. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  219. PQfinish(conn);
  220. exit(1);
  221. }
  222. while (_run == 1) {
  223. if(PQstatus(conn) != CONNECTION_OK) {
  224. PQfinish(conn);
  225. conn = PQconnectdb(_path.c_str());
  226. }
  227. if (conn) {
  228. const char *values[8] = {
  229. controllerId,
  230. hostname,
  231. std::to_string(OSUtils::now()).c_str(),
  232. publicIdentity,
  233. std::to_string(ZEROTIER_ONE_VERSION_MAJOR).c_str(),
  234. std::to_string(ZEROTIER_ONE_VERSION_MINOR).c_str(),
  235. std::to_string(ZEROTIER_ONE_VERSION_REVISION).c_str(),
  236. std::to_string(ZEROTIER_ONE_VERSION_BUILD).c_str()
  237. };
  238. int lengths[8] = {
  239. (int)strlen(values[0]),
  240. (int)strlen(values[1]),
  241. (int)strlen(values[2]),
  242. (int)strlen(values[3]),
  243. (int)strlen(values[4]),
  244. (int)strlen(values[5]),
  245. (int)strlen(values[6]),
  246. (int)strlen(values[7])
  247. };
  248. int binary[8] = {0,0,0,0,0,0,0,0};
  249. PGresult *res = PQexecParams(conn,
  250. "INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build) "
  251. "VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8) "
  252. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  253. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  254. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev",
  255. 8, // number of parameters
  256. NULL, // oid field. ignore
  257. values, // values for substitution
  258. lengths, // lengths in bytes of each value
  259. binary, // binary?
  260. 0);
  261. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  262. fprintf(stderr, "Heartbeat Update Failed: %s\n", PQresultErrorMessage(res));
  263. }
  264. PQclear(res);
  265. }
  266. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  267. }
  268. PQfinish(conn);
  269. conn = NULL;
  270. }
  271. void PostgreSQL::membersDbWatcher()
  272. {
  273. PGconn *conn = PQconnectdb(_path.c_str());
  274. if (PQstatus(conn) == CONNECTION_BAD) {
  275. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  276. PQfinish(conn);
  277. exit(1);
  278. }
  279. initializeMembers(conn);
  280. char buf[11] = {0};
  281. std::string cmd = "LISTEN member_" + std::string(_myAddress.toString(buf));
  282. PGresult *res = PQexec(conn, cmd.c_str());
  283. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  284. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  285. PQclear(res);
  286. PQfinish(conn);
  287. exit(1);
  288. }
  289. PQclear(res); res = NULL;
  290. while(_run == 1) {
  291. if (PQstatus(conn) != CONNECTION_OK) {
  292. fprintf(stderr, "ERROR: Member Watcher lost connection to Postgres.");
  293. exit(-1);
  294. }
  295. PGnotify *notify = NULL;
  296. PQconsumeInput(conn);
  297. while ((notify = PQnotifies(conn)) != NULL) {
  298. fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  299. try {
  300. json tmp(json::parse(notify->extra));
  301. json &ov = tmp["old_val"];
  302. json &nv = tmp["new_val"];
  303. json oldConfig, newConfig;
  304. if (ov.is_object()) oldConfig = ov;
  305. if (nv.is_object()) newConfig = nv;
  306. if (oldConfig.is_object() || newConfig.is_object()) {
  307. _memberChanged(oldConfig,newConfig,(this->_ready>=2));
  308. }
  309. } catch (...) {} // ignore bad records
  310. free(notify);
  311. }
  312. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  313. }
  314. PQfinish(conn);
  315. conn = NULL;
  316. }
  317. void PostgreSQL::networksDbWatcher()
  318. {
  319. PGconn *conn = PQconnectdb(_path.c_str());
  320. if (PQstatus(conn) == CONNECTION_BAD) {
  321. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  322. PQfinish(conn);
  323. exit(1);
  324. }
  325. initializeNetworks(conn);
  326. char buf[11] = {0};
  327. std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
  328. PGresult *res = PQexec(conn, cmd.c_str());
  329. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  330. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  331. PQclear(res);
  332. PQfinish(conn);
  333. exit(1);
  334. }
  335. PQclear(res); res = NULL;
  336. while(_run == 1) {
  337. if (PQstatus(conn) != CONNECTION_OK) {
  338. fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
  339. exit(-1);
  340. }
  341. PGnotify *notify = NULL;
  342. PQconsumeInput(conn);
  343. while ((notify = PQnotifies(conn)) != NULL) {
  344. fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  345. try {
  346. json tmp(json::parse(notify->extra));
  347. json &ov = tmp["old_val"];
  348. json &nv = tmp["new_val"];
  349. json oldConfig, newConfig;
  350. if (ov.is_object()) oldConfig = ov;
  351. if (nv.is_object()) newConfig = nv;
  352. if (oldConfig.is_object()||newConfig.is_object()) {
  353. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  354. }
  355. } catch (...) {} // ignore bad records
  356. free(notify);
  357. }
  358. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  359. }
  360. PQfinish(conn);
  361. conn = NULL;
  362. }
  363. void PostgreSQL::commitThread()
  364. {
  365. json *config = nullptr;
  366. while(_commitQueue.get(config)&(_run == 1)) {
  367. if (!config) {
  368. continue;
  369. }
  370. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  371. }
  372. }
  373. void PostgreSQL::onlineNotificationThread()
  374. {
  375. PGconn *conn = PQconnectdb(_path.c_str());
  376. if (PQstatus(conn) == CONNECTION_BAD) {
  377. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  378. PQfinish(conn);
  379. exit(1);
  380. }
  381. _connected = 1;
  382. int64_t lastUpdatedNetworkStatus = 0;
  383. std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative;
  384. while (_run == 1) {
  385. if (PQstatus(conn) != CONNECTION_OK) {
  386. fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres.");
  387. exit(-1);
  388. }
  389. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  390. {
  391. std::lock_guard<std::mutex> l(_lastOnline_l);
  392. lastOnline.swap(_lastOnline);
  393. }
  394. PGresult *res = NULL;
  395. int qCount = 0;
  396. if (!lastOnline.empty()) {
  397. fprintf(stderr, "Last Online Update\n");
  398. res = PQexec(conn, "BEGIN");
  399. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  400. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  401. PQclear(res);
  402. exit(1);
  403. }
  404. PQclear(res);
  405. }
  406. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  407. lastOnlineCumulative[i->first] = i->second.first;
  408. char nwidTmp[64];
  409. char memTmp[64];
  410. char ipTmp[64];
  411. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", i->first.first);
  412. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  413. std::string networkId(nwidTmp);
  414. std::string memberId(memTmp);
  415. int64_t ts = i->second.first;
  416. std::string ipAddr = i->second.second.toIpString(ipTmp);
  417. const char *values[4] = {
  418. networkId.c_str(),
  419. memberId.c_str(),
  420. std::to_string(ts).c_str(),
  421. ipAddr.c_str()
  422. };
  423. res = PQexecParams(conn,
  424. "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ($1, $2, $3, $4)"
  425. "ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated",
  426. 8, // number of parameters
  427. NULL, // oid field. ignore
  428. values, // values for substitution
  429. NULL, // lengths in bytes of each value
  430. NULL,
  431. 0);
  432. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  433. fprintf(stderr, "Error on Member Status upsert: %s\n", PQresultErrorMessage(res));
  434. PQclear(res);
  435. PQexec(conn, "ROLLBACK");
  436. exit(1);
  437. }
  438. PQclear(res);
  439. if ((++qCount) == 1024) {
  440. res = PQexec(conn, "COMMIT");
  441. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  442. fprintf(stderr, "ERROR: Error on commit (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  443. PQclear(res);
  444. PQexec(conn, "ROLLBACK");
  445. exit(1);
  446. }
  447. PQclear(res);
  448. res = PQexec(conn, "BEGIN");
  449. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  450. fprintf(stderr, "ERROR: Error on BEGIN (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  451. PQclear(res);
  452. exit(1);
  453. }
  454. PQclear(res);
  455. qCount = 0;
  456. }
  457. }
  458. if (qCount > 0) {
  459. fprintf(stderr, "qCount is %d\n", qCount);
  460. res = PQexec(conn, "COMMIT");
  461. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  462. fprintf(stderr, "ERROR: Error on commit (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  463. PQclear(res);
  464. PQexec(conn, "ROLLBACK");
  465. exit(1);
  466. }
  467. PQclear(res);
  468. }
  469. const int64_t now = OSUtils::now();
  470. if ((now - lastUpdatedNetworkStatus) > 10000) {
  471. lastUpdatedNetworkStatus = now;
  472. std::vector<std::pair<uint64_t, std::shared_ptr<_Network>>> networks;
  473. {
  474. std::lock_guard<std::mutex> l(_networks_l);
  475. for (auto i = _networks.begin(); i != _networks.end(); ++i) {
  476. networks.push_back(*i);
  477. }
  478. }
  479. int nCount = 0;
  480. if (!networks.empty()) {
  481. fprintf(stderr, "Network update");
  482. res = PQexec(conn, "BEGIN");
  483. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  484. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  485. PQclear(res);
  486. exit(1);
  487. }
  488. PQclear(res);
  489. }
  490. for (auto i = networks.begin(); i != networks.end(); ++i) {
  491. char tmp[64];
  492. Utils::hex(i->first, tmp);
  493. std::string networkId(tmp);
  494. uint64_t authMemberCount = 0;
  495. uint64_t totalMemberCount = 0;
  496. uint64_t onlineMemberCount = 0;
  497. uint64_t bridgeCount = 0;
  498. uint64_t ts = now;
  499. {
  500. std::lock_guard<std::mutex> l2(i->second->lock);
  501. authMemberCount = i->second->authorizedMembers.size();
  502. totalMemberCount = i->second->members.size();
  503. bridgeCount = i->second->activeBridgeMembers.size();
  504. for (auto m=i->second->members.begin(); m != i->second->members.end(); ++m) {
  505. auto lo = lastOnlineCumulative.find(std::pair<uint64_t,uint64_t>(i->first, m->first));
  506. if (lo != lastOnlineCumulative.end()) {
  507. if ((now - lo->second) <= (ZT_NETWORK_AUTOCONF_DELAY * 2)) {
  508. ++onlineMemberCount;
  509. } else {
  510. lastOnlineCumulative.erase(lo);
  511. }
  512. }
  513. }
  514. }
  515. const char *values[6] = {
  516. networkId.c_str(),
  517. std::to_string(bridgeCount).c_str(),
  518. std::to_string(authMemberCount).c_str(),
  519. std::to_string(onlineMemberCount).c_str(),
  520. std::to_string(totalMemberCount).c_str(),
  521. std::to_string(ts).c_str()
  522. };
  523. res = PQexecParams(conn, "INSERT INTO ztc_network_status (network_id, bridge_count, authorized_member_count, "
  524. "online_member_count, total_member_count, last_modified) VALUES ($1, $2, $3, $4, $5, $6) "
  525. "ON CONFLICT (network_id) DO UPDATE SET bridge_count = EXCLUDED.bridge_count, "
  526. "authorized_member_count = EXCLUDED.authorized_member_count, online_member_count = EXCDLUDED.online_member_count, "
  527. "total_member_count = EXCLUDED.total_member_count, last_modified = EXCLUDED.last_modified",
  528. 6,
  529. NULL,
  530. values,
  531. NULL,
  532. NULL,
  533. 0);
  534. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  535. fprintf(stderr, "ERROR: Error on Network Satus upsert (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  536. PQclear(res);
  537. PQexec(conn, "ROLLBACK");
  538. exit(1);
  539. }
  540. if ((++nCount) == 1024) {
  541. res = PQexec(conn, "COMMIT");
  542. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  543. fprintf(stderr, "ERROR: Error on COMMIT (onlineNotificationThread): %s\n" , PQresultErrorMessage(res));
  544. PQclear(res);
  545. PQexec(conn, "ROLLBACK");
  546. exit(1);
  547. }
  548. res = PQexec(conn, "BEGIN");
  549. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  550. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  551. PQclear(res);
  552. exit(1);
  553. }
  554. nCount = 0;
  555. }
  556. }
  557. if (nCount > 0) {
  558. fprintf(stderr, "nCount is %d\n", nCount);
  559. res = PQexec(conn, "COMMIT");
  560. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  561. fprintf(stderr, "ERROR: Error on COMMIT (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  562. PQclear(res);
  563. PQexec(conn, "ROLLBACK");
  564. exit(1);
  565. }
  566. }
  567. }
  568. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  569. }
  570. PQfinish(conn);
  571. }
  572. #endif //ZT_CONTROLLER_USE_LIBPQ