PostgreSQL.cpp 43 KB

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