PostgreSQL.cpp 42 KB

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