PostgreSQL.cpp 43 KB

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