2
0

PostgreSQL.cpp 37 KB

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