PostgreSQL.cpp 40 KB

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