PostgreSQL.cpp 37 KB

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