PostgreSQL.cpp 39 KB

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