2
0

PostgreSQL.cpp 36 KB

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