PostgreSQL.cpp 43 KB

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