PostgreSQL.cpp 45 KB

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