PostgreSQL.cpp 35 KB

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