PostgreSQL.cpp 40 KB

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