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. fprintf(stderr, "Updating Member %s-%s\n", networkId.c_str(), memberId.c_str());
  553. if (!(*config)["remoteTraceTarget"].is_null()) {
  554. target = (*config)["remoteTraceTarget"];
  555. }
  556. std::string caps = OSUtils::jsonDump((*config)["capabilities"], -1);
  557. std::string lastAuthTime = std::to_string((long long)(*config)["lastAuthorizedTime"]);
  558. std::string lastDeauthTime = std::to_string((long long)(*config)["lastDeauthorizedTime"]);
  559. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  560. std::string rev = std::to_string((unsigned long long)(*config)["revision"]);
  561. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  562. std::string vmajor = std::to_string((int)(*config)["vMajor"]);
  563. std::string vminor = std::to_string((int)(*config)["vMinor"]);
  564. std::string vrev = std::to_string((int)(*config)["vRev"]);
  565. std::string vproto = std::to_string((int)(*config)["vProto"]);
  566. const char *values[19] = {
  567. memberId.c_str(),
  568. networkId.c_str(),
  569. ((*config)["activeBridge"] ? "true" : "false"),
  570. ((*config)["authorized"] ? "true" : "false"),
  571. caps.c_str(),
  572. identity.c_str(),
  573. lastAuthTime.c_str(),
  574. lastDeauthTime.c_str(),
  575. ((*config)["noAutoAssignIps"] ? "true" : "false"),
  576. rtraceLevel.c_str(),
  577. (target == "NULL") ? NULL : target.c_str(),
  578. rev.c_str(),
  579. tags.c_str(),
  580. vmajor.c_str(),
  581. vminor.c_str(),
  582. vrev.c_str(),
  583. vproto.c_str()
  584. };
  585. PGresult *res = PQexecParams(conn,
  586. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  587. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  588. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  589. "VALUES ($1, $2, $3, $4, $5, $6, "
  590. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  591. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  592. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  593. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  594. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  595. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  596. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  597. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  598. 17,
  599. NULL,
  600. values,
  601. NULL,
  602. NULL,
  603. 0);
  604. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  605. fprintf(stderr, "ERROR: Error updating member: %s\n", PQresultErrorMessage(res));
  606. fprintf(stderr, "%s", OSUtils::jsonDump(*config, 2).c_str());
  607. PQclear(res);
  608. delete config;
  609. config = nullptr;
  610. continue;
  611. }
  612. PQclear(res);
  613. res = PQexec(conn, "BEGIN");
  614. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  615. fprintf(stderr, "ERROR: Error beginning transaction: %s\n", PQresultErrorMessage(res));
  616. PQclear(res);
  617. delete config;
  618. config = nullptr;
  619. continue;
  620. }
  621. PQclear(res);
  622. const char *v2[2] = {
  623. memberId.c_str(),
  624. networkId.c_str()
  625. };
  626. res = PQexecParams(conn,
  627. "DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  628. 2,
  629. NULL,
  630. v2,
  631. NULL,
  632. NULL,
  633. 0);
  634. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  635. fprintf(stderr, "ERROR: Error updating IP address assignments: %s\n", PQresultErrorMessage(res));
  636. PQclear(res);
  637. PQclear(PQexec(conn, "ROLLBACK"));;
  638. delete config;
  639. config = nullptr;
  640. continue;
  641. }
  642. PQclear(res);
  643. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  644. std::string addr = *i;
  645. const char *v3[3] = {
  646. memberId.c_str(),
  647. networkId.c_str(),
  648. addr.c_str()
  649. };
  650. res = PQexecParams(conn,
  651. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3)",
  652. 3,
  653. NULL,
  654. v3,
  655. NULL,
  656. NULL,
  657. 0);
  658. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  659. fprintf(stderr, "ERROR: Error setting IP addresses for member: %s\n", PQresultErrorMessage(res));
  660. PQclear(res);
  661. PQclear(PQexec(conn, "ROLLBACK"));
  662. continue;
  663. }
  664. }
  665. res = PQexec(conn, "COMMIT");
  666. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  667. fprintf(stderr, "ERROR: Error committing ip address data: %s\n", PQresultErrorMessage(res));
  668. }
  669. PQclear(res);
  670. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  671. const uint64_t memberidInt = OSUtils::jsonIntHex((*config)["id"], 0ULL);
  672. if (nwidInt && memberidInt) {
  673. nlohmann::json nwOrig;
  674. nlohmann::json memOrig;
  675. nlohmann::json memNew(*config);
  676. get(nwidInt, nwOrig, memberidInt, memOrig);
  677. _memberChanged(memOrig, memNew, (this->_ready>=2));
  678. } else {
  679. fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %lu-%lu\n", nwidInt, memberidInt);
  680. }
  681. } catch (std::exception &e) {
  682. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  683. }
  684. } else if (objtype == "network") {
  685. try {
  686. std::string id = (*config)["id"];
  687. std::string controllerId = _myAddressStr.c_str();
  688. std::string name = (*config)["name"];
  689. std::string remoteTraceTarget("NULL");
  690. if (!(*config)["remoteTraceTarget"].is_null()) {
  691. remoteTraceTarget = (*config)["remoteTraceTarget"];
  692. }
  693. std::string rulesSource = (*config)["rulesSource"];
  694. std::string caps = OSUtils::jsonDump((*config)["capabilitles"], -1);
  695. std::string now = std::to_string(OSUtils::now());
  696. std::string mtu = std::to_string((int)(*config)["mtu"]);
  697. std::string mcastLimit = std::to_string((int)(*config)["multicastLimit"]);
  698. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  699. std::string rules = OSUtils::jsonDump((*config)["rules"], -1);
  700. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  701. std::string v4mode = OSUtils::jsonDump((*config)["v4AssignMode"],-1);
  702. std::string v6mode = OSUtils::jsonDump((*config)["v6AssignMode"], -1);
  703. bool enableBroadcast = (*config)["enableBroadcast"];
  704. bool isPrivate = (*config)["private"];
  705. const char *values[16] = {
  706. id.c_str(),
  707. controllerId.c_str(),
  708. caps.c_str(),
  709. enableBroadcast ? "true" : "false",
  710. now.c_str(),
  711. mtu.c_str(),
  712. mcastLimit.c_str(),
  713. name.c_str(),
  714. isPrivate ? "true" : "false",
  715. rtraceLevel.c_str(),
  716. (remoteTraceTarget == "NULL" ? NULL : remoteTraceTarget.c_str()),
  717. rules.c_str(),
  718. rulesSource.c_str(),
  719. tags.c_str(),
  720. v4mode.c_str(),
  721. v6mode.c_str(),
  722. };
  723. PGresult *res = PQexecParams(conn,
  724. "UPDATE ztc_network SET controller_id = $2, capabilities = $3, enable_broadcast = $4, "
  725. "last_updated = $5, mtu = $6, multicast_limit = $7, name = $8, private = $9, "
  726. "remote_trace_level = $10, remote_trace_target = $11, rules = $12, rules_source = $13, "
  727. "tags = $14, v4_assign_mode = $15, v6_assign_mode = $16 "
  728. "WHERE id = $1",
  729. 16,
  730. NULL,
  731. values,
  732. NULL,
  733. NULL,
  734. 0);
  735. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  736. fprintf(stderr, "ERROR: Error updating network record: %s\n", PQresultErrorMessage(res));
  737. PQclear(res);
  738. delete config;
  739. config = nullptr;
  740. continue;
  741. }
  742. PQclear(res);
  743. res = PQexec(conn, "BEGIN");
  744. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  745. fprintf(stderr, "ERROR: Error beginnning transaction: %s\n", PQresultErrorMessage(res));
  746. PQclear(res);
  747. delete config;
  748. config = nullptr;
  749. continue;
  750. }
  751. PQclear(res);
  752. const char *params[1] = {
  753. id.c_str()
  754. };
  755. res = PQexecParams(conn,
  756. "DELETE FROM ztc_network_assignment_pool WHERE network_id = $1",
  757. 1,
  758. NULL,
  759. params,
  760. NULL,
  761. NULL,
  762. 0);
  763. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  764. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  765. PQclear(res);
  766. PQclear(PQexec(conn, "ROLLBACK"));
  767. delete config;
  768. config = nullptr;
  769. continue;
  770. }
  771. PQclear(res);
  772. auto pool = (*config)["ipAssignmentPools"];
  773. bool err = false;
  774. for (auto i = pool.begin(); i != pool.end(); ++i) {
  775. std::string start = (*i)["ipRangeStart"];
  776. std::string end = (*i)["ipRangeEnd"];
  777. const char *p[3] = {
  778. id.c_str(),
  779. start.c_str(),
  780. end.c_str()
  781. };
  782. res = PQexecParams(conn,
  783. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  784. "VALUES ($1, $2, $3)",
  785. 3,
  786. NULL,
  787. p,
  788. NULL,
  789. NULL,
  790. 0);
  791. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  792. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  793. PQclear(res);
  794. err = true;
  795. break;
  796. }
  797. PQclear(res);
  798. }
  799. if (err) {
  800. PQclear(PQexec(conn, "ROLLBACK"));
  801. delete config;
  802. config = nullptr;
  803. continue;
  804. }
  805. res = PQexecParams(conn,
  806. "DELETE FROM ztc_network_route WHERE network_id = $1",
  807. 1,
  808. NULL,
  809. params,
  810. NULL,
  811. NULL,
  812. 0);
  813. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  814. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  815. PQclear(res);
  816. PQclear(PQexec(conn, "ROLLBACK"));
  817. delete config;
  818. config = nullptr;
  819. continue;
  820. }
  821. auto routes = (*config)["routes"];
  822. err = false;
  823. for (auto i = routes.begin(); i != routes.end(); ++i) {
  824. std::string t = (*i)["target"];
  825. std::vector<std::string> target;
  826. std::istringstream f(t);
  827. std::string s;
  828. while(std::getline(f, s, '/')) {
  829. target.push_back(s);
  830. }
  831. if (target.empty() || target.size() != 2) {
  832. continue;
  833. }
  834. std::string targetAddr = target[0];
  835. std::string targetBits = target[1];
  836. std::string via = "NULL";
  837. if (!(*i)["via"].is_null()) {
  838. via = (*i)["via"];
  839. }
  840. const char *p[4] = {
  841. id.c_str(),
  842. targetAddr.c_str(),
  843. targetBits.c_str(),
  844. (via == "NULL" ? NULL : via.c_str()),
  845. };
  846. res = PQexecParams(conn,
  847. "INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  848. 4,
  849. NULL,
  850. p,
  851. NULL,
  852. NULL,
  853. 0);
  854. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  855. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  856. PQclear(res);
  857. err = true;
  858. break;
  859. }
  860. PQclear(res);
  861. }
  862. if (err) {
  863. PQclear(PQexec(conn, "ROLLBACK"));
  864. delete config;
  865. config = nullptr;
  866. continue;
  867. }
  868. res = PQexec(conn, "COMMIT");
  869. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  870. fprintf(stderr, "ERROR: Error committing network update: %s\n", PQresultErrorMessage(res));
  871. }
  872. PQclear(res);
  873. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  874. if (nwidInt) {
  875. nlohmann::json nwOrig;
  876. nlohmann::json nwNew(*config);
  877. get(nwidInt, nwOrig);
  878. _networkChanged(nwOrig, nwNew, true);
  879. } else {
  880. fprintf(stderr, "Can't notify network changed: %lu\n", nwidInt);
  881. }
  882. } catch (std::exception &e) {
  883. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  884. }
  885. } else if (objtype == "trace") {
  886. fprintf(stderr, "ERROR: Trace not yet implemented");
  887. } else if (objtype == "_delete_network") {
  888. try {
  889. std::string networkId = (*config)["nwid"];
  890. const char *values[1] = {
  891. networkId.c_str()
  892. };
  893. PGresult * res = PQexecParams(conn,
  894. "UPDATE ztc_network SET deleted = true WHERE id = $1",
  895. 1,
  896. NULL,
  897. values,
  898. NULL,
  899. NULL,
  900. 0);
  901. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  902. fprintf(stderr, "ERROR: Error deleting network: %s\n", PQresultErrorMessage(res));
  903. }
  904. PQclear(res);
  905. } catch (std::exception &e) {
  906. fprintf(stderr, "ERROR: Error deleting network: %s\n", e.what());
  907. }
  908. } else if (objtype == "_delete_member") {
  909. try {
  910. std::string memberId = (*config)["id"];
  911. std::string networkId = (*config)["nwid"];
  912. const char *values[2] = {
  913. memberId.c_str(),
  914. networkId.c_str()
  915. };
  916. PGresult *res = PQexecParams(conn,
  917. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  918. 2,
  919. NULL,
  920. values,
  921. NULL,
  922. NULL,
  923. 0);
  924. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  925. fprintf(stderr, "ERROR: Error deleting member: %s\n", PQresultErrorMessage(res));
  926. }
  927. PQclear(res);
  928. } catch (std::exception &e) {
  929. fprintf(stderr, "ERROR: Error deleting member: %s\n", e.what());
  930. }
  931. } else {
  932. fprintf(stderr, "ERROR: unknown objtype");
  933. }
  934. } catch (std::exception &e) {
  935. fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
  936. }
  937. delete config;
  938. config = nullptr;
  939. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  940. }
  941. PQfinish(conn);
  942. }
  943. void PostgreSQL::onlineNotificationThread()
  944. {
  945. PGconn *conn = PQconnectdb(_path.c_str());
  946. if (PQstatus(conn) == CONNECTION_BAD) {
  947. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  948. PQfinish(conn);
  949. exit(1);
  950. }
  951. _connected = 1;
  952. int64_t lastUpdatedNetworkStatus = 0;
  953. std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative;
  954. while (_run == 1) {
  955. if (PQstatus(conn) != CONNECTION_OK) {
  956. fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres.");
  957. exit(-1);
  958. }
  959. // map used to send notifications to front end
  960. std::unordered_map<std::string, std::vector<std::string>> updateMap;
  961. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  962. {
  963. std::lock_guard<std::mutex> l(_lastOnline_l);
  964. lastOnline.swap(_lastOnline);
  965. }
  966. PGresult *res = NULL;
  967. int qCount = 0;
  968. res = PQexec(conn, "BEGIN");
  969. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  970. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  971. PQclear(res);
  972. exit(1);
  973. }
  974. PQclear(res);
  975. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  976. uint64_t nwid_i = i->first.first;
  977. char nwidTmp[64];
  978. char memTmp[64];
  979. char ipTmp[64];
  980. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  981. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  982. auto found = _networks.find(nwid_i);
  983. if (found == _networks.end()) {
  984. continue; // skip members trying to join non-existant networks
  985. }
  986. lastOnlineCumulative[i->first] = i->second.first;
  987. std::string networkId(nwidTmp);
  988. std::string memberId(memTmp);
  989. std::vector<std::string> &members = updateMap[networkId];
  990. members.push_back(memberId);
  991. int64_t ts = i->second.first;
  992. std::string ipAddr = i->second.second.toIpString(ipTmp);
  993. std::string timestamp = std::to_string(ts);
  994. const char *values[4] = {
  995. networkId.c_str(),
  996. memberId.c_str(),
  997. (ipAddr.empty() ? NULL : ipAddr.c_str()),
  998. timestamp.c_str(),
  999. };
  1000. res = PQexecParams(conn,
  1001. "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ($1, $2, $3, TO_TIMESTAMP($4::double precision/1000)) "
  1002. "ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated",
  1003. 4, // number of parameters
  1004. NULL, // oid field. ignore
  1005. values, // values for substitution
  1006. NULL, // lengths in bytes of each value
  1007. NULL,
  1008. 0);
  1009. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1010. fprintf(stderr, "Error on Member Status upsert: %s\n", PQresultErrorMessage(res));
  1011. PQclear(res);
  1012. PQclear(PQexec(conn, "ROLLBACK"));
  1013. continue;
  1014. }
  1015. PQclear(res);
  1016. if ((++qCount) == 1024) {
  1017. res = PQexec(conn, "COMMIT");
  1018. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1019. fprintf(stderr, "ERROR: Error on commit (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1020. PQclear(res);
  1021. PQclear(PQexec(conn, "ROLLBACK"));
  1022. exit(1);
  1023. }
  1024. PQclear(res);
  1025. res = PQexec(conn, "BEGIN");
  1026. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1027. fprintf(stderr, "ERROR: Error on BEGIN (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1028. PQclear(res);
  1029. exit(1);
  1030. }
  1031. PQclear(res);
  1032. qCount = 0;
  1033. }
  1034. }
  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. PQclear(PQexec(conn, "ROLLBACK"));
  1040. exit(1);
  1041. }
  1042. PQclear(res);
  1043. const int64_t now = OSUtils::now();
  1044. if ((now - lastUpdatedNetworkStatus) > 10000) {
  1045. lastUpdatedNetworkStatus = now;
  1046. std::vector<std::pair<uint64_t, std::shared_ptr<_Network>>> networks;
  1047. {
  1048. std::lock_guard<std::mutex> l(_networks_l);
  1049. for (auto i = _networks.begin(); i != _networks.end(); ++i) {
  1050. networks.push_back(*i);
  1051. }
  1052. }
  1053. int nCount = 0;
  1054. res = PQexec(conn, "BEGIN");
  1055. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1056. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1057. PQclear(res);
  1058. exit(1);
  1059. }
  1060. PQclear(res);
  1061. for (auto i = networks.begin(); i != networks.end(); ++i) {
  1062. char tmp[64];
  1063. Utils::hex(i->first, tmp);
  1064. std::string networkId(tmp);
  1065. std::vector<std::string> &_notUsed = updateMap[networkId];
  1066. (void)_notUsed;
  1067. uint64_t authMemberCount = 0;
  1068. uint64_t totalMemberCount = 0;
  1069. uint64_t onlineMemberCount = 0;
  1070. uint64_t bridgeCount = 0;
  1071. uint64_t ts = now;
  1072. {
  1073. std::lock_guard<std::mutex> l2(i->second->lock);
  1074. authMemberCount = i->second->authorizedMembers.size();
  1075. totalMemberCount = i->second->members.size();
  1076. bridgeCount = i->second->activeBridgeMembers.size();
  1077. for (auto m=i->second->members.begin(); m != i->second->members.end(); ++m) {
  1078. auto lo = lastOnlineCumulative.find(std::pair<uint64_t,uint64_t>(i->first, m->first));
  1079. if (lo != lastOnlineCumulative.end()) {
  1080. if ((now - lo->second) <= (ZT_NETWORK_AUTOCONF_DELAY * 2)) {
  1081. ++onlineMemberCount;
  1082. } else {
  1083. lastOnlineCumulative.erase(lo);
  1084. }
  1085. }
  1086. }
  1087. }
  1088. std::string bc = std::to_string(bridgeCount);
  1089. std::string amc = std::to_string(authMemberCount);
  1090. std::string omc = std::to_string(onlineMemberCount);
  1091. std::string tmc = std::to_string(totalMemberCount);
  1092. std::string timestamp = std::to_string(ts);
  1093. const char *values[6] = {
  1094. networkId.c_str(),
  1095. bc.c_str(),
  1096. amc.c_str(),
  1097. omc.c_str(),
  1098. tmc.c_str(),
  1099. timestamp.c_str()
  1100. };
  1101. res = PQexecParams(conn, "INSERT INTO ztc_network_status (network_id, bridge_count, authorized_member_count, "
  1102. "online_member_count, total_member_count, last_modified) VALUES ($1, $2, $3, $4, $5, TO_TIMESTAMP($6::double precision/1000)) "
  1103. "ON CONFLICT (network_id) DO UPDATE SET bridge_count = EXCLUDED.bridge_count, "
  1104. "authorized_member_count = EXCLUDED.authorized_member_count, online_member_count = EXCLUDED.online_member_count, "
  1105. "total_member_count = EXCLUDED.total_member_count, last_modified = EXCLUDED.last_modified",
  1106. 6,
  1107. NULL,
  1108. values,
  1109. NULL,
  1110. NULL,
  1111. 0);
  1112. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1113. fprintf(stderr, "ERROR: Error on Network Status upsert (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1114. PQclear(res);
  1115. PQclear(PQexec(conn, "ROLLBACK"));
  1116. exit(1);
  1117. }
  1118. if ((++nCount) == 1024) {
  1119. res = PQexec(conn, "COMMIT");
  1120. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1121. fprintf(stderr, "ERROR: Error on COMMIT (onlineNotificationThread): %s\n" , PQresultErrorMessage(res));
  1122. PQclear(res);
  1123. PQclear(PQexec(conn, "ROLLBACK"));
  1124. exit(1);
  1125. }
  1126. res = PQexec(conn, "BEGIN");
  1127. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1128. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1129. PQclear(res);
  1130. exit(1);
  1131. }
  1132. nCount = 0;
  1133. }
  1134. }
  1135. res = PQexec(conn, "COMMIT");
  1136. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1137. fprintf(stderr, "ERROR: Error on COMMIT (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1138. PQclear(res);
  1139. PQclear(PQexec(conn, "ROLLBACK"));
  1140. exit(1);
  1141. }
  1142. }
  1143. for (auto it = updateMap.begin(); it != updateMap.end(); ++it) {
  1144. std::string networkId = it->first;
  1145. std::vector<std::string> members = it->second;
  1146. std::stringstream queryBuilder;
  1147. std::string membersStr = ::join(members, ",");
  1148. queryBuilder << "NOTIFY controller, '" << networkId << ":" << membersStr << "'";
  1149. std::string query = queryBuilder.str();
  1150. PGresult *res = PQexec(conn,query.c_str());
  1151. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1152. fprintf(stderr, "ERROR: Error sending NOTIFY: %s\n", PQresultErrorMessage(res));
  1153. }
  1154. PQclear(res);
  1155. }
  1156. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  1157. }
  1158. PQfinish(conn);
  1159. }
  1160. #endif //ZT_CONTROLLER_USE_LIBPQ