2
0

PostgreSQL.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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_CENTRAL_CONTROLLER_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_CENTRAL_CONTROLLER_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. fprintf(stderr, "%s heartbeat thread lost connection to Database\n", _myAddressStr.c_str());
  468. PQfinish(conn);
  469. exit(6);
  470. }
  471. if (conn) {
  472. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  473. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  474. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  475. std::string build = std::to_string(ZEROTIER_ONE_VERSION_BUILD);
  476. std::string now = std::to_string(OSUtils::now());
  477. const char *values[8] = {
  478. controllerId,
  479. hostname,
  480. now.c_str(),
  481. publicIdentity,
  482. major.c_str(),
  483. minor.c_str(),
  484. rev.c_str(),
  485. build.c_str()
  486. };
  487. PGresult *res = PQexecParams(conn,
  488. "INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build) "
  489. "VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8) "
  490. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  491. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  492. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev",
  493. 8, // number of parameters
  494. NULL, // oid field. ignore
  495. values, // values for substitution
  496. NULL, // lengths in bytes of each value
  497. NULL, // binary?
  498. 0);
  499. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  500. fprintf(stderr, "Heartbeat Update Failed: %s\n", PQresultErrorMessage(res));
  501. }
  502. PQclear(res);
  503. }
  504. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  505. }
  506. PQfinish(conn);
  507. conn = NULL;
  508. }
  509. void PostgreSQL::membersDbWatcher()
  510. {
  511. PGconn *conn = getPgConn(NO_OVERRIDE);
  512. if (PQstatus(conn) == CONNECTION_BAD) {
  513. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  514. PQfinish(conn);
  515. exit(1);
  516. }
  517. initializeMembers(conn);
  518. char buf[11] = {0};
  519. std::string cmd = "LISTEN member_" + std::string(_myAddress.toString(buf));
  520. PGresult *res = PQexec(conn, cmd.c_str());
  521. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  522. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  523. PQclear(res);
  524. PQfinish(conn);
  525. exit(1);
  526. }
  527. PQclear(res); res = NULL;
  528. while(_run == 1) {
  529. if (PQstatus(conn) != CONNECTION_OK) {
  530. fprintf(stderr, "ERROR: Member Watcher lost connection to Postgres.");
  531. exit(-1);
  532. }
  533. PGnotify *notify = NULL;
  534. PQconsumeInput(conn);
  535. while ((notify = PQnotifies(conn)) != NULL) {
  536. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  537. try {
  538. json tmp(json::parse(notify->extra));
  539. json &ov = tmp["old_val"];
  540. json &nv = tmp["new_val"];
  541. json oldConfig, newConfig;
  542. if (ov.is_object()) oldConfig = ov;
  543. if (nv.is_object()) newConfig = nv;
  544. if (oldConfig.is_object() || newConfig.is_object()) {
  545. _memberChanged(oldConfig,newConfig,(this->_ready>=2));
  546. }
  547. } catch (...) {} // ignore bad records
  548. free(notify);
  549. }
  550. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  551. }
  552. PQfinish(conn);
  553. conn = NULL;
  554. if (_run == 1) {
  555. fprintf(stderr, "ERROR: %s membersDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  556. exit(9);
  557. }
  558. }
  559. void PostgreSQL::networksDbWatcher()
  560. {
  561. PGconn *conn = getPgConn(NO_OVERRIDE);
  562. if (PQstatus(conn) == CONNECTION_BAD) {
  563. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  564. PQfinish(conn);
  565. exit(1);
  566. }
  567. initializeNetworks(conn);
  568. char buf[11] = {0};
  569. std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
  570. PGresult *res = PQexec(conn, cmd.c_str());
  571. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  572. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  573. PQclear(res);
  574. PQfinish(conn);
  575. exit(1);
  576. }
  577. PQclear(res); res = NULL;
  578. while(_run == 1) {
  579. if (PQstatus(conn) != CONNECTION_OK) {
  580. fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
  581. exit(-1);
  582. }
  583. PGnotify *notify = NULL;
  584. PQconsumeInput(conn);
  585. while ((notify = PQnotifies(conn)) != NULL) {
  586. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  587. try {
  588. json tmp(json::parse(notify->extra));
  589. json &ov = tmp["old_val"];
  590. json &nv = tmp["new_val"];
  591. json oldConfig, newConfig;
  592. if (ov.is_object()) oldConfig = ov;
  593. if (nv.is_object()) newConfig = nv;
  594. if (oldConfig.is_object()||newConfig.is_object()) {
  595. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  596. }
  597. } catch (...) {} // ignore bad records
  598. free(notify);
  599. }
  600. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  601. }
  602. PQfinish(conn);
  603. conn = NULL;
  604. if (_run == 1) {
  605. fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  606. exit(8);
  607. }
  608. }
  609. void PostgreSQL::commitThread()
  610. {
  611. PGconn *conn = getPgConn();
  612. if (PQstatus(conn) == CONNECTION_BAD) {
  613. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  614. PQfinish(conn);
  615. exit(1);
  616. }
  617. json *config = nullptr;
  618. while(_commitQueue.get(config)&(_run == 1)) {
  619. if (!config) {
  620. continue;
  621. }
  622. if (PQstatus(conn) == CONNECTION_BAD) {
  623. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  624. PQfinish(conn);
  625. delete config;
  626. exit(1);
  627. }
  628. try {
  629. const std::string objtype = (*config)["objtype"];
  630. if (objtype == "member") {
  631. try {
  632. std::string memberId = (*config)["id"];
  633. std::string networkId = (*config)["nwid"];
  634. std::string identity = (*config)["identity"];
  635. std::string target = "NULL";
  636. if (!(*config)["remoteTraceTarget"].is_null()) {
  637. target = (*config)["remoteTraceTarget"];
  638. }
  639. std::string caps = OSUtils::jsonDump((*config)["capabilities"], -1);
  640. std::string lastAuthTime = std::to_string((long long)(*config)["lastAuthorizedTime"]);
  641. std::string lastDeauthTime = std::to_string((long long)(*config)["lastDeauthorizedTime"]);
  642. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  643. std::string rev = std::to_string((unsigned long long)(*config)["revision"]);
  644. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  645. std::string vmajor = std::to_string((int)(*config)["vMajor"]);
  646. std::string vminor = std::to_string((int)(*config)["vMinor"]);
  647. std::string vrev = std::to_string((int)(*config)["vRev"]);
  648. std::string vproto = std::to_string((int)(*config)["vProto"]);
  649. const char *values[19] = {
  650. memberId.c_str(),
  651. networkId.c_str(),
  652. ((*config)["activeBridge"] ? "true" : "false"),
  653. ((*config)["authorized"] ? "true" : "false"),
  654. caps.c_str(),
  655. identity.c_str(),
  656. lastAuthTime.c_str(),
  657. lastDeauthTime.c_str(),
  658. ((*config)["noAutoAssignIps"] ? "true" : "false"),
  659. rtraceLevel.c_str(),
  660. (target == "NULL") ? NULL : target.c_str(),
  661. rev.c_str(),
  662. tags.c_str(),
  663. vmajor.c_str(),
  664. vminor.c_str(),
  665. vrev.c_str(),
  666. vproto.c_str()
  667. };
  668. PGresult *res = PQexecParams(conn,
  669. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  670. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  671. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  672. "VALUES ($1, $2, $3, $4, $5, $6, "
  673. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  674. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  675. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  676. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  677. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  678. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  679. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  680. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  681. 17,
  682. NULL,
  683. values,
  684. NULL,
  685. NULL,
  686. 0);
  687. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  688. fprintf(stderr, "ERROR: Error updating member: %s\n", PQresultErrorMessage(res));
  689. fprintf(stderr, "%s", OSUtils::jsonDump(*config, 2).c_str());
  690. PQclear(res);
  691. delete config;
  692. config = nullptr;
  693. continue;
  694. }
  695. PQclear(res);
  696. res = PQexec(conn, "BEGIN");
  697. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  698. fprintf(stderr, "ERROR: Error beginning transaction: %s\n", PQresultErrorMessage(res));
  699. PQclear(res);
  700. delete config;
  701. config = nullptr;
  702. continue;
  703. }
  704. PQclear(res);
  705. const char *v2[2] = {
  706. memberId.c_str(),
  707. networkId.c_str()
  708. };
  709. res = PQexecParams(conn,
  710. "DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  711. 2,
  712. NULL,
  713. v2,
  714. NULL,
  715. NULL,
  716. 0);
  717. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  718. fprintf(stderr, "ERROR: Error updating IP address assignments: %s\n", PQresultErrorMessage(res));
  719. PQclear(res);
  720. PQclear(PQexec(conn, "ROLLBACK"));;
  721. delete config;
  722. config = nullptr;
  723. continue;
  724. }
  725. PQclear(res);
  726. std::vector<std::string> assignments;
  727. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  728. std::string addr = *i;
  729. if (std::find(assignments.begin(), assignments.end(), addr) != assignments.end()) {
  730. continue;
  731. }
  732. const char *v3[3] = {
  733. memberId.c_str(),
  734. networkId.c_str(),
  735. addr.c_str()
  736. };
  737. res = PQexecParams(conn,
  738. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3)",
  739. 3,
  740. NULL,
  741. v3,
  742. NULL,
  743. NULL,
  744. 0);
  745. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  746. fprintf(stderr, "ERROR: Error setting IP addresses for member: %s\n", PQresultErrorMessage(res));
  747. PQclear(res);
  748. PQclear(PQexec(conn, "ROLLBACK"));
  749. break;;
  750. }
  751. }
  752. res = PQexec(conn, "COMMIT");
  753. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  754. fprintf(stderr, "ERROR: Error committing ip address data: %s\n", PQresultErrorMessage(res));
  755. }
  756. PQclear(res);
  757. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  758. const uint64_t memberidInt = OSUtils::jsonIntHex((*config)["id"], 0ULL);
  759. if (nwidInt && memberidInt) {
  760. nlohmann::json nwOrig;
  761. nlohmann::json memOrig;
  762. nlohmann::json memNew(*config);
  763. get(nwidInt, nwOrig, memberidInt, memOrig);
  764. _memberChanged(memOrig, memNew, (this->_ready>=2));
  765. } else {
  766. fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %lu-%lu\n", nwidInt, memberidInt);
  767. }
  768. } catch (std::exception &e) {
  769. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  770. }
  771. } else if (objtype == "network") {
  772. try {
  773. std::string id = (*config)["id"];
  774. std::string controllerId = _myAddressStr.c_str();
  775. std::string name = (*config)["name"];
  776. std::string remoteTraceTarget("NULL");
  777. if (!(*config)["remoteTraceTarget"].is_null()) {
  778. remoteTraceTarget = (*config)["remoteTraceTarget"];
  779. }
  780. std::string rulesSource = (*config)["rulesSource"];
  781. std::string caps = OSUtils::jsonDump((*config)["capabilitles"], -1);
  782. std::string now = std::to_string(OSUtils::now());
  783. std::string mtu = std::to_string((int)(*config)["mtu"]);
  784. std::string mcastLimit = std::to_string((int)(*config)["multicastLimit"]);
  785. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  786. std::string rules = OSUtils::jsonDump((*config)["rules"], -1);
  787. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  788. std::string v4mode = OSUtils::jsonDump((*config)["v4AssignMode"],-1);
  789. std::string v6mode = OSUtils::jsonDump((*config)["v6AssignMode"], -1);
  790. bool enableBroadcast = (*config)["enableBroadcast"];
  791. bool isPrivate = (*config)["private"];
  792. const char *values[16] = {
  793. id.c_str(),
  794. controllerId.c_str(),
  795. caps.c_str(),
  796. enableBroadcast ? "true" : "false",
  797. now.c_str(),
  798. mtu.c_str(),
  799. mcastLimit.c_str(),
  800. name.c_str(),
  801. isPrivate ? "true" : "false",
  802. rtraceLevel.c_str(),
  803. (remoteTraceTarget == "NULL" ? NULL : remoteTraceTarget.c_str()),
  804. rules.c_str(),
  805. rulesSource.c_str(),
  806. tags.c_str(),
  807. v4mode.c_str(),
  808. v6mode.c_str(),
  809. };
  810. PGresult *res = PQexecParams(conn,
  811. "UPDATE ztc_network SET controller_id = $2, capabilities = $3, enable_broadcast = $4, "
  812. "last_updated = $5, mtu = $6, multicast_limit = $7, name = $8, private = $9, "
  813. "remote_trace_level = $10, remote_trace_target = $11, rules = $12, rules_source = $13, "
  814. "tags = $14, v4_assign_mode = $15, v6_assign_mode = $16 "
  815. "WHERE id = $1",
  816. 16,
  817. NULL,
  818. values,
  819. NULL,
  820. NULL,
  821. 0);
  822. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  823. fprintf(stderr, "ERROR: Error updating network record: %s\n", PQresultErrorMessage(res));
  824. PQclear(res);
  825. delete config;
  826. config = nullptr;
  827. continue;
  828. }
  829. PQclear(res);
  830. res = PQexec(conn, "BEGIN");
  831. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  832. fprintf(stderr, "ERROR: Error beginnning transaction: %s\n", PQresultErrorMessage(res));
  833. PQclear(res);
  834. delete config;
  835. config = nullptr;
  836. continue;
  837. }
  838. PQclear(res);
  839. const char *params[1] = {
  840. id.c_str()
  841. };
  842. res = PQexecParams(conn,
  843. "DELETE FROM ztc_network_assignment_pool WHERE network_id = $1",
  844. 1,
  845. NULL,
  846. params,
  847. NULL,
  848. NULL,
  849. 0);
  850. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  851. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  852. PQclear(res);
  853. PQclear(PQexec(conn, "ROLLBACK"));
  854. delete config;
  855. config = nullptr;
  856. continue;
  857. }
  858. PQclear(res);
  859. auto pool = (*config)["ipAssignmentPools"];
  860. bool err = false;
  861. for (auto i = pool.begin(); i != pool.end(); ++i) {
  862. std::string start = (*i)["ipRangeStart"];
  863. std::string end = (*i)["ipRangeEnd"];
  864. const char *p[3] = {
  865. id.c_str(),
  866. start.c_str(),
  867. end.c_str()
  868. };
  869. res = PQexecParams(conn,
  870. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  871. "VALUES ($1, $2, $3)",
  872. 3,
  873. NULL,
  874. p,
  875. NULL,
  876. NULL,
  877. 0);
  878. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  879. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  880. PQclear(res);
  881. err = true;
  882. break;
  883. }
  884. PQclear(res);
  885. }
  886. if (err) {
  887. PQclear(PQexec(conn, "ROLLBACK"));
  888. delete config;
  889. config = nullptr;
  890. continue;
  891. }
  892. res = PQexecParams(conn,
  893. "DELETE FROM ztc_network_route WHERE network_id = $1",
  894. 1,
  895. NULL,
  896. params,
  897. NULL,
  898. NULL,
  899. 0);
  900. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  901. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  902. PQclear(res);
  903. PQclear(PQexec(conn, "ROLLBACK"));
  904. delete config;
  905. config = nullptr;
  906. continue;
  907. }
  908. auto routes = (*config)["routes"];
  909. err = false;
  910. for (auto i = routes.begin(); i != routes.end(); ++i) {
  911. std::string t = (*i)["target"];
  912. std::vector<std::string> target;
  913. std::istringstream f(t);
  914. std::string s;
  915. while(std::getline(f, s, '/')) {
  916. target.push_back(s);
  917. }
  918. if (target.empty() || target.size() != 2) {
  919. continue;
  920. }
  921. std::string targetAddr = target[0];
  922. std::string targetBits = target[1];
  923. std::string via = "NULL";
  924. if (!(*i)["via"].is_null()) {
  925. via = (*i)["via"];
  926. }
  927. const char *p[4] = {
  928. id.c_str(),
  929. targetAddr.c_str(),
  930. targetBits.c_str(),
  931. (via == "NULL" ? NULL : via.c_str()),
  932. };
  933. res = PQexecParams(conn,
  934. "INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  935. 4,
  936. NULL,
  937. p,
  938. NULL,
  939. NULL,
  940. 0);
  941. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  942. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  943. PQclear(res);
  944. err = true;
  945. break;
  946. }
  947. PQclear(res);
  948. }
  949. if (err) {
  950. PQclear(PQexec(conn, "ROLLBACK"));
  951. delete config;
  952. config = nullptr;
  953. continue;
  954. }
  955. res = PQexec(conn, "COMMIT");
  956. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  957. fprintf(stderr, "ERROR: Error committing network update: %s\n", PQresultErrorMessage(res));
  958. }
  959. PQclear(res);
  960. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  961. if (nwidInt) {
  962. nlohmann::json nwOrig;
  963. nlohmann::json nwNew(*config);
  964. get(nwidInt, nwOrig);
  965. _networkChanged(nwOrig, nwNew, true);
  966. } else {
  967. fprintf(stderr, "Can't notify network changed: %lu\n", nwidInt);
  968. }
  969. } catch (std::exception &e) {
  970. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  971. }
  972. } else if (objtype == "trace") {
  973. fprintf(stderr, "ERROR: Trace not yet implemented");
  974. } else if (objtype == "_delete_network") {
  975. try {
  976. std::string networkId = (*config)["nwid"];
  977. const char *values[1] = {
  978. networkId.c_str()
  979. };
  980. PGresult * res = PQexecParams(conn,
  981. "UPDATE ztc_network SET deleted = true WHERE id = $1",
  982. 1,
  983. NULL,
  984. values,
  985. NULL,
  986. NULL,
  987. 0);
  988. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  989. fprintf(stderr, "ERROR: Error deleting network: %s\n", PQresultErrorMessage(res));
  990. }
  991. PQclear(res);
  992. } catch (std::exception &e) {
  993. fprintf(stderr, "ERROR: Error deleting network: %s\n", e.what());
  994. }
  995. } else if (objtype == "_delete_member") {
  996. try {
  997. std::string memberId = (*config)["id"];
  998. std::string networkId = (*config)["nwid"];
  999. const char *values[2] = {
  1000. memberId.c_str(),
  1001. networkId.c_str()
  1002. };
  1003. PGresult *res = PQexecParams(conn,
  1004. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  1005. 2,
  1006. NULL,
  1007. values,
  1008. NULL,
  1009. NULL,
  1010. 0);
  1011. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1012. fprintf(stderr, "ERROR: Error deleting member: %s\n", PQresultErrorMessage(res));
  1013. }
  1014. PQclear(res);
  1015. } catch (std::exception &e) {
  1016. fprintf(stderr, "ERROR: Error deleting member: %s\n", e.what());
  1017. }
  1018. } else {
  1019. fprintf(stderr, "ERROR: unknown objtype");
  1020. }
  1021. } catch (std::exception &e) {
  1022. fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
  1023. }
  1024. delete config;
  1025. config = nullptr;
  1026. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1027. }
  1028. PQfinish(conn);
  1029. if (_run == 1) {
  1030. fprintf(stderr, "ERROR: %s commitThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1031. exit(7);
  1032. }
  1033. }
  1034. void PostgreSQL::onlineNotificationThread()
  1035. {
  1036. PGconn *conn = getPgConn();
  1037. if (PQstatus(conn) == CONNECTION_BAD) {
  1038. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  1039. PQfinish(conn);
  1040. exit(1);
  1041. }
  1042. _connected = 1;
  1043. int64_t lastUpdatedNetworkStatus = 0;
  1044. std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative;
  1045. while (_run == 1) {
  1046. if (PQstatus(conn) != CONNECTION_OK) {
  1047. fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres.");
  1048. PQfinish(conn);
  1049. exit(5);
  1050. }
  1051. // map used to send notifications to front end
  1052. std::unordered_map<std::string, std::vector<std::string>> updateMap;
  1053. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1054. {
  1055. std::lock_guard<std::mutex> l(_lastOnline_l);
  1056. lastOnline.swap(_lastOnline);
  1057. }
  1058. PGresult *res = NULL;
  1059. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1060. uint64_t nwid_i = i->first.first;
  1061. char nwidTmp[64];
  1062. char memTmp[64];
  1063. char ipTmp[64];
  1064. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1065. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  1066. auto found = _networks.find(nwid_i);
  1067. if (found == _networks.end()) {
  1068. continue; // skip members trying to join non-existant networks
  1069. }
  1070. lastOnlineCumulative[i->first] = i->second.first;
  1071. std::string networkId(nwidTmp);
  1072. std::string memberId(memTmp);
  1073. std::vector<std::string> &members = updateMap[networkId];
  1074. members.push_back(memberId);
  1075. int64_t ts = i->second.first;
  1076. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1077. std::string timestamp = std::to_string(ts);
  1078. const char *values[4] = {
  1079. networkId.c_str(),
  1080. memberId.c_str(),
  1081. (ipAddr.empty() ? NULL : ipAddr.c_str()),
  1082. timestamp.c_str(),
  1083. };
  1084. res = PQexecParams(conn,
  1085. "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ($1, $2, $3, TO_TIMESTAMP($4::double precision/1000)) "
  1086. "ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated",
  1087. 4, // number of parameters
  1088. NULL, // oid field. ignore
  1089. values, // values for substitution
  1090. NULL, // lengths in bytes of each value
  1091. NULL,
  1092. 0);
  1093. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1094. fprintf(stderr, "Error on Member Status upsert: %s\n", PQresultErrorMessage(res));
  1095. PQclear(res);
  1096. continue;
  1097. }
  1098. PQclear(res);
  1099. }
  1100. const int64_t now = OSUtils::now();
  1101. if ((now - lastUpdatedNetworkStatus) > 10000) {
  1102. lastUpdatedNetworkStatus = now;
  1103. std::vector<std::pair<uint64_t, std::shared_ptr<_Network>>> networks;
  1104. {
  1105. std::lock_guard<std::mutex> l(_networks_l);
  1106. for (auto i = _networks.begin(); i != _networks.end(); ++i) {
  1107. networks.push_back(*i);
  1108. }
  1109. }
  1110. for (auto i = networks.begin(); i != networks.end(); ++i) {
  1111. char tmp[64];
  1112. Utils::hex(i->first, tmp);
  1113. std::string networkId(tmp);
  1114. std::vector<std::string> &_notUsed = updateMap[networkId];
  1115. (void)_notUsed;
  1116. uint64_t authMemberCount = 0;
  1117. uint64_t totalMemberCount = 0;
  1118. uint64_t onlineMemberCount = 0;
  1119. uint64_t bridgeCount = 0;
  1120. uint64_t ts = now;
  1121. {
  1122. std::lock_guard<std::mutex> l2(i->second->lock);
  1123. authMemberCount = i->second->authorizedMembers.size();
  1124. totalMemberCount = i->second->members.size();
  1125. bridgeCount = i->second->activeBridgeMembers.size();
  1126. for (auto m=i->second->members.begin(); m != i->second->members.end(); ++m) {
  1127. auto lo = lastOnlineCumulative.find(std::pair<uint64_t,uint64_t>(i->first, m->first));
  1128. if (lo != lastOnlineCumulative.end()) {
  1129. if ((now - lo->second) <= (ZT_NETWORK_AUTOCONF_DELAY * 2)) {
  1130. ++onlineMemberCount;
  1131. } else {
  1132. lastOnlineCumulative.erase(lo);
  1133. }
  1134. }
  1135. }
  1136. }
  1137. std::string bc = std::to_string(bridgeCount);
  1138. std::string amc = std::to_string(authMemberCount);
  1139. std::string omc = std::to_string(onlineMemberCount);
  1140. std::string tmc = std::to_string(totalMemberCount);
  1141. std::string timestamp = std::to_string(ts);
  1142. const char *values[6] = {
  1143. networkId.c_str(),
  1144. bc.c_str(),
  1145. amc.c_str(),
  1146. omc.c_str(),
  1147. tmc.c_str(),
  1148. timestamp.c_str()
  1149. };
  1150. res = PQexecParams(conn, "INSERT INTO ztc_network_status (network_id, bridge_count, authorized_member_count, "
  1151. "online_member_count, total_member_count, last_modified) VALUES ($1, $2, $3, $4, $5, TO_TIMESTAMP($6::double precision/1000)) "
  1152. "ON CONFLICT (network_id) DO UPDATE SET bridge_count = EXCLUDED.bridge_count, "
  1153. "authorized_member_count = EXCLUDED.authorized_member_count, online_member_count = EXCLUDED.online_member_count, "
  1154. "total_member_count = EXCLUDED.total_member_count, last_modified = EXCLUDED.last_modified",
  1155. 6,
  1156. NULL,
  1157. values,
  1158. NULL,
  1159. NULL,
  1160. 0);
  1161. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1162. fprintf(stderr, "ERROR: Error on Network Status upsert (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1163. PQclear(res);
  1164. continue;
  1165. }
  1166. PQclear(res);
  1167. }
  1168. }
  1169. // for (auto it = updateMap.begin(); it != updateMap.end(); ++it) {
  1170. // std::string networkId = it->first;
  1171. // std::vector<std::string> members = it->second;
  1172. // std::stringstream queryBuilder;
  1173. // std::string membersStr = ::join(members, ",");
  1174. // queryBuilder << "NOTIFY controller, '" << networkId << ":" << membersStr << "'";
  1175. // std::string query = queryBuilder.str();
  1176. // PGresult *res = PQexec(conn,query.c_str());
  1177. // if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1178. // fprintf(stderr, "ERROR: Error sending NOTIFY: %s\n", PQresultErrorMessage(res));
  1179. // }
  1180. // PQclear(res);
  1181. // }
  1182. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  1183. }
  1184. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  1185. PQfinish(conn);
  1186. if (_run == 1) {
  1187. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1188. exit(6);
  1189. }
  1190. }
  1191. PGconn *PostgreSQL::getPgConn(OverrideMode m) {
  1192. if (m == ALLOW_PGBOUNCER_OVERRIDE) {
  1193. char *connStr = getenv("PGBOUNCER_CONNSTR");
  1194. if (connStr != NULL) {
  1195. fprintf(stderr, "PGBouncer Override\n");
  1196. return PQconnectdb(connStr);
  1197. }
  1198. }
  1199. return PQconnectdb(_connString.c_str());
  1200. }
  1201. #endif //ZT_CONTROLLER_USE_LIBPQ