PostgreSQL.cpp 34 KB

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