PostgreSQL.cpp 41 KB

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