PostgreSQL.cpp 29 KB

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