PostgreSQL.cpp 43 KB

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