PostgreSQL.cpp 42 KB

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