PostgreSQL.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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. config["objtype"] = "network";
  179. _networkChanged(empty, config, false);
  180. }
  181. PQclear(res);
  182. if (++this->_ready == 2) {
  183. if (_waitNoticePrinted) {
  184. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  185. }
  186. _readyLock.unlock();
  187. }
  188. }
  189. void PostgreSQL::initializeMembers(PGconn *conn)
  190. {
  191. if (PQstatus(conn) != CONNECTION_OK) {
  192. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  193. exit(1);
  194. }
  195. const char *params[1] = {
  196. _myAddressStr.c_str()
  197. };
  198. PGresult *res = PQexecParams(conn,
  199. "SELECT m.id, m.network_id, m.active_bridge, m.authorized, m.capabilities, EXTRACT(EPOCH FROM m.creation_time AT TIME ZONE 'UTC')*1000, m.identity, "
  200. " EXTRACT(EPOCH FROM m.last_authorized_time AT TIME ZONE 'UTC')*1000, "
  201. " EXTRACT(EPOCH FROM m.last_deauthorized_time AT TIME ZONE 'UTC')*1000, "
  202. " m.remote_trace_level, m.remote_trace_target, m.tags, m.v_major, m.v_minor, m.v_rev, m.v_proto, "
  203. " m.no_auto_assign_ips, m.revision "
  204. "FROM ztc_member m "
  205. "INNER JOIN ztc_network n "
  206. " ON n.id = m.network_id "
  207. "WHERE n.controller_id = $1 AND m.deleted = false",
  208. 1,
  209. NULL,
  210. params,
  211. NULL,
  212. NULL,
  213. 0);
  214. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  215. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  216. PQclear(res);
  217. exit(1);
  218. }
  219. int numRows = PQntuples(res);
  220. for (int i = 0; i < numRows; ++i) {
  221. json empty;
  222. json config;
  223. std::string memberId(PQgetvalue(res, i, 0));
  224. std::string networkId(PQgetvalue(res, i, 1));
  225. config["id"] = memberId;
  226. config["nwid"] = networkId;
  227. config["activeBridge"] = (strcmp(PQgetvalue(res, i, 3), "true") == 0);
  228. config["authorized"] = (strcmp(PQgetvalue(res, i, 4), "true") == 0);
  229. config["capabilities"] = json::parse(PQgetvalue(res, i, 5));
  230. config["creationTime"] = std::stoull(PQgetvalue(res, i, 6));
  231. config["identity"] = PQgetvalue(res, i, 7);
  232. config["lastAuthorizedTime"] = std::stoull(PQgetvalue(res, i, 8));
  233. config["lastDeauthorizedTime"] = std::stoull(PQgetvalue(res, i, 9));
  234. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 10));
  235. config["remoteTraceTarget"] = PQgetvalue(res, i, 11);
  236. config["tags"] = json::parse(PQgetvalue(res, i, 12));
  237. config["vMajor"] = std::stoi(PQgetvalue(res, i, 13));
  238. config["vMinor"] = std::stoi(PQgetvalue(res, i, 14));
  239. config["vRev"] = std::stoi(PQgetvalue(res, i, 15));
  240. config["vProto"] = std::stoi(PQgetvalue(res, i, 16));
  241. config["noAutoAssignIps"] = (strcmp(PQgetvalue(res, i, 17), "true") == 0);
  242. config["revision"] = std::stoull(PQgetvalue(res, i, 18));
  243. config["objtype"] = "member";
  244. config["ipAssignments"] = json::array();
  245. const char *p2[2] = {
  246. memberId.c_str(),
  247. networkId.c_str()
  248. };
  249. PGresult *r2 = PQexecParams(conn,
  250. "SELECT address FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  251. 2,
  252. NULL,
  253. p2,
  254. NULL,
  255. NULL,
  256. 0);
  257. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  258. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  259. PQclear(r2);
  260. PQclear(res);
  261. exit(1);
  262. }
  263. int n = PQntuples(r2);
  264. for (int j = 0; j < n; ++j) {
  265. config["ipAssignments"].push_back(PQgetvalue(r2, j, 0));
  266. }
  267. _memberChanged(empty, config, false);
  268. }
  269. PQclear(res);
  270. if (++this->_ready == 2) {
  271. if (_waitNoticePrinted) {
  272. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  273. }
  274. _readyLock.unlock();
  275. }
  276. }
  277. void PostgreSQL::heartbeat()
  278. {
  279. char publicId[1024];
  280. char hostnameTmp[1024];
  281. _myId.toString(false,publicId);
  282. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  283. hostnameTmp[0] = (char)0;
  284. } else {
  285. for (int i = 0; i < sizeof(hostnameTmp); ++i) {
  286. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  287. hostnameTmp[i] = (char)0;
  288. break;
  289. }
  290. }
  291. }
  292. const char *controllerId = _myAddressStr.c_str();
  293. const char *publicIdentity = publicId;
  294. const char *hostname = hostnameTmp;
  295. PGconn *conn = PQconnectdb(_path.c_str());
  296. if (PQstatus(conn) == CONNECTION_BAD) {
  297. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  298. PQfinish(conn);
  299. exit(1);
  300. }
  301. while (_run == 1) {
  302. if(PQstatus(conn) != CONNECTION_OK) {
  303. PQfinish(conn);
  304. conn = PQconnectdb(_path.c_str());
  305. }
  306. if (conn) {
  307. const char *values[8] = {
  308. controllerId,
  309. hostname,
  310. std::to_string(OSUtils::now()).c_str(),
  311. publicIdentity,
  312. std::to_string(ZEROTIER_ONE_VERSION_MAJOR).c_str(),
  313. std::to_string(ZEROTIER_ONE_VERSION_MINOR).c_str(),
  314. std::to_string(ZEROTIER_ONE_VERSION_REVISION).c_str(),
  315. std::to_string(ZEROTIER_ONE_VERSION_BUILD).c_str()
  316. };
  317. int lengths[8] = {
  318. (int)strlen(values[0]),
  319. (int)strlen(values[1]),
  320. (int)strlen(values[2]),
  321. (int)strlen(values[3]),
  322. (int)strlen(values[4]),
  323. (int)strlen(values[5]),
  324. (int)strlen(values[6]),
  325. (int)strlen(values[7])
  326. };
  327. int binary[8] = {0,0,0,0,0,0,0,0};
  328. PGresult *res = PQexecParams(conn,
  329. "INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build) "
  330. "VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8) "
  331. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  332. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  333. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev",
  334. 8, // number of parameters
  335. NULL, // oid field. ignore
  336. values, // values for substitution
  337. lengths, // lengths in bytes of each value
  338. binary, // binary?
  339. 0);
  340. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  341. fprintf(stderr, "Heartbeat Update Failed: %s\n", PQresultErrorMessage(res));
  342. }
  343. PQclear(res);
  344. }
  345. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  346. }
  347. PQfinish(conn);
  348. conn = NULL;
  349. }
  350. void PostgreSQL::membersDbWatcher()
  351. {
  352. PGconn *conn = PQconnectdb(_path.c_str());
  353. if (PQstatus(conn) == CONNECTION_BAD) {
  354. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  355. PQfinish(conn);
  356. exit(1);
  357. }
  358. initializeMembers(conn);
  359. char buf[11] = {0};
  360. std::string cmd = "LISTEN member_" + std::string(_myAddress.toString(buf));
  361. PGresult *res = PQexec(conn, cmd.c_str());
  362. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  363. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  364. PQclear(res);
  365. PQfinish(conn);
  366. exit(1);
  367. }
  368. PQclear(res); res = NULL;
  369. while(_run == 1) {
  370. if (PQstatus(conn) != CONNECTION_OK) {
  371. fprintf(stderr, "ERROR: Member Watcher lost connection to Postgres.");
  372. exit(-1);
  373. }
  374. PGnotify *notify = NULL;
  375. PQconsumeInput(conn);
  376. while ((notify = PQnotifies(conn)) != NULL) {
  377. fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  378. try {
  379. json tmp(json::parse(notify->extra));
  380. json &ov = tmp["old_val"];
  381. json &nv = tmp["new_val"];
  382. json oldConfig, newConfig;
  383. if (ov.is_object()) oldConfig = ov;
  384. if (nv.is_object()) newConfig = nv;
  385. if (oldConfig.is_object() || newConfig.is_object()) {
  386. _memberChanged(oldConfig,newConfig,(this->_ready>=2));
  387. }
  388. } catch (...) {} // ignore bad records
  389. free(notify);
  390. }
  391. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  392. }
  393. PQfinish(conn);
  394. conn = NULL;
  395. }
  396. void PostgreSQL::networksDbWatcher()
  397. {
  398. PGconn *conn = PQconnectdb(_path.c_str());
  399. if (PQstatus(conn) == CONNECTION_BAD) {
  400. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  401. PQfinish(conn);
  402. exit(1);
  403. }
  404. initializeNetworks(conn);
  405. char buf[11] = {0};
  406. std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
  407. PGresult *res = PQexec(conn, cmd.c_str());
  408. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  409. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  410. PQclear(res);
  411. PQfinish(conn);
  412. exit(1);
  413. }
  414. PQclear(res); res = NULL;
  415. while(_run == 1) {
  416. if (PQstatus(conn) != CONNECTION_OK) {
  417. fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
  418. exit(-1);
  419. }
  420. PGnotify *notify = NULL;
  421. PQconsumeInput(conn);
  422. while ((notify = PQnotifies(conn)) != NULL) {
  423. fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  424. try {
  425. json tmp(json::parse(notify->extra));
  426. json &ov = tmp["old_val"];
  427. json &nv = tmp["new_val"];
  428. json oldConfig, newConfig;
  429. if (ov.is_object()) oldConfig = ov;
  430. if (nv.is_object()) newConfig = nv;
  431. if (oldConfig.is_object()||newConfig.is_object()) {
  432. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  433. }
  434. } catch (...) {} // ignore bad records
  435. free(notify);
  436. }
  437. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  438. }
  439. PQfinish(conn);
  440. conn = NULL;
  441. }
  442. void PostgreSQL::commitThread()
  443. {
  444. json *config = nullptr;
  445. while(_commitQueue.get(config)&(_run == 1)) {
  446. if (!config) {
  447. continue;
  448. }
  449. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  450. }
  451. }
  452. void PostgreSQL::onlineNotificationThread()
  453. {
  454. PGconn *conn = PQconnectdb(_path.c_str());
  455. if (PQstatus(conn) == CONNECTION_BAD) {
  456. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  457. PQfinish(conn);
  458. exit(1);
  459. }
  460. _connected = 1;
  461. int64_t lastUpdatedNetworkStatus = 0;
  462. std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative;
  463. while (_run == 1) {
  464. if (PQstatus(conn) != CONNECTION_OK) {
  465. fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres.");
  466. exit(-1);
  467. }
  468. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  469. {
  470. std::lock_guard<std::mutex> l(_lastOnline_l);
  471. lastOnline.swap(_lastOnline);
  472. }
  473. PGresult *res = NULL;
  474. int qCount = 0;
  475. if (!lastOnline.empty()) {
  476. fprintf(stderr, "Last Online Update\n");
  477. res = PQexec(conn, "BEGIN");
  478. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  479. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  480. PQclear(res);
  481. exit(1);
  482. }
  483. PQclear(res);
  484. }
  485. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  486. lastOnlineCumulative[i->first] = i->second.first;
  487. char nwidTmp[64];
  488. char memTmp[64];
  489. char ipTmp[64];
  490. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", i->first.first);
  491. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  492. std::string networkId(nwidTmp);
  493. std::string memberId(memTmp);
  494. int64_t ts = i->second.first;
  495. std::string ipAddr = i->second.second.toIpString(ipTmp);
  496. const char *values[4] = {
  497. networkId.c_str(),
  498. memberId.c_str(),
  499. std::to_string(ts).c_str(),
  500. ipAddr.c_str()
  501. };
  502. res = PQexecParams(conn,
  503. "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ($1, $2, $3, $4)"
  504. "ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated",
  505. 8, // number of parameters
  506. NULL, // oid field. ignore
  507. values, // values for substitution
  508. NULL, // lengths in bytes of each value
  509. NULL,
  510. 0);
  511. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  512. fprintf(stderr, "Error on Member Status upsert: %s\n", PQresultErrorMessage(res));
  513. PQclear(res);
  514. PQexec(conn, "ROLLBACK");
  515. exit(1);
  516. }
  517. PQclear(res);
  518. if ((++qCount) == 1024) {
  519. res = PQexec(conn, "COMMIT");
  520. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  521. fprintf(stderr, "ERROR: Error on commit (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  522. PQclear(res);
  523. PQexec(conn, "ROLLBACK");
  524. exit(1);
  525. }
  526. PQclear(res);
  527. res = PQexec(conn, "BEGIN");
  528. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  529. fprintf(stderr, "ERROR: Error on BEGIN (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  530. PQclear(res);
  531. exit(1);
  532. }
  533. PQclear(res);
  534. qCount = 0;
  535. }
  536. }
  537. if (qCount > 0) {
  538. fprintf(stderr, "qCount is %d\n", qCount);
  539. res = PQexec(conn, "COMMIT");
  540. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  541. fprintf(stderr, "ERROR: Error on commit (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  542. PQclear(res);
  543. PQexec(conn, "ROLLBACK");
  544. exit(1);
  545. }
  546. PQclear(res);
  547. }
  548. const int64_t now = OSUtils::now();
  549. if ((now - lastUpdatedNetworkStatus) > 10000) {
  550. lastUpdatedNetworkStatus = now;
  551. std::vector<std::pair<uint64_t, std::shared_ptr<_Network>>> networks;
  552. {
  553. std::lock_guard<std::mutex> l(_networks_l);
  554. for (auto i = _networks.begin(); i != _networks.end(); ++i) {
  555. networks.push_back(*i);
  556. }
  557. }
  558. int nCount = 0;
  559. if (!networks.empty()) {
  560. fprintf(stderr, "Network update");
  561. res = PQexec(conn, "BEGIN");
  562. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  563. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  564. PQclear(res);
  565. exit(1);
  566. }
  567. PQclear(res);
  568. }
  569. for (auto i = networks.begin(); i != networks.end(); ++i) {
  570. char tmp[64];
  571. Utils::hex(i->first, tmp);
  572. std::string networkId(tmp);
  573. uint64_t authMemberCount = 0;
  574. uint64_t totalMemberCount = 0;
  575. uint64_t onlineMemberCount = 0;
  576. uint64_t bridgeCount = 0;
  577. uint64_t ts = now;
  578. {
  579. std::lock_guard<std::mutex> l2(i->second->lock);
  580. authMemberCount = i->second->authorizedMembers.size();
  581. totalMemberCount = i->second->members.size();
  582. bridgeCount = i->second->activeBridgeMembers.size();
  583. for (auto m=i->second->members.begin(); m != i->second->members.end(); ++m) {
  584. auto lo = lastOnlineCumulative.find(std::pair<uint64_t,uint64_t>(i->first, m->first));
  585. if (lo != lastOnlineCumulative.end()) {
  586. if ((now - lo->second) <= (ZT_NETWORK_AUTOCONF_DELAY * 2)) {
  587. ++onlineMemberCount;
  588. } else {
  589. lastOnlineCumulative.erase(lo);
  590. }
  591. }
  592. }
  593. }
  594. const char *values[6] = {
  595. networkId.c_str(),
  596. std::to_string(bridgeCount).c_str(),
  597. std::to_string(authMemberCount).c_str(),
  598. std::to_string(onlineMemberCount).c_str(),
  599. std::to_string(totalMemberCount).c_str(),
  600. std::to_string(ts).c_str()
  601. };
  602. res = PQexecParams(conn, "INSERT INTO ztc_network_status (network_id, bridge_count, authorized_member_count, "
  603. "online_member_count, total_member_count, last_modified) VALUES ($1, $2, $3, $4, $5, $6) "
  604. "ON CONFLICT (network_id) DO UPDATE SET bridge_count = EXCLUDED.bridge_count, "
  605. "authorized_member_count = EXCLUDED.authorized_member_count, online_member_count = EXCDLUDED.online_member_count, "
  606. "total_member_count = EXCLUDED.total_member_count, last_modified = EXCLUDED.last_modified",
  607. 6,
  608. NULL,
  609. values,
  610. NULL,
  611. NULL,
  612. 0);
  613. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  614. fprintf(stderr, "ERROR: Error on Network Satus upsert (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  615. PQclear(res);
  616. PQexec(conn, "ROLLBACK");
  617. exit(1);
  618. }
  619. if ((++nCount) == 1024) {
  620. res = PQexec(conn, "COMMIT");
  621. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  622. fprintf(stderr, "ERROR: Error on COMMIT (onlineNotificationThread): %s\n" , PQresultErrorMessage(res));
  623. PQclear(res);
  624. PQexec(conn, "ROLLBACK");
  625. exit(1);
  626. }
  627. res = PQexec(conn, "BEGIN");
  628. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  629. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  630. PQclear(res);
  631. exit(1);
  632. }
  633. nCount = 0;
  634. }
  635. }
  636. if (nCount > 0) {
  637. fprintf(stderr, "nCount is %d\n", nCount);
  638. res = PQexec(conn, "COMMIT");
  639. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  640. fprintf(stderr, "ERROR: Error on COMMIT (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  641. PQclear(res);
  642. PQexec(conn, "ROLLBACK");
  643. exit(1);
  644. }
  645. }
  646. }
  647. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  648. }
  649. PQfinish(conn);
  650. }
  651. #endif //ZT_CONTROLLER_USE_LIBPQ