PostgreSQL.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  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. #include <sstream>
  24. using json = nlohmann::json;
  25. namespace {
  26. static const char *_timestr()
  27. {
  28. time_t t = time(0);
  29. char *ts = ctime(&t);
  30. char *p = ts;
  31. if (!p)
  32. return "";
  33. while (*p) {
  34. if (*p == '\n') {
  35. *p = (char)0;
  36. break;
  37. }
  38. ++p;
  39. }
  40. return ts;
  41. }
  42. std::string join(const std::vector<std::string> &elements, const char * const separator)
  43. {
  44. switch(elements.size()) {
  45. case 0:
  46. return "";
  47. case 1:
  48. return elements[0];
  49. default:
  50. std::ostringstream os;
  51. std::copy(elements.begin(), elements.end()-1, std::ostream_iterator<std::string>(os, separator));
  52. os << *elements.rbegin();
  53. return os.str();
  54. }
  55. }
  56. }
  57. using namespace ZeroTier;
  58. PostgreSQL::PostgreSQL(EmbeddedNetworkController *const nc, const Identity &myId, const char *path)
  59. : DB(nc, myId, path)
  60. , _ready(0)
  61. , _connected(1)
  62. , _run(1)
  63. , _waitNoticePrinted(false)
  64. {
  65. _connString = std::string(path);
  66. _readyLock.lock();
  67. _heartbeatThread = std::thread(&PostgreSQL::heartbeat, this);
  68. _membersDbWatcher = std::thread(&PostgreSQL::membersDbWatcher, this);
  69. _networksDbWatcher = std::thread(&PostgreSQL::networksDbWatcher, this);
  70. for (int i = 0; i < ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS; ++i) {
  71. _commitThread[i] = std::thread(&PostgreSQL::commitThread, this);
  72. }
  73. _onlineNotificationThread = std::thread(&PostgreSQL::onlineNotificationThread, this);
  74. }
  75. PostgreSQL::~PostgreSQL()
  76. {
  77. _run = 0;
  78. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  79. _heartbeatThread.join();
  80. _membersDbWatcher.join();
  81. _networksDbWatcher.join();
  82. for (int i = 0; i < ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS; ++i) {
  83. _commitThread[i].join();
  84. }
  85. _onlineNotificationThread.join();
  86. }
  87. bool PostgreSQL::waitForReady()
  88. {
  89. while (_ready < 2) {
  90. if (!_waitNoticePrinted) {
  91. _waitNoticePrinted = true;
  92. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S, ::_timestr(), (unsigned long long)_myAddress.toInt());
  93. }
  94. _readyLock.lock();
  95. _readyLock.unlock();
  96. }
  97. return true;
  98. }
  99. bool PostgreSQL::isReady()
  100. {
  101. return ((_ready == 2)&&(_connected));
  102. }
  103. void PostgreSQL::save(nlohmann::json *orig, nlohmann::json &record)
  104. {
  105. if (!record.is_object()) {
  106. return;
  107. }
  108. waitForReady();
  109. if (orig) {
  110. if (*orig != record) {
  111. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  112. _commitQueue.post(new nlohmann::json(record));
  113. }
  114. } else {
  115. record["revision"] = 1;
  116. _commitQueue.post(new nlohmann::json(record));
  117. }
  118. }
  119. void PostgreSQL::eraseNetwork(const uint64_t networkId)
  120. {
  121. char tmp2[24];
  122. waitForReady();
  123. Utils::hex(networkId, tmp2);
  124. json *tmp = new json();
  125. (*tmp)["id"] = tmp2;
  126. (*tmp)["objtype"] = "_delete_network";
  127. _commitQueue.post(tmp);
  128. }
  129. void PostgreSQL::eraseMember(const uint64_t networkId, const uint64_t memberId)
  130. {
  131. char tmp2[24];
  132. json *tmp = new json();
  133. Utils::hex(networkId, tmp2);
  134. (*tmp)["nwid"] = tmp2;
  135. Utils::hex(memberId, tmp2);
  136. (*tmp)["id"] = tmp2;
  137. (*tmp)["objtype"] = "_delete_member";
  138. _commitQueue.post(tmp);
  139. }
  140. void PostgreSQL::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress)
  141. {
  142. std::lock_guard<std::mutex> l(_lastOnline_l);
  143. std::pair<int64_t, InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId, memberId)];
  144. i.first = OSUtils::now();
  145. if (physicalAddress) {
  146. i.second = physicalAddress;
  147. }
  148. }
  149. void PostgreSQL::initializeNetworks(PGconn *conn)
  150. {
  151. try {
  152. if (PQstatus(conn) != CONNECTION_OK) {
  153. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  154. exit(1);
  155. }
  156. const char *params[1] = {
  157. _myAddressStr.c_str()
  158. };
  159. PGresult *res = PQexecParams(conn, "SELECT id, EXTRACT(EPOCH FROM creation_time AT TIME ZONE 'UTC')*1000, capabilities, "
  160. "enable_broadcast, EXTRACT(EPOCH FROM last_modified AT TIME ZONE 'UTC')*1000, mtu, multicast_limit, name, private, remote_trace_level, "
  161. "remote_trace_target, revision, rules, tags, v4_assign_mode, v6_assign_mode FROM ztc_network "
  162. "WHERE deleted = false AND controller_id = $1",
  163. 1,
  164. NULL,
  165. params,
  166. NULL,
  167. NULL,
  168. 0);
  169. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  170. fprintf(stderr, "Networks Initialization Failed: %s", PQerrorMessage(conn));
  171. PQclear(res);
  172. exit(1);
  173. }
  174. int numRows = PQntuples(res);
  175. for (int i = 0; i < numRows; ++i) {
  176. json empty;
  177. json config;
  178. const char *nwidparam[1] = {
  179. PQgetvalue(res, i, 0)
  180. };
  181. config["id"] = PQgetvalue(res, i, 0);
  182. config["nwid"] = PQgetvalue(res, i, 0);
  183. config["creationTime"] = std::stoull(PQgetvalue(res, i, 1));
  184. config["capabilities"] = json::parse(PQgetvalue(res, i, 2));
  185. config["enableBroadcast"] = (strcmp(PQgetvalue(res, i, 3),"t")==0);
  186. config["lastModified"] = std::stoull(PQgetvalue(res, i, 4));
  187. config["mtu"] = std::stoi(PQgetvalue(res, i, 5));
  188. config["multicastLimit"] = std::stoi(PQgetvalue(res, i, 6));
  189. config["name"] = PQgetvalue(res, i, 7);
  190. config["private"] = (strcmp(PQgetvalue(res, i, 8),"t")==0);
  191. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
  192. config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
  193. config["revision"] = std::stoull(PQgetvalue(res, i, 11));
  194. config["rules"] = json::parse(PQgetvalue(res, i, 12));
  195. config["tags"] = json::parse(PQgetvalue(res, i, 13));
  196. config["v4AssignMode"] = json::parse(PQgetvalue(res, i, 14));
  197. config["v6AssignMode"] = json::parse(PQgetvalue(res, i, 15));
  198. config["objtype"] = "network";
  199. config["ipAssignmentPools"] = json::array();
  200. config["routes"] = json::array();
  201. PGresult *r2 = PQexecParams(conn,
  202. "SELECT host(ip_range_start), host(ip_range_end) FROM ztc_network_assignment_pool WHERE network_id = $1",
  203. 1,
  204. NULL,
  205. nwidparam,
  206. NULL,
  207. NULL,
  208. 0);
  209. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  210. fprintf(stderr, "ERROR: Error retreiving IP pools for network: %s\n", PQresultErrorMessage(r2));
  211. PQclear(r2);
  212. PQclear(res);
  213. exit(1);
  214. }
  215. int n = PQntuples(r2);
  216. for (int j = 0; j < n; ++j) {
  217. json ip;
  218. ip["ipRangeStart"] = PQgetvalue(r2, j, 0);
  219. ip["ipRangeEnd"] = PQgetvalue(r2, j, 1);
  220. config["ipAssignmentPools"].push_back(ip);
  221. }
  222. PQclear(r2);
  223. r2 = PQexecParams(conn,
  224. "SELECT host(address), bits, host(via) FROM ztc_network_route WHERE network_id = $1",
  225. 1,
  226. NULL,
  227. nwidparam,
  228. NULL,
  229. NULL,
  230. 0);
  231. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  232. fprintf(stderr, "ERROR: Error retreiving routes for network: %s\n", PQresultErrorMessage(r2));
  233. PQclear(r2);
  234. PQclear(res);
  235. exit(1);
  236. }
  237. n = PQntuples(r2);
  238. for (int j = 0; j < n; ++j) {
  239. std::string addr = PQgetvalue(r2, j, 0);
  240. std::string bits = PQgetvalue(r2, j, 1);
  241. std::string via = PQgetvalue(r2, j, 2);
  242. fprintf(stderr, "via: %s", via.c_str());
  243. json route;
  244. route["target"] = addr + "/" + bits;
  245. if (via == "NULL") {
  246. route["via"] = nullptr;
  247. } else {
  248. route["via"] = via;
  249. }
  250. config["routes"].push_back(route);
  251. }
  252. PQclear(r2);
  253. _networkChanged(empty, config, false);
  254. }
  255. PQclear(res);
  256. if (++this->_ready == 2) {
  257. if (_waitNoticePrinted) {
  258. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  259. }
  260. _readyLock.unlock();
  261. }
  262. } catch (std::exception &e) {
  263. fprintf(stderr, "ERROR: Error initializing networks: %s", e.what());
  264. exit(-1);
  265. }
  266. }
  267. void PostgreSQL::initializeMembers(PGconn *conn)
  268. {
  269. try {
  270. if (PQstatus(conn) != CONNECTION_OK) {
  271. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  272. exit(1);
  273. }
  274. const char *params[1] = {
  275. _myAddressStr.c_str()
  276. };
  277. PGresult *res = PQexecParams(conn,
  278. "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, "
  279. " EXTRACT(EPOCH FROM m.last_authorized_time AT TIME ZONE 'UTC')*1000, "
  280. " EXTRACT(EPOCH FROM m.last_deauthorized_time AT TIME ZONE 'UTC')*1000, "
  281. " m.remote_trace_level, m.remote_trace_target, m.tags, m.v_major, m.v_minor, m.v_rev, m.v_proto, "
  282. " m.no_auto_assign_ips, m.revision "
  283. "FROM ztc_member m "
  284. "INNER JOIN ztc_network n "
  285. " ON n.id = m.network_id "
  286. "WHERE n.controller_id = $1 AND m.deleted = false",
  287. 1,
  288. NULL,
  289. params,
  290. NULL,
  291. NULL,
  292. 0);
  293. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  294. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  295. PQclear(res);
  296. exit(1);
  297. }
  298. int numRows = PQntuples(res);
  299. for (int i = 0; i < numRows; ++i) {
  300. json empty;
  301. json config;
  302. std::string memberId(PQgetvalue(res, i, 0));
  303. std::string networkId(PQgetvalue(res, i, 1));
  304. std::string ctime = PQgetvalue(res, i, 5);
  305. config["id"] = memberId;
  306. config["nwid"] = networkId;
  307. config["activeBridge"] = (strcmp(PQgetvalue(res, i, 2), "t") == 0);
  308. config["authorized"] = (strcmp(PQgetvalue(res, i, 3), "t") == 0);
  309. config["capabilities"] = json::parse(PQgetvalue(res, i, 4));
  310. config["creationTime"] = std::stoull(PQgetvalue(res, i, 5));
  311. config["identity"] = PQgetvalue(res, i, 6);
  312. config["lastAuthorizedTime"] = std::stoull(PQgetvalue(res, i, 7));
  313. config["lastDeauthorizedTime"] = std::stoull(PQgetvalue(res, i, 8));
  314. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
  315. config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
  316. config["tags"] = json::parse(PQgetvalue(res, i, 11));
  317. config["vMajor"] = std::stoi(PQgetvalue(res, i, 12));
  318. config["vMinor"] = std::stoi(PQgetvalue(res, i, 13));
  319. config["vRev"] = std::stoi(PQgetvalue(res, i, 14));
  320. config["vProto"] = std::stoi(PQgetvalue(res, i, 15));
  321. config["noAutoAssignIps"] = (strcmp(PQgetvalue(res, i, 16), "t") == 0);
  322. config["revision"] = std::stoull(PQgetvalue(res, i, 17));
  323. config["objtype"] = "member";
  324. config["ipAssignments"] = json::array();
  325. const char *p2[2] = {
  326. memberId.c_str(),
  327. networkId.c_str()
  328. };
  329. PGresult *r2 = PQexecParams(conn,
  330. "SELECT address FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  331. 2,
  332. NULL,
  333. p2,
  334. NULL,
  335. NULL,
  336. 0);
  337. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  338. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  339. PQclear(r2);
  340. PQclear(res);
  341. exit(1);
  342. }
  343. int n = PQntuples(r2);
  344. for (int j = 0; j < n; ++j) {
  345. config["ipAssignments"].push_back(PQgetvalue(r2, j, 0));
  346. }
  347. _memberChanged(empty, config, false);
  348. }
  349. PQclear(res);
  350. if (++this->_ready == 2) {
  351. if (_waitNoticePrinted) {
  352. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  353. }
  354. _readyLock.unlock();
  355. }
  356. } catch (std::exception &e) {
  357. fprintf(stderr, "ERROR: Error initializing members: %s\n", e.what());
  358. exit(-1);
  359. }
  360. }
  361. void PostgreSQL::heartbeat()
  362. {
  363. char publicId[1024];
  364. char hostnameTmp[1024];
  365. _myId.toString(false,publicId);
  366. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  367. hostnameTmp[0] = (char)0;
  368. } else {
  369. for (int i = 0; i < sizeof(hostnameTmp); ++i) {
  370. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  371. hostnameTmp[i] = (char)0;
  372. break;
  373. }
  374. }
  375. }
  376. const char *controllerId = _myAddressStr.c_str();
  377. const char *publicIdentity = publicId;
  378. const char *hostname = hostnameTmp;
  379. PGconn *conn = PQconnectdb(_path.c_str());
  380. if (PQstatus(conn) == CONNECTION_BAD) {
  381. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  382. PQfinish(conn);
  383. exit(1);
  384. }
  385. while (_run == 1) {
  386. if(PQstatus(conn) != CONNECTION_OK) {
  387. PQfinish(conn);
  388. conn = PQconnectdb(_path.c_str());
  389. }
  390. if (conn) {
  391. const char *values[8] = {
  392. controllerId,
  393. hostname,
  394. std::to_string(OSUtils::now()).c_str(),
  395. publicIdentity,
  396. std::to_string(ZEROTIER_ONE_VERSION_MAJOR).c_str(),
  397. std::to_string(ZEROTIER_ONE_VERSION_MINOR).c_str(),
  398. std::to_string(ZEROTIER_ONE_VERSION_REVISION).c_str(),
  399. std::to_string(ZEROTIER_ONE_VERSION_BUILD).c_str()
  400. };
  401. int lengths[8] = {
  402. (int)strlen(values[0]),
  403. (int)strlen(values[1]),
  404. (int)strlen(values[2]),
  405. (int)strlen(values[3]),
  406. (int)strlen(values[4]),
  407. (int)strlen(values[5]),
  408. (int)strlen(values[6]),
  409. (int)strlen(values[7])
  410. };
  411. int binary[8] = {0,0,0,0,0,0,0,0};
  412. PGresult *res = PQexecParams(conn,
  413. "INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build) "
  414. "VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8) "
  415. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  416. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  417. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev",
  418. 8, // number of parameters
  419. NULL, // oid field. ignore
  420. values, // values for substitution
  421. lengths, // lengths in bytes of each value
  422. binary, // binary?
  423. 0);
  424. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  425. fprintf(stderr, "Heartbeat Update Failed: %s\n", PQresultErrorMessage(res));
  426. }
  427. PQclear(res);
  428. }
  429. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  430. }
  431. PQfinish(conn);
  432. conn = NULL;
  433. }
  434. void PostgreSQL::membersDbWatcher()
  435. {
  436. PGconn *conn = PQconnectdb(_path.c_str());
  437. if (PQstatus(conn) == CONNECTION_BAD) {
  438. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  439. PQfinish(conn);
  440. exit(1);
  441. }
  442. initializeMembers(conn);
  443. char buf[11] = {0};
  444. std::string cmd = "LISTEN member_" + std::string(_myAddress.toString(buf));
  445. PGresult *res = PQexec(conn, cmd.c_str());
  446. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  447. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  448. PQclear(res);
  449. PQfinish(conn);
  450. exit(1);
  451. }
  452. PQclear(res); res = NULL;
  453. while(_run == 1) {
  454. if (PQstatus(conn) != CONNECTION_OK) {
  455. fprintf(stderr, "ERROR: Member Watcher lost connection to Postgres.");
  456. exit(-1);
  457. }
  458. PGnotify *notify = NULL;
  459. PQconsumeInput(conn);
  460. while ((notify = PQnotifies(conn)) != NULL) {
  461. fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  462. try {
  463. json tmp(json::parse(notify->extra));
  464. json &ov = tmp["old_val"];
  465. json &nv = tmp["new_val"];
  466. json oldConfig, newConfig;
  467. if (ov.is_object()) oldConfig = ov;
  468. if (nv.is_object()) newConfig = nv;
  469. if (oldConfig.is_object() || newConfig.is_object()) {
  470. _memberChanged(oldConfig,newConfig,(this->_ready>=2));
  471. }
  472. } catch (...) {} // ignore bad records
  473. free(notify);
  474. }
  475. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  476. }
  477. PQfinish(conn);
  478. conn = NULL;
  479. }
  480. void PostgreSQL::networksDbWatcher()
  481. {
  482. PGconn *conn = PQconnectdb(_path.c_str());
  483. if (PQstatus(conn) == CONNECTION_BAD) {
  484. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  485. PQfinish(conn);
  486. exit(1);
  487. }
  488. initializeNetworks(conn);
  489. char buf[11] = {0};
  490. std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
  491. PGresult *res = PQexec(conn, cmd.c_str());
  492. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  493. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  494. PQclear(res);
  495. PQfinish(conn);
  496. exit(1);
  497. }
  498. PQclear(res); res = NULL;
  499. while(_run == 1) {
  500. if (PQstatus(conn) != CONNECTION_OK) {
  501. fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
  502. exit(-1);
  503. }
  504. PGnotify *notify = NULL;
  505. PQconsumeInput(conn);
  506. while ((notify = PQnotifies(conn)) != NULL) {
  507. fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  508. try {
  509. json tmp(json::parse(notify->extra));
  510. json &ov = tmp["old_val"];
  511. json &nv = tmp["new_val"];
  512. json oldConfig, newConfig;
  513. if (ov.is_object()) oldConfig = ov;
  514. if (nv.is_object()) newConfig = nv;
  515. if (oldConfig.is_object()||newConfig.is_object()) {
  516. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  517. }
  518. } catch (...) {} // ignore bad records
  519. free(notify);
  520. }
  521. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  522. }
  523. PQfinish(conn);
  524. conn = NULL;
  525. }
  526. void PostgreSQL::commitThread()
  527. {
  528. PGconn *conn = PQconnectdb(_path.c_str());
  529. if (PQstatus(conn) == CONNECTION_BAD) {
  530. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  531. PQfinish(conn);
  532. exit(1);
  533. }
  534. json *config = nullptr;
  535. while(_commitQueue.get(config)&(_run == 1)) {
  536. if (!config) {
  537. continue;
  538. }
  539. if (PQstatus(conn) == CONNECTION_BAD) {
  540. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  541. PQfinish(conn);
  542. exit(1);
  543. }
  544. try {
  545. const std::string objtype = (*config)["objtype"];
  546. if (objtype == "member") {
  547. try {
  548. std::string memberId = (*config)["id"];
  549. std::string networkId = (*config)["nwid"];
  550. std::string identity = (*config)["identity"];
  551. std::string target = "NULL";
  552. if (!(*config)["remoteTraceTarget"].is_null()) {
  553. target = (*config)["remoteTraceTarget"];
  554. }
  555. const char *values[19] = {
  556. memberId.c_str(),
  557. networkId.c_str(),
  558. ((*config)["activeBridge"] ? "true" : "false"),
  559. ((*config)["authorized"] ? "true" : "false"),
  560. OSUtils::jsonDump((*config)["capabilities"], -1).c_str(),
  561. identity.c_str(),
  562. std::to_string((long long)(*config)["lastAuthorizedTime"]).c_str(),
  563. std::to_string((long long)(*config)["lastDeauthorizedTime"]).c_str(),
  564. ((*config)["noAutoAssignIps"] ? "true" : "false"),
  565. std::to_string((int)(*config)["remoteTraceLevel"]).c_str(),
  566. (target == "NULL") ? NULL : target.c_str(),
  567. std::to_string((unsigned long long)(*config)["revision"]).c_str(),
  568. OSUtils::jsonDump((*config)["tags"], -1).c_str(),
  569. std::to_string((int)(*config)["vMajor"]).c_str(),
  570. std::to_string((int)(*config)["vMinor"]).c_str(),
  571. std::to_string((int)(*config)["vRev"]).c_str(),
  572. std::to_string((int)(*config)["vProto"]).c_str()
  573. };
  574. PGresult *res = PQexecParams(conn,
  575. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  576. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  577. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  578. "VALUES ($1, $2, $3, $4, $5, $6, "
  579. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  580. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  581. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  582. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  583. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  584. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  585. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  586. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  587. 17,
  588. NULL,
  589. values,
  590. NULL,
  591. NULL,
  592. 0);
  593. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  594. fprintf(stderr, "ERROR: Error updating member: %s\n", PQresultErrorMessage(res));
  595. fprintf(stderr, "%s", OSUtils::jsonDump(*config, 2).c_str());
  596. PQclear(res);
  597. continue;
  598. }
  599. PQclear(res);
  600. res = PQexec(conn, "BEGIN");
  601. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  602. fprintf(stderr, "ERROR: Error beginning transaction: %s\n", PQresultErrorMessage(res));
  603. PQclear(res);
  604. continue;
  605. }
  606. PQclear(res);
  607. const char *v2[2] = {
  608. memberId.c_str(),
  609. networkId.c_str()
  610. };
  611. res = PQexecParams(conn,
  612. "DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  613. 2,
  614. NULL,
  615. v2,
  616. NULL,
  617. NULL,
  618. 0);
  619. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  620. fprintf(stderr, "ERROR: Error updating IP address assignments: %s\n", PQresultErrorMessage(res));
  621. PQclear(res);
  622. PQclear(PQexec(conn, "ROLLBACK"));;
  623. continue;
  624. }
  625. PQclear(res);
  626. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  627. std::string addr = *i;
  628. const char *v3[3] = {
  629. memberId.c_str(),
  630. networkId.c_str(),
  631. addr.c_str()
  632. };
  633. res = PQexecParams(conn,
  634. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3)",
  635. 3,
  636. NULL,
  637. v3,
  638. NULL,
  639. NULL,
  640. 0);
  641. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  642. fprintf(stderr, "ERROR: Error setting IP addresses for member: %s\n", PQresultErrorMessage(res));
  643. PQclear(res);
  644. PQclear(PQexec(conn, "ROLLBACK"));
  645. continue;
  646. }
  647. }
  648. res = PQexec(conn, "COMMIT");
  649. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  650. fprintf(stderr, "ERROR: Error committing ip address data: %s\n", PQresultErrorMessage(res));
  651. }
  652. PQclear(res);
  653. } catch (std::exception &e) {
  654. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  655. }
  656. } else if (objtype == "network") {
  657. try {
  658. std::string id = (*config)["id"];
  659. std::string controllerId = _myAddressStr.c_str();
  660. std::string name = (*config)["name"];
  661. std::string remoteTraceTarget("NULL");
  662. if (!(*config)["remoteTraceTarget"].is_null()) {
  663. remoteTraceTarget = (*config)["remoteTraceTarget"];
  664. }
  665. std::string rulesSource = (*config)["rulesSource"];
  666. const char *values[16] = {
  667. id.c_str(),
  668. controllerId.c_str(),
  669. OSUtils::jsonDump((*config)["capabilitles"], -1).c_str(),
  670. ((*config)["enableBroadcast"] ? "true" : "false"),
  671. std::to_string(OSUtils::now()).c_str(),
  672. std::to_string((int)(*config)["mtu"]).c_str(),
  673. std::to_string((int)(*config)["multicastLimit"]).c_str(),
  674. name.c_str(),
  675. ((*config)["private"] ? "true" : "false"),
  676. std::to_string((int)(*config)["remoteTraceLevel"]).c_str(),
  677. (remoteTraceTarget == "NULL" ? NULL : remoteTraceTarget.c_str()),
  678. OSUtils::jsonDump((*config)["rules"], -1).c_str(),
  679. rulesSource.c_str(),
  680. OSUtils::jsonDump((*config)["tags"], -1).c_str(),
  681. OSUtils::jsonDump((*config)["v4AssignMode"],-1).c_str(),
  682. OSUtils::jsonDump((*config)["v6AssignMode"], -1).c_str(),
  683. };
  684. PGresult *res = PQexecParams(conn,
  685. "UPDATE ztc_network SET controller_id = $2, capabilities = $3, enable_broadcast = $4, "
  686. "last_updated = $5, mtu = $6, multicast_limit = $7, name = $8, private = $9, "
  687. "remote_trace_level = $10, remote_trace_target = $11, rules = $12, rules_source = $13, "
  688. "tags = $14, v4_assign_mode = $15, v6_assign_mode = $16 "
  689. "WHERE id = $1",
  690. 16,
  691. NULL,
  692. values,
  693. NULL,
  694. NULL,
  695. 0);
  696. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  697. fprintf(stderr, "ERROR: Error updating network record: %s\n", PQresultErrorMessage(res));
  698. PQclear(res);
  699. continue;
  700. }
  701. PQclear(res);
  702. res = PQexec(conn, "BEGIN");
  703. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  704. fprintf(stderr, "ERROR: Error beginnning transaction: %s\n", PQresultErrorMessage(res));
  705. PQclear(res);
  706. continue;
  707. }
  708. PQclear(res);
  709. const char *params[1] = {
  710. id.c_str()
  711. };
  712. res = PQexecParams(conn,
  713. "DELETE FROM ztc_network_assignment_pool WHERE network_id = $1",
  714. 1,
  715. NULL,
  716. params,
  717. NULL,
  718. NULL,
  719. 0);
  720. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  721. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  722. PQclear(res);
  723. PQclear(PQexec(conn, "ROLLBACK"));
  724. continue;
  725. }
  726. PQclear(res);
  727. auto pool = (*config)["ipAssignmentPools"];
  728. bool err = false;
  729. for (auto i = pool.begin(); i != pool.end(); ++i) {
  730. std::string start = (*i)["ipRangeStart"];
  731. std::string end = (*i)["ipRangeEnd"];
  732. const char *p[3] = {
  733. id.c_str(),
  734. start.c_str(),
  735. end.c_str()
  736. };
  737. res = PQexecParams(conn,
  738. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  739. "VALUES ($1, $2, $3)",
  740. 3,
  741. NULL,
  742. p,
  743. NULL,
  744. NULL,
  745. 0);
  746. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  747. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  748. PQclear(res);
  749. err = true;
  750. break;
  751. }
  752. PQclear(res);
  753. }
  754. if (err) {
  755. PQclear(PQexec(conn, "ROLLBACK"));
  756. continue;
  757. }
  758. res = PQexecParams(conn,
  759. "DELETE FROM ztc_network_route WHERE network_id = $1",
  760. 1,
  761. NULL,
  762. params,
  763. NULL,
  764. NULL,
  765. 0);
  766. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  767. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  768. PQclear(res);
  769. PQclear(PQexec(conn, "ROLLBACK"));
  770. continue;
  771. }
  772. auto routes = (*config)["routes"];
  773. err = false;
  774. for (auto i = routes.begin(); i != routes.end(); ++i) {
  775. std::string t = (*i)["target"];
  776. std::vector<std::string> target;
  777. std::istringstream f(t);
  778. std::string s;
  779. while(std::getline(f, s, '/')) {
  780. target.push_back(s);
  781. }
  782. if (target.empty() || target.size() != 2) {
  783. continue;
  784. }
  785. std::string targetAddr = target[0];
  786. std::string targetBits = target[1];
  787. std::string via = "NULL";
  788. if (!(*i)["via"].is_null()) {
  789. via = (*i)["via"];
  790. }
  791. const char *p[4] = {
  792. id.c_str(),
  793. targetAddr.c_str(),
  794. targetBits.c_str(),
  795. (via == "NULL" ? NULL : via.c_str()),
  796. };
  797. res = PQexecParams(conn,
  798. "INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  799. 4,
  800. NULL,
  801. p,
  802. NULL,
  803. NULL,
  804. 0);
  805. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  806. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  807. PQclear(res);
  808. err = true;
  809. break;
  810. }
  811. PQclear(res);
  812. }
  813. if (err) {
  814. PQclear(PQexec(conn, "ROLLBAcK"));
  815. continue;
  816. }
  817. res = PQexec(conn, "COMMIT");
  818. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  819. fprintf(stderr, "ERROR: Error committing network update: %s\n", PQresultErrorMessage(res));
  820. }
  821. PQclear(res);
  822. } catch (std::exception &e) {
  823. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  824. }
  825. } else if (objtype == "trace") {
  826. fprintf(stderr, "ERROR: Trace not yet implemented");
  827. } else if (objtype == "_delete_network") {
  828. try {
  829. std::string networkId = (*config)["nwid"];
  830. const char *values[1] = {
  831. networkId.c_str()
  832. };
  833. PGresult * res = PQexecParams(conn,
  834. "UPDATE ztc_network SET deleted = true WHERE id = $1",
  835. 1,
  836. NULL,
  837. values,
  838. NULL,
  839. NULL,
  840. 0);
  841. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  842. fprintf(stderr, "ERROR: Error deleting network: %s\n", PQresultErrorMessage(res));
  843. }
  844. PQclear(res);
  845. } catch (std::exception &e) {
  846. fprintf(stderr, "ERROR: Error deleting network: %s\n", e.what());
  847. }
  848. } else if (objtype == "_delete_member") {
  849. try {
  850. std::string memberId = (*config)["id"];
  851. std::string networkId = (*config)["nwid"];
  852. const char *values[2] = {
  853. memberId.c_str(),
  854. networkId.c_str()
  855. };
  856. PGresult *res = PQexecParams(conn,
  857. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  858. 2,
  859. NULL,
  860. values,
  861. NULL,
  862. NULL,
  863. 0);
  864. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  865. fprintf(stderr, "ERROR: Error deleting member: %s\n", PQresultErrorMessage(res));
  866. }
  867. PQclear(res);
  868. } catch (std::exception &e) {
  869. fprintf(stderr, "ERROR: Error deleting member: %s\n", e.what());
  870. }
  871. } else {
  872. fprintf(stderr, "ERROR: unknown objtype");
  873. }
  874. } catch (std::exception &e) {
  875. fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
  876. }
  877. delete config;
  878. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  879. }
  880. PQfinish(conn);
  881. }
  882. void PostgreSQL::onlineNotificationThread()
  883. {
  884. PGconn *conn = PQconnectdb(_path.c_str());
  885. if (PQstatus(conn) == CONNECTION_BAD) {
  886. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  887. PQfinish(conn);
  888. exit(1);
  889. }
  890. _connected = 1;
  891. int64_t lastUpdatedNetworkStatus = 0;
  892. std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative;
  893. while (_run == 1) {
  894. if (PQstatus(conn) != CONNECTION_OK) {
  895. fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres.");
  896. exit(-1);
  897. }
  898. // map used to send notifications to front end
  899. std::unordered_map<std::string, std::vector<std::string>> updateMap;
  900. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  901. {
  902. std::lock_guard<std::mutex> l(_lastOnline_l);
  903. lastOnline.swap(_lastOnline);
  904. }
  905. PGresult *res = NULL;
  906. int qCount = 0;
  907. res = PQexec(conn, "BEGIN");
  908. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  909. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  910. PQclear(res);
  911. exit(1);
  912. }
  913. PQclear(res);
  914. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  915. uint64_t nwid_i = i->first.first;
  916. char nwidTmp[64];
  917. char memTmp[64];
  918. char ipTmp[64];
  919. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  920. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  921. auto found = _networks.find(nwid_i);
  922. if (found == _networks.end()) {
  923. continue; // skip members trying to join non-existant networks
  924. }
  925. lastOnlineCumulative[i->first] = i->second.first;
  926. std::string networkId(nwidTmp);
  927. std::string memberId(memTmp);
  928. std::vector<std::string> &members = updateMap[networkId];
  929. members.push_back(memberId);
  930. int64_t ts = i->second.first;
  931. std::string ipAddr = i->second.second.toIpString(ipTmp);
  932. const char *values[4] = {
  933. networkId.c_str(),
  934. memberId.c_str(),
  935. (ipAddr.empty() ? NULL : ipAddr.c_str()),
  936. std::to_string(ts).c_str(),
  937. };
  938. res = PQexecParams(conn,
  939. "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ($1, $2, $3, TO_TIMESTAMP($4::double precision/1000)) "
  940. "ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated",
  941. 4, // number of parameters
  942. NULL, // oid field. ignore
  943. values, // values for substitution
  944. NULL, // lengths in bytes of each value
  945. NULL,
  946. 0);
  947. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  948. fprintf(stderr, "Error on Member Status upsert: %s\n", PQresultErrorMessage(res));
  949. PQclear(res);
  950. PQclear(PQexec(conn, "ROLLBACK"));
  951. continue;
  952. }
  953. PQclear(res);
  954. if ((++qCount) == 1024) {
  955. res = PQexec(conn, "COMMIT");
  956. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  957. fprintf(stderr, "ERROR: Error on commit (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  958. PQclear(res);
  959. PQclear(PQexec(conn, "ROLLBACK"));
  960. exit(1);
  961. }
  962. PQclear(res);
  963. res = PQexec(conn, "BEGIN");
  964. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  965. fprintf(stderr, "ERROR: Error on BEGIN (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  966. PQclear(res);
  967. exit(1);
  968. }
  969. PQclear(res);
  970. qCount = 0;
  971. }
  972. }
  973. res = PQexec(conn, "COMMIT");
  974. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  975. fprintf(stderr, "ERROR: Error on commit (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  976. PQclear(res);
  977. PQclear(PQexec(conn, "ROLLBACK"));
  978. exit(1);
  979. }
  980. PQclear(res);
  981. const int64_t now = OSUtils::now();
  982. if ((now - lastUpdatedNetworkStatus) > 10000) {
  983. lastUpdatedNetworkStatus = now;
  984. std::vector<std::pair<uint64_t, std::shared_ptr<_Network>>> networks;
  985. {
  986. std::lock_guard<std::mutex> l(_networks_l);
  987. for (auto i = _networks.begin(); i != _networks.end(); ++i) {
  988. networks.push_back(*i);
  989. }
  990. }
  991. int nCount = 0;
  992. res = PQexec(conn, "BEGIN");
  993. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  994. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  995. PQclear(res);
  996. exit(1);
  997. }
  998. PQclear(res);
  999. for (auto i = networks.begin(); i != networks.end(); ++i) {
  1000. char tmp[64];
  1001. Utils::hex(i->first, tmp);
  1002. std::string networkId(tmp);
  1003. std::vector<std::string> &_notUsed = updateMap[networkId];
  1004. (void)_notUsed;
  1005. uint64_t authMemberCount = 0;
  1006. uint64_t totalMemberCount = 0;
  1007. uint64_t onlineMemberCount = 0;
  1008. uint64_t bridgeCount = 0;
  1009. uint64_t ts = now;
  1010. {
  1011. std::lock_guard<std::mutex> l2(i->second->lock);
  1012. authMemberCount = i->second->authorizedMembers.size();
  1013. totalMemberCount = i->second->members.size();
  1014. bridgeCount = i->second->activeBridgeMembers.size();
  1015. for (auto m=i->second->members.begin(); m != i->second->members.end(); ++m) {
  1016. auto lo = lastOnlineCumulative.find(std::pair<uint64_t,uint64_t>(i->first, m->first));
  1017. if (lo != lastOnlineCumulative.end()) {
  1018. if ((now - lo->second) <= (ZT_NETWORK_AUTOCONF_DELAY * 2)) {
  1019. ++onlineMemberCount;
  1020. } else {
  1021. lastOnlineCumulative.erase(lo);
  1022. }
  1023. }
  1024. }
  1025. }
  1026. const char *values[6] = {
  1027. networkId.c_str(),
  1028. std::to_string(bridgeCount).c_str(),
  1029. std::to_string(authMemberCount).c_str(),
  1030. std::to_string(onlineMemberCount).c_str(),
  1031. std::to_string(totalMemberCount).c_str(),
  1032. std::to_string(ts).c_str()
  1033. };
  1034. res = PQexecParams(conn, "INSERT INTO ztc_network_status (network_id, bridge_count, authorized_member_count, "
  1035. "online_member_count, total_member_count, last_modified) VALUES ($1, $2, $3, $4, $5, TO_TIMESTAMP($6::double precision/1000)) "
  1036. "ON CONFLICT (network_id) DO UPDATE SET bridge_count = EXCLUDED.bridge_count, "
  1037. "authorized_member_count = EXCLUDED.authorized_member_count, online_member_count = EXCLUDED.online_member_count, "
  1038. "total_member_count = EXCLUDED.total_member_count, last_modified = EXCLUDED.last_modified",
  1039. 6,
  1040. NULL,
  1041. values,
  1042. NULL,
  1043. NULL,
  1044. 0);
  1045. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1046. fprintf(stderr, "ERROR: Error on Network Status upsert (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1047. PQclear(res);
  1048. PQclear(PQexec(conn, "ROLLBACK"));
  1049. exit(1);
  1050. }
  1051. if ((++nCount) == 1024) {
  1052. res = PQexec(conn, "COMMIT");
  1053. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1054. fprintf(stderr, "ERROR: Error on COMMIT (onlineNotificationThread): %s\n" , PQresultErrorMessage(res));
  1055. PQclear(res);
  1056. PQclear(PQexec(conn, "ROLLBACK"));
  1057. exit(1);
  1058. }
  1059. res = PQexec(conn, "BEGIN");
  1060. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1061. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1062. PQclear(res);
  1063. exit(1);
  1064. }
  1065. nCount = 0;
  1066. }
  1067. }
  1068. res = PQexec(conn, "COMMIT");
  1069. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1070. fprintf(stderr, "ERROR: Error on COMMIT (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1071. PQclear(res);
  1072. PQclear(PQexec(conn, "ROLLBACK"));
  1073. exit(1);
  1074. }
  1075. }
  1076. for (auto it = updateMap.begin(); it != updateMap.end(); ++it) {
  1077. std::string networkId = it->first;
  1078. std::vector<std::string> members = it->second;
  1079. std::stringstream queryBuilder;
  1080. std::string membersStr = ::join(members, ",");
  1081. queryBuilder << "NOTIFY controller, '" << networkId << ":" << membersStr << "'";
  1082. std::string query = queryBuilder.str();
  1083. PGresult *res = PQexec(conn,query.c_str());
  1084. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1085. fprintf(stderr, "ERROR: Error sending NOTIFY: %s\n", PQresultErrorMessage(res));
  1086. }
  1087. PQclear(res);
  1088. }
  1089. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  1090. }
  1091. PQfinish(conn);
  1092. }
  1093. #endif //ZT_CONTROLLER_USE_LIBPQ