2
0

PostgreSQL.cpp 39 KB

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