PostgreSQL.cpp 48 KB

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