PostgreSQL.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  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. try {
  190. config["creationTime"] = std::stoull(PQgetvalue(res, i, 1));
  191. } catch (std::exception &e) {
  192. config["creationTime"] = 0ULL;
  193. //fprintf(stderr, "Error converting creation time: %s\n", PQgetvalue(res, i, 1));
  194. }
  195. config["capabilities"] = json::parse(PQgetvalue(res, i, 2));
  196. config["enableBroadcast"] = (strcmp(PQgetvalue(res, i, 3),"t")==0);
  197. try {
  198. config["lastModified"] = std::stoull(PQgetvalue(res, i, 4));
  199. } catch (std::exception &e) {
  200. config["lastModified"] = 0ULL;
  201. //fprintf(stderr, "Error converting last modified: %s\n", PQgetvalue(res, i, 4));
  202. }
  203. try {
  204. config["mtu"] = std::stoi(PQgetvalue(res, i, 5));
  205. } catch (std::exception &e) {
  206. config["mtu"] = 2800;
  207. }
  208. try {
  209. config["multicastLimit"] = std::stoi(PQgetvalue(res, i, 6));
  210. } catch (std::exception &e) {
  211. config["multicastLimit"] = 64;
  212. }
  213. config["name"] = PQgetvalue(res, i, 7);
  214. config["private"] = (strcmp(PQgetvalue(res, i, 8),"t")==0);
  215. try {
  216. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
  217. } catch (std::exception &e) {
  218. config["remoteTraceLevel"] = 0;
  219. }
  220. config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
  221. try {
  222. config["revision"] = std::stoull(PQgetvalue(res, i, 11));
  223. } catch (std::exception &e) {
  224. config["revision"] = 0ULL;
  225. //fprintf(stderr, "Error converting revision: %s\n", PQgetvalue(res, i, 11));
  226. }
  227. config["rules"] = json::parse(PQgetvalue(res, i, 12));
  228. config["tags"] = json::parse(PQgetvalue(res, i, 13));
  229. config["v4AssignMode"] = json::parse(PQgetvalue(res, i, 14));
  230. config["v6AssignMode"] = json::parse(PQgetvalue(res, i, 15));
  231. config["objtype"] = "network";
  232. config["ipAssignmentPools"] = json::array();
  233. config["routes"] = json::array();
  234. PGresult *r2 = PQexecParams(conn,
  235. "SELECT host(ip_range_start), host(ip_range_end) FROM ztc_network_assignment_pool WHERE network_id = $1",
  236. 1,
  237. NULL,
  238. nwidparam,
  239. NULL,
  240. NULL,
  241. 0);
  242. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  243. fprintf(stderr, "ERROR: Error retreiving IP pools for network: %s\n", PQresultErrorMessage(r2));
  244. PQclear(r2);
  245. PQclear(res);
  246. exit(1);
  247. }
  248. int n = PQntuples(r2);
  249. for (int j = 0; j < n; ++j) {
  250. json ip;
  251. ip["ipRangeStart"] = PQgetvalue(r2, j, 0);
  252. ip["ipRangeEnd"] = PQgetvalue(r2, j, 1);
  253. config["ipAssignmentPools"].push_back(ip);
  254. }
  255. PQclear(r2);
  256. r2 = PQexecParams(conn,
  257. "SELECT host(address), bits, host(via) FROM ztc_network_route WHERE network_id = $1",
  258. 1,
  259. NULL,
  260. nwidparam,
  261. NULL,
  262. NULL,
  263. 0);
  264. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  265. fprintf(stderr, "ERROR: Error retreiving routes for network: %s\n", PQresultErrorMessage(r2));
  266. PQclear(r2);
  267. PQclear(res);
  268. exit(1);
  269. }
  270. n = PQntuples(r2);
  271. for (int j = 0; j < n; ++j) {
  272. std::string addr = PQgetvalue(r2, j, 0);
  273. std::string bits = PQgetvalue(r2, j, 1);
  274. std::string via = PQgetvalue(r2, j, 2);
  275. json route;
  276. route["target"] = addr + "/" + bits;
  277. if (via == "NULL") {
  278. route["via"] = nullptr;
  279. } else {
  280. route["via"] = via;
  281. }
  282. config["routes"].push_back(route);
  283. }
  284. PQclear(r2);
  285. _networkChanged(empty, config, false);
  286. }
  287. PQclear(res);
  288. if (++this->_ready == 2) {
  289. if (_waitNoticePrinted) {
  290. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  291. }
  292. _readyLock.unlock();
  293. }
  294. } catch (std::exception &e) {
  295. fprintf(stderr, "ERROR: Error initializing networks: %s", e.what());
  296. exit(-1);
  297. }
  298. }
  299. void PostgreSQL::initializeMembers(PGconn *conn)
  300. {
  301. try {
  302. if (PQstatus(conn) != CONNECTION_OK) {
  303. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  304. exit(1);
  305. }
  306. const char *params[1] = {
  307. _myAddressStr.c_str()
  308. };
  309. PGresult *res = PQexecParams(conn,
  310. "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, "
  311. " EXTRACT(EPOCH FROM m.last_authorized_time AT TIME ZONE 'UTC')*1000, "
  312. " EXTRACT(EPOCH FROM m.last_deauthorized_time AT TIME ZONE 'UTC')*1000, "
  313. " m.remote_trace_level, m.remote_trace_target, m.tags, m.v_major, m.v_minor, m.v_rev, m.v_proto, "
  314. " m.no_auto_assign_ips, m.revision "
  315. "FROM ztc_member m "
  316. "INNER JOIN ztc_network n "
  317. " ON n.id = m.network_id "
  318. "WHERE n.controller_id = $1 AND m.deleted = false",
  319. 1,
  320. NULL,
  321. params,
  322. NULL,
  323. NULL,
  324. 0);
  325. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  326. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  327. PQclear(res);
  328. exit(1);
  329. }
  330. int numRows = PQntuples(res);
  331. for (int i = 0; i < numRows; ++i) {
  332. json empty;
  333. json config;
  334. std::string memberId(PQgetvalue(res, i, 0));
  335. std::string networkId(PQgetvalue(res, i, 1));
  336. std::string ctime = PQgetvalue(res, i, 5);
  337. config["id"] = memberId;
  338. config["nwid"] = networkId;
  339. config["activeBridge"] = (strcmp(PQgetvalue(res, i, 2), "t") == 0);
  340. config["authorized"] = (strcmp(PQgetvalue(res, i, 3), "t") == 0);
  341. try {
  342. config["capabilities"] = json::parse(PQgetvalue(res, i, 4));
  343. } catch (std::exception &e) {
  344. config["capabilities"] = json::array();
  345. }
  346. try {
  347. config["creationTime"] = std::stoull(PQgetvalue(res, i, 5));
  348. } catch (std::exception &e) {
  349. config["creationTime"] = 0ULL;
  350. //fprintf(stderr, "Error upding creation time (member): %s\n", PQgetvalue(res, i, 5));
  351. }
  352. config["identity"] = PQgetvalue(res, i, 6);
  353. try {
  354. config["lastAuthorizedTime"] = std::stoull(PQgetvalue(res, i, 7));
  355. } catch(std::exception &e) {
  356. config["lastAuthorizedTime"] = 0ULL;
  357. //fprintf(stderr, "Error updating last auth time (member): %s\n", PQgetvalue(res, i, 7));
  358. }
  359. try {
  360. config["lastDeauthorizedTime"] = std::stoull(PQgetvalue(res, i, 8));
  361. } catch( std::exception &e) {
  362. config["lastDeauthorizedTime"] = 0ULL;
  363. //fprintf(stderr, "Error updating last deauth time (member): %s\n", PQgetvalue(res, i, 8));
  364. }
  365. try {
  366. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
  367. } catch (std::exception &e) {
  368. config["remoteTraceLevel"] = 0;
  369. }
  370. config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
  371. try {
  372. config["tags"] = json::parse(PQgetvalue(res, i, 11));
  373. } catch (std::exception &e) {
  374. config["tags"] = json::array();
  375. }
  376. try {
  377. config["vMajor"] = std::stoi(PQgetvalue(res, i, 12));
  378. } catch(std::exception &e) {
  379. config["vMajor"] = -1;
  380. }
  381. try {
  382. config["vMinor"] = std::stoi(PQgetvalue(res, i, 13));
  383. } catch (std::exception &e) {
  384. config["vMinor"] = -1;
  385. }
  386. try {
  387. config["vRev"] = std::stoi(PQgetvalue(res, i, 14));
  388. } catch (std::exception &e) {
  389. config["vRev"] = -1;
  390. }
  391. try {
  392. config["vProto"] = std::stoi(PQgetvalue(res, i, 15));
  393. } catch (std::exception &e) {
  394. config["vProto"] = -1;
  395. }
  396. config["noAutoAssignIps"] = (strcmp(PQgetvalue(res, i, 16), "t") == 0);
  397. try {
  398. config["revision"] = std::stoull(PQgetvalue(res, i, 17));
  399. } catch (std::exception &e) {
  400. config["revision"] = 0ULL;
  401. //fprintf(stderr, "Error updating revision (member): %s\n", PQgetvalue(res, i, 17));
  402. }
  403. config["objtype"] = "member";
  404. config["ipAssignments"] = json::array();
  405. const char *p2[2] = {
  406. memberId.c_str(),
  407. networkId.c_str()
  408. };
  409. PGresult *r2 = PQexecParams(conn,
  410. "SELECT address FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  411. 2,
  412. NULL,
  413. p2,
  414. NULL,
  415. NULL,
  416. 0);
  417. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  418. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  419. PQclear(r2);
  420. PQclear(res);
  421. exit(1);
  422. }
  423. int n = PQntuples(r2);
  424. for (int j = 0; j < n; ++j) {
  425. config["ipAssignments"].push_back(PQgetvalue(r2, j, 0));
  426. }
  427. _memberChanged(empty, config, false);
  428. }
  429. PQclear(res);
  430. if (++this->_ready == 2) {
  431. if (_waitNoticePrinted) {
  432. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  433. }
  434. _readyLock.unlock();
  435. }
  436. } catch (std::exception &e) {
  437. fprintf(stderr, "ERROR: Error initializing members: %s\n", e.what());
  438. exit(-1);
  439. }
  440. }
  441. void PostgreSQL::heartbeat()
  442. {
  443. char publicId[1024];
  444. char hostnameTmp[1024];
  445. _myId.toString(false,publicId);
  446. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  447. hostnameTmp[0] = (char)0;
  448. } else {
  449. for (int i = 0; i < sizeof(hostnameTmp); ++i) {
  450. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  451. hostnameTmp[i] = (char)0;
  452. break;
  453. }
  454. }
  455. }
  456. const char *controllerId = _myAddressStr.c_str();
  457. const char *publicIdentity = publicId;
  458. const char *hostname = hostnameTmp;
  459. PGconn *conn = PQconnectdb(_path.c_str());
  460. if (PQstatus(conn) == CONNECTION_BAD) {
  461. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  462. PQfinish(conn);
  463. exit(1);
  464. }
  465. while (_run == 1) {
  466. if(PQstatus(conn) != CONNECTION_OK) {
  467. PQfinish(conn);
  468. conn = PQconnectdb(_path.c_str());
  469. }
  470. if (conn) {
  471. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  472. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  473. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  474. std::string build = std::to_string(ZEROTIER_ONE_VERSION_BUILD);
  475. std::string now = std::to_string(OSUtils::now());
  476. const char *values[8] = {
  477. controllerId,
  478. hostname,
  479. now.c_str(),
  480. publicIdentity,
  481. major.c_str(),
  482. minor.c_str(),
  483. rev.c_str(),
  484. build.c_str()
  485. };
  486. PGresult *res = PQexecParams(conn,
  487. "INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build) "
  488. "VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8) "
  489. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  490. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  491. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev",
  492. 8, // number of parameters
  493. NULL, // oid field. ignore
  494. values, // values for substitution
  495. NULL, // lengths in bytes of each value
  496. NULL, // binary?
  497. 0);
  498. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  499. fprintf(stderr, "Heartbeat Update Failed: %s\n", PQresultErrorMessage(res));
  500. }
  501. PQclear(res);
  502. }
  503. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  504. }
  505. PQfinish(conn);
  506. conn = NULL;
  507. }
  508. void PostgreSQL::membersDbWatcher()
  509. {
  510. PGconn *conn = PQconnectdb(_path.c_str());
  511. if (PQstatus(conn) == CONNECTION_BAD) {
  512. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  513. PQfinish(conn);
  514. exit(1);
  515. }
  516. initializeMembers(conn);
  517. char buf[11] = {0};
  518. std::string cmd = "LISTEN member_" + std::string(_myAddress.toString(buf));
  519. PGresult *res = PQexec(conn, cmd.c_str());
  520. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  521. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  522. PQclear(res);
  523. PQfinish(conn);
  524. exit(1);
  525. }
  526. PQclear(res); res = NULL;
  527. while(_run == 1) {
  528. if (PQstatus(conn) != CONNECTION_OK) {
  529. fprintf(stderr, "ERROR: Member Watcher lost connection to Postgres.");
  530. exit(-1);
  531. }
  532. PGnotify *notify = NULL;
  533. PQconsumeInput(conn);
  534. while ((notify = PQnotifies(conn)) != NULL) {
  535. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  536. try {
  537. json tmp(json::parse(notify->extra));
  538. json &ov = tmp["old_val"];
  539. json &nv = tmp["new_val"];
  540. json oldConfig, newConfig;
  541. if (ov.is_object()) oldConfig = ov;
  542. if (nv.is_object()) newConfig = nv;
  543. if (oldConfig.is_object() || newConfig.is_object()) {
  544. _memberChanged(oldConfig,newConfig,(this->_ready>=2));
  545. }
  546. } catch (...) {} // ignore bad records
  547. free(notify);
  548. }
  549. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  550. }
  551. PQfinish(conn);
  552. conn = NULL;
  553. }
  554. void PostgreSQL::networksDbWatcher()
  555. {
  556. PGconn *conn = PQconnectdb(_path.c_str());
  557. if (PQstatus(conn) == CONNECTION_BAD) {
  558. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  559. PQfinish(conn);
  560. exit(1);
  561. }
  562. initializeNetworks(conn);
  563. char buf[11] = {0};
  564. std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
  565. PGresult *res = PQexec(conn, cmd.c_str());
  566. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  567. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  568. PQclear(res);
  569. PQfinish(conn);
  570. exit(1);
  571. }
  572. PQclear(res); res = NULL;
  573. while(_run == 1) {
  574. if (PQstatus(conn) != CONNECTION_OK) {
  575. fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
  576. exit(-1);
  577. }
  578. PGnotify *notify = NULL;
  579. PQconsumeInput(conn);
  580. while ((notify = PQnotifies(conn)) != NULL) {
  581. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  582. try {
  583. json tmp(json::parse(notify->extra));
  584. json &ov = tmp["old_val"];
  585. json &nv = tmp["new_val"];
  586. json oldConfig, newConfig;
  587. if (ov.is_object()) oldConfig = ov;
  588. if (nv.is_object()) newConfig = nv;
  589. if (oldConfig.is_object()||newConfig.is_object()) {
  590. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  591. }
  592. } catch (...) {} // ignore bad records
  593. free(notify);
  594. }
  595. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  596. }
  597. PQfinish(conn);
  598. conn = NULL;
  599. }
  600. void PostgreSQL::commitThread()
  601. {
  602. PGconn *conn = PQconnectdb(_path.c_str());
  603. if (PQstatus(conn) == CONNECTION_BAD) {
  604. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  605. PQfinish(conn);
  606. exit(1);
  607. }
  608. json *config = nullptr;
  609. while(_commitQueue.get(config)&(_run == 1)) {
  610. if (!config) {
  611. continue;
  612. }
  613. if (PQstatus(conn) == CONNECTION_BAD) {
  614. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  615. PQfinish(conn);
  616. delete config;
  617. exit(1);
  618. }
  619. try {
  620. const std::string objtype = (*config)["objtype"];
  621. if (objtype == "member") {
  622. try {
  623. std::string memberId = (*config)["id"];
  624. std::string networkId = (*config)["nwid"];
  625. std::string identity = (*config)["identity"];
  626. std::string target = "NULL";
  627. if (!(*config)["remoteTraceTarget"].is_null()) {
  628. target = (*config)["remoteTraceTarget"];
  629. }
  630. std::string caps = OSUtils::jsonDump((*config)["capabilities"], -1);
  631. std::string lastAuthTime = std::to_string((long long)(*config)["lastAuthorizedTime"]);
  632. std::string lastDeauthTime = std::to_string((long long)(*config)["lastDeauthorizedTime"]);
  633. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  634. std::string rev = std::to_string((unsigned long long)(*config)["revision"]);
  635. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  636. std::string vmajor = std::to_string((int)(*config)["vMajor"]);
  637. std::string vminor = std::to_string((int)(*config)["vMinor"]);
  638. std::string vrev = std::to_string((int)(*config)["vRev"]);
  639. std::string vproto = std::to_string((int)(*config)["vProto"]);
  640. const char *values[19] = {
  641. memberId.c_str(),
  642. networkId.c_str(),
  643. ((*config)["activeBridge"] ? "true" : "false"),
  644. ((*config)["authorized"] ? "true" : "false"),
  645. caps.c_str(),
  646. identity.c_str(),
  647. lastAuthTime.c_str(),
  648. lastDeauthTime.c_str(),
  649. ((*config)["noAutoAssignIps"] ? "true" : "false"),
  650. rtraceLevel.c_str(),
  651. (target == "NULL") ? NULL : target.c_str(),
  652. rev.c_str(),
  653. tags.c_str(),
  654. vmajor.c_str(),
  655. vminor.c_str(),
  656. vrev.c_str(),
  657. vproto.c_str()
  658. };
  659. PGresult *res = PQexecParams(conn,
  660. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  661. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  662. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  663. "VALUES ($1, $2, $3, $4, $5, $6, "
  664. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  665. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  666. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  667. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  668. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  669. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  670. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  671. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  672. 17,
  673. NULL,
  674. values,
  675. NULL,
  676. NULL,
  677. 0);
  678. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  679. fprintf(stderr, "ERROR: Error updating member: %s\n", PQresultErrorMessage(res));
  680. fprintf(stderr, "%s", OSUtils::jsonDump(*config, 2).c_str());
  681. PQclear(res);
  682. delete config;
  683. config = nullptr;
  684. continue;
  685. }
  686. PQclear(res);
  687. res = PQexec(conn, "BEGIN");
  688. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  689. fprintf(stderr, "ERROR: Error beginning transaction: %s\n", PQresultErrorMessage(res));
  690. PQclear(res);
  691. delete config;
  692. config = nullptr;
  693. continue;
  694. }
  695. PQclear(res);
  696. const char *v2[2] = {
  697. memberId.c_str(),
  698. networkId.c_str()
  699. };
  700. res = PQexecParams(conn,
  701. "DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  702. 2,
  703. NULL,
  704. v2,
  705. NULL,
  706. NULL,
  707. 0);
  708. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  709. fprintf(stderr, "ERROR: Error updating IP address assignments: %s\n", PQresultErrorMessage(res));
  710. PQclear(res);
  711. PQclear(PQexec(conn, "ROLLBACK"));;
  712. delete config;
  713. config = nullptr;
  714. continue;
  715. }
  716. PQclear(res);
  717. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  718. std::string addr = *i;
  719. const char *v3[3] = {
  720. memberId.c_str(),
  721. networkId.c_str(),
  722. addr.c_str()
  723. };
  724. res = PQexecParams(conn,
  725. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3)",
  726. 3,
  727. NULL,
  728. v3,
  729. NULL,
  730. NULL,
  731. 0);
  732. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  733. fprintf(stderr, "ERROR: Error setting IP addresses for member: %s\n", PQresultErrorMessage(res));
  734. PQclear(res);
  735. PQclear(PQexec(conn, "ROLLBACK"));
  736. continue;
  737. }
  738. }
  739. res = PQexec(conn, "COMMIT");
  740. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  741. fprintf(stderr, "ERROR: Error committing ip address data: %s\n", PQresultErrorMessage(res));
  742. }
  743. PQclear(res);
  744. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  745. const uint64_t memberidInt = OSUtils::jsonIntHex((*config)["id"], 0ULL);
  746. if (nwidInt && memberidInt) {
  747. nlohmann::json nwOrig;
  748. nlohmann::json memOrig;
  749. nlohmann::json memNew(*config);
  750. get(nwidInt, nwOrig, memberidInt, memOrig);
  751. _memberChanged(memOrig, memNew, (this->_ready>=2));
  752. } else {
  753. fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %lu-%lu\n", nwidInt, memberidInt);
  754. }
  755. } catch (std::exception &e) {
  756. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  757. }
  758. } else if (objtype == "network") {
  759. try {
  760. std::string id = (*config)["id"];
  761. std::string controllerId = _myAddressStr.c_str();
  762. std::string name = (*config)["name"];
  763. std::string remoteTraceTarget("NULL");
  764. if (!(*config)["remoteTraceTarget"].is_null()) {
  765. remoteTraceTarget = (*config)["remoteTraceTarget"];
  766. }
  767. std::string rulesSource = (*config)["rulesSource"];
  768. std::string caps = OSUtils::jsonDump((*config)["capabilitles"], -1);
  769. std::string now = std::to_string(OSUtils::now());
  770. std::string mtu = std::to_string((int)(*config)["mtu"]);
  771. std::string mcastLimit = std::to_string((int)(*config)["multicastLimit"]);
  772. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  773. std::string rules = OSUtils::jsonDump((*config)["rules"], -1);
  774. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  775. std::string v4mode = OSUtils::jsonDump((*config)["v4AssignMode"],-1);
  776. std::string v6mode = OSUtils::jsonDump((*config)["v6AssignMode"], -1);
  777. bool enableBroadcast = (*config)["enableBroadcast"];
  778. bool isPrivate = (*config)["private"];
  779. const char *values[16] = {
  780. id.c_str(),
  781. controllerId.c_str(),
  782. caps.c_str(),
  783. enableBroadcast ? "true" : "false",
  784. now.c_str(),
  785. mtu.c_str(),
  786. mcastLimit.c_str(),
  787. name.c_str(),
  788. isPrivate ? "true" : "false",
  789. rtraceLevel.c_str(),
  790. (remoteTraceTarget == "NULL" ? NULL : remoteTraceTarget.c_str()),
  791. rules.c_str(),
  792. rulesSource.c_str(),
  793. tags.c_str(),
  794. v4mode.c_str(),
  795. v6mode.c_str(),
  796. };
  797. PGresult *res = PQexecParams(conn,
  798. "UPDATE ztc_network SET controller_id = $2, capabilities = $3, enable_broadcast = $4, "
  799. "last_updated = $5, mtu = $6, multicast_limit = $7, name = $8, private = $9, "
  800. "remote_trace_level = $10, remote_trace_target = $11, rules = $12, rules_source = $13, "
  801. "tags = $14, v4_assign_mode = $15, v6_assign_mode = $16 "
  802. "WHERE id = $1",
  803. 16,
  804. NULL,
  805. values,
  806. NULL,
  807. NULL,
  808. 0);
  809. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  810. fprintf(stderr, "ERROR: Error updating network record: %s\n", PQresultErrorMessage(res));
  811. PQclear(res);
  812. delete config;
  813. config = nullptr;
  814. continue;
  815. }
  816. PQclear(res);
  817. res = PQexec(conn, "BEGIN");
  818. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  819. fprintf(stderr, "ERROR: Error beginnning transaction: %s\n", PQresultErrorMessage(res));
  820. PQclear(res);
  821. delete config;
  822. config = nullptr;
  823. continue;
  824. }
  825. PQclear(res);
  826. const char *params[1] = {
  827. id.c_str()
  828. };
  829. res = PQexecParams(conn,
  830. "DELETE FROM ztc_network_assignment_pool WHERE network_id = $1",
  831. 1,
  832. NULL,
  833. params,
  834. NULL,
  835. NULL,
  836. 0);
  837. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  838. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  839. PQclear(res);
  840. PQclear(PQexec(conn, "ROLLBACK"));
  841. delete config;
  842. config = nullptr;
  843. continue;
  844. }
  845. PQclear(res);
  846. auto pool = (*config)["ipAssignmentPools"];
  847. bool err = false;
  848. for (auto i = pool.begin(); i != pool.end(); ++i) {
  849. std::string start = (*i)["ipRangeStart"];
  850. std::string end = (*i)["ipRangeEnd"];
  851. const char *p[3] = {
  852. id.c_str(),
  853. start.c_str(),
  854. end.c_str()
  855. };
  856. res = PQexecParams(conn,
  857. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  858. "VALUES ($1, $2, $3)",
  859. 3,
  860. NULL,
  861. p,
  862. NULL,
  863. NULL,
  864. 0);
  865. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  866. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  867. PQclear(res);
  868. err = true;
  869. break;
  870. }
  871. PQclear(res);
  872. }
  873. if (err) {
  874. PQclear(PQexec(conn, "ROLLBACK"));
  875. delete config;
  876. config = nullptr;
  877. continue;
  878. }
  879. res = PQexecParams(conn,
  880. "DELETE FROM ztc_network_route WHERE network_id = $1",
  881. 1,
  882. NULL,
  883. params,
  884. NULL,
  885. NULL,
  886. 0);
  887. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  888. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  889. PQclear(res);
  890. PQclear(PQexec(conn, "ROLLBACK"));
  891. delete config;
  892. config = nullptr;
  893. continue;
  894. }
  895. auto routes = (*config)["routes"];
  896. err = false;
  897. for (auto i = routes.begin(); i != routes.end(); ++i) {
  898. std::string t = (*i)["target"];
  899. std::vector<std::string> target;
  900. std::istringstream f(t);
  901. std::string s;
  902. while(std::getline(f, s, '/')) {
  903. target.push_back(s);
  904. }
  905. if (target.empty() || target.size() != 2) {
  906. continue;
  907. }
  908. std::string targetAddr = target[0];
  909. std::string targetBits = target[1];
  910. std::string via = "NULL";
  911. if (!(*i)["via"].is_null()) {
  912. via = (*i)["via"];
  913. }
  914. const char *p[4] = {
  915. id.c_str(),
  916. targetAddr.c_str(),
  917. targetBits.c_str(),
  918. (via == "NULL" ? NULL : via.c_str()),
  919. };
  920. res = PQexecParams(conn,
  921. "INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  922. 4,
  923. NULL,
  924. p,
  925. NULL,
  926. NULL,
  927. 0);
  928. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  929. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  930. PQclear(res);
  931. err = true;
  932. break;
  933. }
  934. PQclear(res);
  935. }
  936. if (err) {
  937. PQclear(PQexec(conn, "ROLLBACK"));
  938. delete config;
  939. config = nullptr;
  940. continue;
  941. }
  942. res = PQexec(conn, "COMMIT");
  943. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  944. fprintf(stderr, "ERROR: Error committing network update: %s\n", PQresultErrorMessage(res));
  945. }
  946. PQclear(res);
  947. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  948. if (nwidInt) {
  949. nlohmann::json nwOrig;
  950. nlohmann::json nwNew(*config);
  951. get(nwidInt, nwOrig);
  952. _networkChanged(nwOrig, nwNew, true);
  953. } else {
  954. fprintf(stderr, "Can't notify network changed: %lu\n", nwidInt);
  955. }
  956. } catch (std::exception &e) {
  957. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  958. }
  959. } else if (objtype == "trace") {
  960. fprintf(stderr, "ERROR: Trace not yet implemented");
  961. } else if (objtype == "_delete_network") {
  962. try {
  963. std::string networkId = (*config)["nwid"];
  964. const char *values[1] = {
  965. networkId.c_str()
  966. };
  967. PGresult * res = PQexecParams(conn,
  968. "UPDATE ztc_network SET deleted = true WHERE id = $1",
  969. 1,
  970. NULL,
  971. values,
  972. NULL,
  973. NULL,
  974. 0);
  975. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  976. fprintf(stderr, "ERROR: Error deleting network: %s\n", PQresultErrorMessage(res));
  977. }
  978. PQclear(res);
  979. } catch (std::exception &e) {
  980. fprintf(stderr, "ERROR: Error deleting network: %s\n", e.what());
  981. }
  982. } else if (objtype == "_delete_member") {
  983. try {
  984. std::string memberId = (*config)["id"];
  985. std::string networkId = (*config)["nwid"];
  986. const char *values[2] = {
  987. memberId.c_str(),
  988. networkId.c_str()
  989. };
  990. PGresult *res = PQexecParams(conn,
  991. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  992. 2,
  993. NULL,
  994. values,
  995. NULL,
  996. NULL,
  997. 0);
  998. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  999. fprintf(stderr, "ERROR: Error deleting member: %s\n", PQresultErrorMessage(res));
  1000. }
  1001. PQclear(res);
  1002. } catch (std::exception &e) {
  1003. fprintf(stderr, "ERROR: Error deleting member: %s\n", e.what());
  1004. }
  1005. } else {
  1006. fprintf(stderr, "ERROR: unknown objtype");
  1007. }
  1008. } catch (std::exception &e) {
  1009. fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
  1010. }
  1011. delete config;
  1012. config = nullptr;
  1013. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1014. }
  1015. PQfinish(conn);
  1016. }
  1017. void PostgreSQL::onlineNotificationThread()
  1018. {
  1019. PGconn *conn = PQconnectdb(_path.c_str());
  1020. if (PQstatus(conn) == CONNECTION_BAD) {
  1021. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  1022. PQfinish(conn);
  1023. exit(1);
  1024. }
  1025. _connected = 1;
  1026. int64_t lastUpdatedNetworkStatus = 0;
  1027. std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative;
  1028. while (_run == 1) {
  1029. if (PQstatus(conn) != CONNECTION_OK) {
  1030. fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres.");
  1031. exit(-1);
  1032. }
  1033. // map used to send notifications to front end
  1034. std::unordered_map<std::string, std::vector<std::string>> updateMap;
  1035. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1036. {
  1037. std::lock_guard<std::mutex> l(_lastOnline_l);
  1038. lastOnline.swap(_lastOnline);
  1039. }
  1040. PGresult *res = NULL;
  1041. int qCount = 0;
  1042. res = PQexec(conn, "BEGIN");
  1043. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1044. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1045. PQclear(res);
  1046. exit(1);
  1047. }
  1048. PQclear(res);
  1049. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1050. uint64_t nwid_i = i->first.first;
  1051. char nwidTmp[64];
  1052. char memTmp[64];
  1053. char ipTmp[64];
  1054. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1055. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  1056. auto found = _networks.find(nwid_i);
  1057. if (found == _networks.end()) {
  1058. continue; // skip members trying to join non-existant networks
  1059. }
  1060. lastOnlineCumulative[i->first] = i->second.first;
  1061. std::string networkId(nwidTmp);
  1062. std::string memberId(memTmp);
  1063. std::vector<std::string> &members = updateMap[networkId];
  1064. members.push_back(memberId);
  1065. int64_t ts = i->second.first;
  1066. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1067. std::string timestamp = std::to_string(ts);
  1068. const char *values[4] = {
  1069. networkId.c_str(),
  1070. memberId.c_str(),
  1071. (ipAddr.empty() ? NULL : ipAddr.c_str()),
  1072. timestamp.c_str(),
  1073. };
  1074. res = PQexecParams(conn,
  1075. "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ($1, $2, $3, TO_TIMESTAMP($4::double precision/1000)) "
  1076. "ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated",
  1077. 4, // number of parameters
  1078. NULL, // oid field. ignore
  1079. values, // values for substitution
  1080. NULL, // lengths in bytes of each value
  1081. NULL,
  1082. 0);
  1083. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1084. fprintf(stderr, "Error on Member Status upsert: %s\n", PQresultErrorMessage(res));
  1085. PQclear(res);
  1086. PQclear(PQexec(conn, "ROLLBACK"));
  1087. continue;
  1088. }
  1089. PQclear(res);
  1090. if ((++qCount) == 1024) {
  1091. res = PQexec(conn, "COMMIT");
  1092. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1093. fprintf(stderr, "ERROR: Error on commit (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1094. PQclear(res);
  1095. PQclear(PQexec(conn, "ROLLBACK"));
  1096. exit(1);
  1097. }
  1098. PQclear(res);
  1099. res = PQexec(conn, "BEGIN");
  1100. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1101. fprintf(stderr, "ERROR: Error on BEGIN (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1102. PQclear(res);
  1103. exit(1);
  1104. }
  1105. PQclear(res);
  1106. qCount = 0;
  1107. }
  1108. }
  1109. res = PQexec(conn, "COMMIT");
  1110. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1111. fprintf(stderr, "ERROR: Error on commit (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1112. PQclear(res);
  1113. PQclear(PQexec(conn, "ROLLBACK"));
  1114. exit(1);
  1115. }
  1116. PQclear(res);
  1117. const int64_t now = OSUtils::now();
  1118. if ((now - lastUpdatedNetworkStatus) > 10000) {
  1119. lastUpdatedNetworkStatus = now;
  1120. std::vector<std::pair<uint64_t, std::shared_ptr<_Network>>> networks;
  1121. {
  1122. std::lock_guard<std::mutex> l(_networks_l);
  1123. for (auto i = _networks.begin(); i != _networks.end(); ++i) {
  1124. networks.push_back(*i);
  1125. }
  1126. }
  1127. int nCount = 0;
  1128. res = PQexec(conn, "BEGIN");
  1129. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1130. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1131. PQclear(res);
  1132. exit(1);
  1133. }
  1134. PQclear(res);
  1135. for (auto i = networks.begin(); i != networks.end(); ++i) {
  1136. char tmp[64];
  1137. Utils::hex(i->first, tmp);
  1138. std::string networkId(tmp);
  1139. std::vector<std::string> &_notUsed = updateMap[networkId];
  1140. (void)_notUsed;
  1141. uint64_t authMemberCount = 0;
  1142. uint64_t totalMemberCount = 0;
  1143. uint64_t onlineMemberCount = 0;
  1144. uint64_t bridgeCount = 0;
  1145. uint64_t ts = now;
  1146. {
  1147. std::lock_guard<std::mutex> l2(i->second->lock);
  1148. authMemberCount = i->second->authorizedMembers.size();
  1149. totalMemberCount = i->second->members.size();
  1150. bridgeCount = i->second->activeBridgeMembers.size();
  1151. for (auto m=i->second->members.begin(); m != i->second->members.end(); ++m) {
  1152. auto lo = lastOnlineCumulative.find(std::pair<uint64_t,uint64_t>(i->first, m->first));
  1153. if (lo != lastOnlineCumulative.end()) {
  1154. if ((now - lo->second) <= (ZT_NETWORK_AUTOCONF_DELAY * 2)) {
  1155. ++onlineMemberCount;
  1156. } else {
  1157. lastOnlineCumulative.erase(lo);
  1158. }
  1159. }
  1160. }
  1161. }
  1162. std::string bc = std::to_string(bridgeCount);
  1163. std::string amc = std::to_string(authMemberCount);
  1164. std::string omc = std::to_string(onlineMemberCount);
  1165. std::string tmc = std::to_string(totalMemberCount);
  1166. std::string timestamp = std::to_string(ts);
  1167. const char *values[6] = {
  1168. networkId.c_str(),
  1169. bc.c_str(),
  1170. amc.c_str(),
  1171. omc.c_str(),
  1172. tmc.c_str(),
  1173. timestamp.c_str()
  1174. };
  1175. res = PQexecParams(conn, "INSERT INTO ztc_network_status (network_id, bridge_count, authorized_member_count, "
  1176. "online_member_count, total_member_count, last_modified) VALUES ($1, $2, $3, $4, $5, TO_TIMESTAMP($6::double precision/1000)) "
  1177. "ON CONFLICT (network_id) DO UPDATE SET bridge_count = EXCLUDED.bridge_count, "
  1178. "authorized_member_count = EXCLUDED.authorized_member_count, online_member_count = EXCLUDED.online_member_count, "
  1179. "total_member_count = EXCLUDED.total_member_count, last_modified = EXCLUDED.last_modified",
  1180. 6,
  1181. NULL,
  1182. values,
  1183. NULL,
  1184. NULL,
  1185. 0);
  1186. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1187. fprintf(stderr, "ERROR: Error on Network Status upsert (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1188. PQclear(res);
  1189. PQclear(PQexec(conn, "ROLLBACK"));
  1190. exit(1);
  1191. }
  1192. if ((++nCount) == 1024) {
  1193. res = PQexec(conn, "COMMIT");
  1194. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1195. fprintf(stderr, "ERROR: Error on COMMIT (onlineNotificationThread): %s\n" , PQresultErrorMessage(res));
  1196. PQclear(res);
  1197. PQclear(PQexec(conn, "ROLLBACK"));
  1198. exit(1);
  1199. }
  1200. res = PQexec(conn, "BEGIN");
  1201. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1202. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1203. PQclear(res);
  1204. exit(1);
  1205. }
  1206. nCount = 0;
  1207. }
  1208. }
  1209. res = PQexec(conn, "COMMIT");
  1210. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1211. fprintf(stderr, "ERROR: Error on COMMIT (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1212. PQclear(res);
  1213. PQclear(PQexec(conn, "ROLLBACK"));
  1214. exit(1);
  1215. }
  1216. }
  1217. for (auto it = updateMap.begin(); it != updateMap.end(); ++it) {
  1218. std::string networkId = it->first;
  1219. std::vector<std::string> members = it->second;
  1220. std::stringstream queryBuilder;
  1221. std::string membersStr = ::join(members, ",");
  1222. queryBuilder << "NOTIFY controller, '" << networkId << ":" << membersStr << "'";
  1223. std::string query = queryBuilder.str();
  1224. PGresult *res = PQexec(conn,query.c_str());
  1225. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1226. fprintf(stderr, "ERROR: Error sending NOTIFY: %s\n", PQresultErrorMessage(res));
  1227. }
  1228. PQclear(res);
  1229. }
  1230. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  1231. }
  1232. PQfinish(conn);
  1233. }
  1234. #endif //ZT_CONTROLLER_USE_LIBPQ