PostgreSQL.cpp 45 KB

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