PostgreSQL.cpp 40 KB

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