PostgreSQL.cpp 41 KB

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