PostgreSQL.cpp 45 KB

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