PostgreSQL.cpp 40 KB

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