2
0

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. /*
  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())||(!_compareRecords(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())||(!_compareRecords(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. } catch (std::exception &e) {
  180. fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what());
  181. } catch (...) {
  182. fprintf(stderr, "Unknown error on PostgreSQL::save\n");
  183. }
  184. return modified;
  185. }
  186. void PostgreSQL::eraseNetwork(const uint64_t networkId)
  187. {
  188. char tmp2[24];
  189. waitForReady();
  190. Utils::hex(networkId, tmp2);
  191. std::pair<nlohmann::json,bool> tmp;
  192. tmp.first["id"] = tmp2;
  193. tmp.first["objtype"] = "_delete_network";
  194. tmp.second = true;
  195. _commitQueue.post(tmp);
  196. }
  197. void PostgreSQL::eraseMember(const uint64_t networkId, const uint64_t memberId)
  198. {
  199. char tmp2[24];
  200. std::pair<nlohmann::json,bool> tmp;
  201. Utils::hex(networkId, tmp2);
  202. tmp.first["nwid"] = tmp2;
  203. Utils::hex(memberId, tmp2);
  204. tmp.first["id"] = tmp2;
  205. tmp.first["objtype"] = "_delete_member";
  206. tmp.second = true;
  207. _commitQueue.post(tmp);
  208. }
  209. void PostgreSQL::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress)
  210. {
  211. std::lock_guard<std::mutex> l(_lastOnline_l);
  212. std::pair<int64_t, InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId, memberId)];
  213. i.first = OSUtils::now();
  214. if (physicalAddress) {
  215. i.second = physicalAddress;
  216. }
  217. }
  218. void PostgreSQL::initializeNetworks(PGconn *conn)
  219. {
  220. try {
  221. if (PQstatus(conn) != CONNECTION_OK) {
  222. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  223. exit(1);
  224. }
  225. const char *params[1] = {
  226. _myAddressStr.c_str()
  227. };
  228. PGresult *res = PQexecParams(conn, "SELECT id, EXTRACT(EPOCH FROM creation_time AT TIME ZONE 'UTC')*1000, capabilities, "
  229. "enable_broadcast, EXTRACT(EPOCH FROM last_modified AT TIME ZONE 'UTC')*1000, mtu, multicast_limit, name, private, remote_trace_level, "
  230. "remote_trace_target, revision, rules, tags, v4_assign_mode, v6_assign_mode FROM ztc_network "
  231. "WHERE deleted = false AND controller_id = $1",
  232. 1,
  233. NULL,
  234. params,
  235. NULL,
  236. NULL,
  237. 0);
  238. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  239. fprintf(stderr, "Networks Initialization Failed: %s", PQerrorMessage(conn));
  240. PQclear(res);
  241. exit(1);
  242. }
  243. int numRows = PQntuples(res);
  244. for (int i = 0; i < numRows; ++i) {
  245. json empty;
  246. json config;
  247. const char *nwidparam[1] = {
  248. PQgetvalue(res, i, 0)
  249. };
  250. config["id"] = PQgetvalue(res, i, 0);
  251. config["nwid"] = PQgetvalue(res, i, 0);
  252. try {
  253. config["creationTime"] = std::stoull(PQgetvalue(res, i, 1));
  254. } catch (std::exception &e) {
  255. config["creationTime"] = 0ULL;
  256. //fprintf(stderr, "Error converting creation time: %s\n", PQgetvalue(res, i, 1));
  257. }
  258. config["capabilities"] = json::parse(PQgetvalue(res, i, 2));
  259. config["enableBroadcast"] = (strcmp(PQgetvalue(res, i, 3),"t")==0);
  260. try {
  261. config["lastModified"] = std::stoull(PQgetvalue(res, i, 4));
  262. } catch (std::exception &e) {
  263. config["lastModified"] = 0ULL;
  264. //fprintf(stderr, "Error converting last modified: %s\n", PQgetvalue(res, i, 4));
  265. }
  266. try {
  267. config["mtu"] = std::stoi(PQgetvalue(res, i, 5));
  268. } catch (std::exception &e) {
  269. config["mtu"] = 2800;
  270. }
  271. try {
  272. config["multicastLimit"] = std::stoi(PQgetvalue(res, i, 6));
  273. } catch (std::exception &e) {
  274. config["multicastLimit"] = 64;
  275. }
  276. config["name"] = PQgetvalue(res, i, 7);
  277. config["private"] = (strcmp(PQgetvalue(res, i, 8),"t")==0);
  278. try {
  279. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
  280. } catch (std::exception &e) {
  281. config["remoteTraceLevel"] = 0;
  282. }
  283. config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
  284. try {
  285. config["revision"] = std::stoull(PQgetvalue(res, i, 11));
  286. } catch (std::exception &e) {
  287. config["revision"] = 0ULL;
  288. //fprintf(stderr, "Error converting revision: %s\n", PQgetvalue(res, i, 11));
  289. }
  290. config["rules"] = json::parse(PQgetvalue(res, i, 12));
  291. config["tags"] = json::parse(PQgetvalue(res, i, 13));
  292. config["v4AssignMode"] = json::parse(PQgetvalue(res, i, 14));
  293. config["v6AssignMode"] = json::parse(PQgetvalue(res, i, 15));
  294. config["objtype"] = "network";
  295. config["ipAssignmentPools"] = json::array();
  296. config["routes"] = json::array();
  297. PGresult *r2 = PQexecParams(conn,
  298. "SELECT host(ip_range_start), host(ip_range_end) FROM ztc_network_assignment_pool WHERE network_id = $1",
  299. 1,
  300. NULL,
  301. nwidparam,
  302. NULL,
  303. NULL,
  304. 0);
  305. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  306. fprintf(stderr, "ERROR: Error retreiving IP pools for network: %s\n", PQresultErrorMessage(r2));
  307. PQclear(r2);
  308. PQclear(res);
  309. exit(1);
  310. }
  311. int n = PQntuples(r2);
  312. for (int j = 0; j < n; ++j) {
  313. json ip;
  314. ip["ipRangeStart"] = PQgetvalue(r2, j, 0);
  315. ip["ipRangeEnd"] = PQgetvalue(r2, j, 1);
  316. config["ipAssignmentPools"].push_back(ip);
  317. }
  318. PQclear(r2);
  319. r2 = PQexecParams(conn,
  320. "SELECT host(address), bits, host(via) FROM ztc_network_route WHERE network_id = $1",
  321. 1,
  322. NULL,
  323. nwidparam,
  324. NULL,
  325. NULL,
  326. 0);
  327. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  328. fprintf(stderr, "ERROR: Error retreiving routes for network: %s\n", PQresultErrorMessage(r2));
  329. PQclear(r2);
  330. PQclear(res);
  331. exit(1);
  332. }
  333. n = PQntuples(r2);
  334. for (int j = 0; j < n; ++j) {
  335. std::string addr = PQgetvalue(r2, j, 0);
  336. std::string bits = PQgetvalue(r2, j, 1);
  337. std::string via = PQgetvalue(r2, j, 2);
  338. json route;
  339. route["target"] = addr + "/" + bits;
  340. if (via == "NULL") {
  341. route["via"] = nullptr;
  342. } else {
  343. route["via"] = via;
  344. }
  345. config["routes"].push_back(route);
  346. }
  347. PQclear(r2);
  348. _networkChanged(empty, config, false);
  349. }
  350. PQclear(res);
  351. if (++this->_ready == 2) {
  352. if (_waitNoticePrinted) {
  353. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  354. }
  355. _readyLock.unlock();
  356. }
  357. } catch (std::exception &e) {
  358. fprintf(stderr, "ERROR: Error initializing networks: %s", e.what());
  359. exit(-1);
  360. }
  361. }
  362. void PostgreSQL::initializeMembers(PGconn *conn)
  363. {
  364. try {
  365. if (PQstatus(conn) != CONNECTION_OK) {
  366. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  367. exit(1);
  368. }
  369. const char *params[1] = {
  370. _myAddressStr.c_str()
  371. };
  372. PGresult *res = PQexecParams(conn,
  373. "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, "
  374. " EXTRACT(EPOCH FROM m.last_authorized_time AT TIME ZONE 'UTC')*1000, "
  375. " EXTRACT(EPOCH FROM m.last_deauthorized_time AT TIME ZONE 'UTC')*1000, "
  376. " m.remote_trace_level, m.remote_trace_target, m.tags, m.v_major, m.v_minor, m.v_rev, m.v_proto, "
  377. " m.no_auto_assign_ips, m.revision "
  378. "FROM ztc_member m "
  379. "INNER JOIN ztc_network n "
  380. " ON n.id = m.network_id "
  381. "WHERE n.controller_id = $1 AND m.deleted = false",
  382. 1,
  383. NULL,
  384. params,
  385. NULL,
  386. NULL,
  387. 0);
  388. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  389. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  390. PQclear(res);
  391. exit(1);
  392. }
  393. int numRows = PQntuples(res);
  394. for (int i = 0; i < numRows; ++i) {
  395. json empty;
  396. json config;
  397. std::string memberId(PQgetvalue(res, i, 0));
  398. std::string networkId(PQgetvalue(res, i, 1));
  399. std::string ctime = PQgetvalue(res, i, 5);
  400. config["id"] = memberId;
  401. config["nwid"] = networkId;
  402. config["activeBridge"] = (strcmp(PQgetvalue(res, i, 2), "t") == 0);
  403. config["authorized"] = (strcmp(PQgetvalue(res, i, 3), "t") == 0);
  404. try {
  405. config["capabilities"] = json::parse(PQgetvalue(res, i, 4));
  406. } catch (std::exception &e) {
  407. config["capabilities"] = json::array();
  408. }
  409. try {
  410. config["creationTime"] = std::stoull(PQgetvalue(res, i, 5));
  411. } catch (std::exception &e) {
  412. config["creationTime"] = 0ULL;
  413. //fprintf(stderr, "Error upding creation time (member): %s\n", PQgetvalue(res, i, 5));
  414. }
  415. config["identity"] = PQgetvalue(res, i, 6);
  416. try {
  417. config["lastAuthorizedTime"] = std::stoull(PQgetvalue(res, i, 7));
  418. } catch(std::exception &e) {
  419. config["lastAuthorizedTime"] = 0ULL;
  420. //fprintf(stderr, "Error updating last auth time (member): %s\n", PQgetvalue(res, i, 7));
  421. }
  422. try {
  423. config["lastDeauthorizedTime"] = std::stoull(PQgetvalue(res, i, 8));
  424. } catch( std::exception &e) {
  425. config["lastDeauthorizedTime"] = 0ULL;
  426. //fprintf(stderr, "Error updating last deauth time (member): %s\n", PQgetvalue(res, i, 8));
  427. }
  428. try {
  429. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
  430. } catch (std::exception &e) {
  431. config["remoteTraceLevel"] = 0;
  432. }
  433. config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
  434. try {
  435. config["tags"] = json::parse(PQgetvalue(res, i, 11));
  436. } catch (std::exception &e) {
  437. config["tags"] = json::array();
  438. }
  439. try {
  440. config["vMajor"] = std::stoi(PQgetvalue(res, i, 12));
  441. } catch(std::exception &e) {
  442. config["vMajor"] = -1;
  443. }
  444. try {
  445. config["vMinor"] = std::stoi(PQgetvalue(res, i, 13));
  446. } catch (std::exception &e) {
  447. config["vMinor"] = -1;
  448. }
  449. try {
  450. config["vRev"] = std::stoi(PQgetvalue(res, i, 14));
  451. } catch (std::exception &e) {
  452. config["vRev"] = -1;
  453. }
  454. try {
  455. config["vProto"] = std::stoi(PQgetvalue(res, i, 15));
  456. } catch (std::exception &e) {
  457. config["vProto"] = -1;
  458. }
  459. config["noAutoAssignIps"] = (strcmp(PQgetvalue(res, i, 16), "t") == 0);
  460. try {
  461. config["revision"] = std::stoull(PQgetvalue(res, i, 17));
  462. } catch (std::exception &e) {
  463. config["revision"] = 0ULL;
  464. //fprintf(stderr, "Error updating revision (member): %s\n", PQgetvalue(res, i, 17));
  465. }
  466. config["objtype"] = "member";
  467. config["ipAssignments"] = json::array();
  468. const char *p2[2] = {
  469. memberId.c_str(),
  470. networkId.c_str()
  471. };
  472. PGresult *r2 = PQexecParams(conn,
  473. "SELECT DISTINCT address FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  474. 2,
  475. NULL,
  476. p2,
  477. NULL,
  478. NULL,
  479. 0);
  480. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  481. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  482. PQclear(r2);
  483. PQclear(res);
  484. exit(1);
  485. }
  486. int n = PQntuples(r2);
  487. for (int j = 0; j < n; ++j) {
  488. config["ipAssignments"].push_back(PQgetvalue(r2, j, 0));
  489. }
  490. _memberChanged(empty, config, false);
  491. }
  492. PQclear(res);
  493. if (++this->_ready == 2) {
  494. if (_waitNoticePrinted) {
  495. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  496. }
  497. _readyLock.unlock();
  498. }
  499. } catch (std::exception &e) {
  500. fprintf(stderr, "ERROR: Error initializing members: %s\n", e.what());
  501. exit(-1);
  502. }
  503. }
  504. void PostgreSQL::heartbeat()
  505. {
  506. char publicId[1024];
  507. char hostnameTmp[1024];
  508. _myId.toString(false,publicId);
  509. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  510. hostnameTmp[0] = (char)0;
  511. } else {
  512. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  513. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  514. hostnameTmp[i] = (char)0;
  515. break;
  516. }
  517. }
  518. }
  519. const char *controllerId = _myAddressStr.c_str();
  520. const char *publicIdentity = publicId;
  521. const char *hostname = hostnameTmp;
  522. PGconn *conn = getPgConn();
  523. if (PQstatus(conn) == CONNECTION_BAD) {
  524. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  525. PQfinish(conn);
  526. exit(1);
  527. }
  528. while (_run == 1) {
  529. if(PQstatus(conn) != CONNECTION_OK) {
  530. fprintf(stderr, "%s heartbeat thread lost connection to Database\n", _myAddressStr.c_str());
  531. PQfinish(conn);
  532. exit(6);
  533. }
  534. if (conn) {
  535. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  536. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  537. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  538. std::string build = std::to_string(ZEROTIER_ONE_VERSION_BUILD);
  539. std::string now = std::to_string(OSUtils::now());
  540. std::string host_port = std::to_string(_listenPort);
  541. std::string use_rabbitmq = (_mqc != NULL) ? "true" : "false";
  542. const char *values[10] = {
  543. controllerId,
  544. hostname,
  545. now.c_str(),
  546. publicIdentity,
  547. major.c_str(),
  548. minor.c_str(),
  549. rev.c_str(),
  550. build.c_str(),
  551. host_port.c_str(),
  552. use_rabbitmq.c_str()
  553. };
  554. PGresult *res = PQexecParams(conn,
  555. "INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build, host_port, use_rabbitmq) "
  556. "VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8, $9, $10) "
  557. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  558. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  559. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev, host_port = EXCLUDED.host_port, "
  560. "use_rabbitmq = EXCLUDED.use_rabbitmq",
  561. 10, // number of parameters
  562. NULL, // oid field. ignore
  563. values, // values for substitution
  564. NULL, // lengths in bytes of each value
  565. NULL, // binary?
  566. 0);
  567. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  568. fprintf(stderr, "Heartbeat Update Failed: %s\n", PQresultErrorMessage(res));
  569. }
  570. PQclear(res);
  571. }
  572. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  573. }
  574. PQfinish(conn);
  575. conn = NULL;
  576. }
  577. void PostgreSQL::membersDbWatcher()
  578. {
  579. PGconn *conn = getPgConn(NO_OVERRIDE);
  580. if (PQstatus(conn) == CONNECTION_BAD) {
  581. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  582. PQfinish(conn);
  583. exit(1);
  584. }
  585. initializeMembers(conn);
  586. if (this->_mqc != NULL) {
  587. PQfinish(conn);
  588. conn = NULL;
  589. _membersWatcher_RabbitMQ();
  590. } else {
  591. _membersWatcher_Postgres(conn);
  592. PQfinish(conn);
  593. conn = NULL;
  594. }
  595. if (_run == 1) {
  596. fprintf(stderr, "ERROR: %s membersDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  597. exit(9);
  598. }
  599. fprintf(stderr, "Exited membersDbWatcher\n");
  600. }
  601. void PostgreSQL::_membersWatcher_Postgres(PGconn *conn) {
  602. char buf[11] = {0};
  603. std::string cmd = "LISTEN member_" + std::string(_myAddress.toString(buf));
  604. PGresult *res = PQexec(conn, cmd.c_str());
  605. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  606. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  607. PQclear(res);
  608. PQfinish(conn);
  609. exit(1);
  610. }
  611. PQclear(res); res = NULL;
  612. while(_run == 1) {
  613. if (PQstatus(conn) != CONNECTION_OK) {
  614. fprintf(stderr, "ERROR: Member Watcher lost connection to Postgres.");
  615. exit(-1);
  616. }
  617. PGnotify *notify = NULL;
  618. PQconsumeInput(conn);
  619. while ((notify = PQnotifies(conn)) != NULL) {
  620. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  621. try {
  622. json tmp(json::parse(notify->extra));
  623. json &ov = tmp["old_val"];
  624. json &nv = tmp["new_val"];
  625. json oldConfig, newConfig;
  626. if (ov.is_object()) oldConfig = ov;
  627. if (nv.is_object()) newConfig = nv;
  628. if (oldConfig.is_object() || newConfig.is_object()) {
  629. _memberChanged(oldConfig,newConfig,(this->_ready>=2));
  630. }
  631. } catch (...) {} // ignore bad records
  632. free(notify);
  633. }
  634. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  635. }
  636. }
  637. void PostgreSQL::_membersWatcher_RabbitMQ() {
  638. char buf[11] = {0};
  639. std::string qname = "member_"+ std::string(_myAddress.toString(buf));
  640. RabbitMQ rmq(_mqc, qname.c_str());
  641. try {
  642. rmq.init();
  643. } catch (std::runtime_error &e) {
  644. fprintf(stderr, "RABBITMQ ERROR: %s\n", e.what());
  645. exit(11);
  646. }
  647. while (_run == 1) {
  648. try {
  649. std::string msg = rmq.consume();
  650. // fprintf(stderr, "Got Member Update: %s\n", msg.c_str());
  651. if (msg.empty()) {
  652. continue;
  653. }
  654. json tmp(json::parse(msg));
  655. json &ov = tmp["old_val"];
  656. json &nv = tmp["new_val"];
  657. json oldConfig, newConfig;
  658. if (ov.is_object()) oldConfig = ov;
  659. if (nv.is_object()) newConfig = nv;
  660. if (oldConfig.is_object() || newConfig.is_object()) {
  661. _memberChanged(oldConfig,newConfig,(this->_ready>=2));
  662. }
  663. } catch (std::runtime_error &e) {
  664. fprintf(stderr, "RABBITMQ ERROR member change: %s\n", e.what());
  665. break;
  666. } catch(std::exception &e ) {
  667. fprintf(stderr, "RABBITMQ ERROR member change: %s\n", e.what());
  668. } catch(...) {
  669. fprintf(stderr, "RABBITMQ ERROR member change: unknown error\n");
  670. }
  671. }
  672. }
  673. void PostgreSQL::networksDbWatcher()
  674. {
  675. PGconn *conn = getPgConn(NO_OVERRIDE);
  676. if (PQstatus(conn) == CONNECTION_BAD) {
  677. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  678. PQfinish(conn);
  679. exit(1);
  680. }
  681. initializeNetworks(conn);
  682. if (this->_mqc != NULL) {
  683. PQfinish(conn);
  684. conn = NULL;
  685. _networksWatcher_RabbitMQ();
  686. } else {
  687. _networksWatcher_Postgres(conn);
  688. PQfinish(conn);
  689. conn = NULL;
  690. }
  691. if (_run == 1) {
  692. fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  693. exit(8);
  694. }
  695. fprintf(stderr, "Exited membersDbWatcher\n");
  696. }
  697. void PostgreSQL::_networksWatcher_Postgres(PGconn *conn) {
  698. char buf[11] = {0};
  699. std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
  700. PGresult *res = PQexec(conn, cmd.c_str());
  701. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  702. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  703. PQclear(res);
  704. PQfinish(conn);
  705. exit(1);
  706. }
  707. PQclear(res); res = NULL;
  708. while(_run == 1) {
  709. if (PQstatus(conn) != CONNECTION_OK) {
  710. fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
  711. exit(-1);
  712. }
  713. PGnotify *notify = NULL;
  714. PQconsumeInput(conn);
  715. while ((notify = PQnotifies(conn)) != NULL) {
  716. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  717. try {
  718. json tmp(json::parse(notify->extra));
  719. json &ov = tmp["old_val"];
  720. json &nv = tmp["new_val"];
  721. json oldConfig, newConfig;
  722. if (ov.is_object()) oldConfig = ov;
  723. if (nv.is_object()) newConfig = nv;
  724. if (oldConfig.is_object()||newConfig.is_object()) {
  725. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  726. }
  727. } catch (...) {} // ignore bad records
  728. free(notify);
  729. }
  730. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  731. }
  732. }
  733. void PostgreSQL::_networksWatcher_RabbitMQ() {
  734. char buf[11] = {0};
  735. std::string qname = "network_"+ std::string(_myAddress.toString(buf));
  736. RabbitMQ rmq(_mqc, qname.c_str());
  737. try {
  738. rmq.init();
  739. } catch (std::runtime_error &e) {
  740. fprintf(stderr, "RABBITMQ ERROR: %s\n", e.what());
  741. exit(11);
  742. }
  743. while (_run == 1) {
  744. try {
  745. std::string msg = rmq.consume();
  746. if (msg.empty()) {
  747. continue;
  748. }
  749. // fprintf(stderr, "Got network update: %s\n", msg.c_str());
  750. json tmp(json::parse(msg));
  751. json &ov = tmp["old_val"];
  752. json &nv = tmp["new_val"];
  753. json oldConfig, newConfig;
  754. if (ov.is_object()) oldConfig = ov;
  755. if (nv.is_object()) newConfig = nv;
  756. if (oldConfig.is_object()||newConfig.is_object()) {
  757. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  758. }
  759. } catch (std::runtime_error &e) {
  760. fprintf(stderr, "RABBITMQ ERROR: %s\n", e.what());
  761. break;
  762. } catch (std::exception &e) {
  763. fprintf(stderr, "RABBITMQ ERROR network watcher: %s\n", e.what());
  764. } catch(...) {
  765. fprintf(stderr, "RABBITMQ ERROR network watcher: unknown error\n");
  766. }
  767. }
  768. }
  769. void PostgreSQL::commitThread()
  770. {
  771. PGconn *conn = getPgConn();
  772. if (PQstatus(conn) == CONNECTION_BAD) {
  773. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  774. PQfinish(conn);
  775. exit(1);
  776. }
  777. std::pair<nlohmann::json,bool> qitem;
  778. while(_commitQueue.get(qitem)&(_run == 1)) {
  779. if (!qitem.first.is_object()) {
  780. continue;
  781. }
  782. if (PQstatus(conn) == CONNECTION_BAD) {
  783. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  784. PQfinish(conn);
  785. exit(1);
  786. }
  787. try {
  788. nlohmann::json *config = &(qitem.first);
  789. const std::string objtype = (*config)["objtype"];
  790. if (objtype == "member") {
  791. try {
  792. std::string memberId = (*config)["id"];
  793. std::string networkId = (*config)["nwid"];
  794. std::string identity = (*config)["identity"];
  795. std::string target = "NULL";
  796. if (!(*config)["remoteTraceTarget"].is_null()) {
  797. target = (*config)["remoteTraceTarget"];
  798. }
  799. std::string caps = OSUtils::jsonDump((*config)["capabilities"], -1);
  800. std::string lastAuthTime = std::to_string((long long)(*config)["lastAuthorizedTime"]);
  801. std::string lastDeauthTime = std::to_string((long long)(*config)["lastDeauthorizedTime"]);
  802. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  803. std::string rev = std::to_string((unsigned long long)(*config)["revision"]);
  804. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  805. std::string vmajor = std::to_string((int)(*config)["vMajor"]);
  806. std::string vminor = std::to_string((int)(*config)["vMinor"]);
  807. std::string vrev = std::to_string((int)(*config)["vRev"]);
  808. std::string vproto = std::to_string((int)(*config)["vProto"]);
  809. const char *values[19] = {
  810. memberId.c_str(),
  811. networkId.c_str(),
  812. ((*config)["activeBridge"] ? "true" : "false"),
  813. ((*config)["authorized"] ? "true" : "false"),
  814. caps.c_str(),
  815. identity.c_str(),
  816. lastAuthTime.c_str(),
  817. lastDeauthTime.c_str(),
  818. ((*config)["noAutoAssignIps"] ? "true" : "false"),
  819. rtraceLevel.c_str(),
  820. (target == "NULL") ? NULL : target.c_str(),
  821. rev.c_str(),
  822. tags.c_str(),
  823. vmajor.c_str(),
  824. vminor.c_str(),
  825. vrev.c_str(),
  826. vproto.c_str()
  827. };
  828. PGresult *res = PQexecParams(conn,
  829. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  830. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  831. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  832. "VALUES ($1, $2, $3, $4, $5, $6, "
  833. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  834. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  835. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  836. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  837. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  838. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  839. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  840. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  841. 17,
  842. NULL,
  843. values,
  844. NULL,
  845. NULL,
  846. 0);
  847. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  848. fprintf(stderr, "ERROR: Error updating member: %s\n", PQresultErrorMessage(res));
  849. fprintf(stderr, "%s", OSUtils::jsonDump(*config, 2).c_str());
  850. PQclear(res);
  851. delete config;
  852. config = nullptr;
  853. continue;
  854. }
  855. PQclear(res);
  856. res = PQexec(conn, "BEGIN");
  857. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  858. fprintf(stderr, "ERROR: Error beginning transaction: %s\n", PQresultErrorMessage(res));
  859. PQclear(res);
  860. delete config;
  861. config = nullptr;
  862. continue;
  863. }
  864. PQclear(res);
  865. const char *v2[2] = {
  866. memberId.c_str(),
  867. networkId.c_str()
  868. };
  869. res = PQexecParams(conn,
  870. "DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  871. 2,
  872. NULL,
  873. v2,
  874. NULL,
  875. NULL,
  876. 0);
  877. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  878. fprintf(stderr, "ERROR: Error updating IP address assignments: %s\n", PQresultErrorMessage(res));
  879. PQclear(res);
  880. PQclear(PQexec(conn, "ROLLBACK"));;
  881. delete config;
  882. config = nullptr;
  883. continue;
  884. }
  885. PQclear(res);
  886. std::vector<std::string> assignments;
  887. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  888. std::string addr = *i;
  889. if (std::find(assignments.begin(), assignments.end(), addr) != assignments.end()) {
  890. continue;
  891. }
  892. const char *v3[3] = {
  893. memberId.c_str(),
  894. networkId.c_str(),
  895. addr.c_str()
  896. };
  897. res = PQexecParams(conn,
  898. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3)",
  899. 3,
  900. NULL,
  901. v3,
  902. NULL,
  903. NULL,
  904. 0);
  905. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  906. fprintf(stderr, "ERROR: Error setting IP addresses for member: %s\n", PQresultErrorMessage(res));
  907. PQclear(res);
  908. PQclear(PQexec(conn, "ROLLBACK"));
  909. break;;
  910. }
  911. }
  912. res = PQexec(conn, "COMMIT");
  913. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  914. fprintf(stderr, "ERROR: Error committing ip address data: %s\n", PQresultErrorMessage(res));
  915. }
  916. PQclear(res);
  917. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  918. const uint64_t memberidInt = OSUtils::jsonIntHex((*config)["id"], 0ULL);
  919. if (nwidInt && memberidInt) {
  920. nlohmann::json nwOrig;
  921. nlohmann::json memOrig;
  922. nlohmann::json memNew(*config);
  923. get(nwidInt, nwOrig, memberidInt, memOrig);
  924. _memberChanged(memOrig, memNew, qitem.second);
  925. } else {
  926. fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %llu-%llu\n", (unsigned long long)nwidInt, (unsigned long long)memberidInt);
  927. }
  928. } catch (std::exception &e) {
  929. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  930. }
  931. } else if (objtype == "network") {
  932. try {
  933. std::string id = (*config)["id"];
  934. std::string controllerId = _myAddressStr.c_str();
  935. std::string name = (*config)["name"];
  936. std::string remoteTraceTarget("NULL");
  937. if (!(*config)["remoteTraceTarget"].is_null()) {
  938. remoteTraceTarget = (*config)["remoteTraceTarget"];
  939. }
  940. std::string rulesSource;
  941. if ((*config)["rulesSource"].is_string()) {
  942. rulesSource = (*config)["rulesSource"];
  943. }
  944. std::string caps = OSUtils::jsonDump((*config)["capabilitles"], -1);
  945. std::string now = std::to_string(OSUtils::now());
  946. std::string mtu = std::to_string((int)(*config)["mtu"]);
  947. std::string mcastLimit = std::to_string((int)(*config)["multicastLimit"]);
  948. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  949. std::string rules = OSUtils::jsonDump((*config)["rules"], -1);
  950. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  951. std::string v4mode = OSUtils::jsonDump((*config)["v4AssignMode"],-1);
  952. std::string v6mode = OSUtils::jsonDump((*config)["v6AssignMode"], -1);
  953. bool enableBroadcast = (*config)["enableBroadcast"];
  954. bool isPrivate = (*config)["private"];
  955. const char *values[16] = {
  956. id.c_str(),
  957. controllerId.c_str(),
  958. caps.c_str(),
  959. enableBroadcast ? "true" : "false",
  960. now.c_str(),
  961. mtu.c_str(),
  962. mcastLimit.c_str(),
  963. name.c_str(),
  964. isPrivate ? "true" : "false",
  965. rtraceLevel.c_str(),
  966. (remoteTraceTarget == "NULL" ? NULL : remoteTraceTarget.c_str()),
  967. rules.c_str(),
  968. rulesSource.c_str(),
  969. tags.c_str(),
  970. v4mode.c_str(),
  971. v6mode.c_str(),
  972. };
  973. PGresult *res = PQexecParams(conn,
  974. "INSERT INTO ztc_network (id, controller_id, capabilities, enable_broadcast, "
  975. "last_modified, mtu, multicast_limit, name, private, "
  976. "remote_trace_level, remote_trace_target, rules, rules_source, "
  977. "tags, v4_assign_mode, v6_assign_mode) VALUES ("
  978. "$1, $2, $3, $4, TO_TIMESTAMP($5::double precision/1000), $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) "
  979. "ON CONFLICT (id) DO UPDATE set controller_id = EXCLUDED.controller_id, "
  980. "capabilities = EXCLUDED.capabilities, enable_broadcast = EXCLUDED.enable_broadcast, "
  981. "last_modified = EXCLUDED.last_modified, mtu = EXCLUDED.mtu, "
  982. "multicast_limit = EXCLUDED.multicast_limit, name = EXCLUDED.name, "
  983. "private = EXCLUDED.private, remote_trace_level = EXCLUDED.remote_trace_level, "
  984. "remote_trace_target = EXCLUDED.remote_trace_target, rules = EXCLUDED.rules, "
  985. "rules_source = EXCLUDED.rules_source, tags = EXCLUDED.tags, "
  986. "v4_assign_mode = EXCLUDED.v4_assign_mode, v6_assign_mode = EXCLUDED.v6_assign_mode",
  987. 16,
  988. NULL,
  989. values,
  990. NULL,
  991. NULL,
  992. 0);
  993. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  994. fprintf(stderr, "ERROR: Error updating network record: %s\n", PQresultErrorMessage(res));
  995. PQclear(res);
  996. delete config;
  997. config = nullptr;
  998. continue;
  999. }
  1000. PQclear(res);
  1001. res = PQexec(conn, "BEGIN");
  1002. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1003. fprintf(stderr, "ERROR: Error beginnning transaction: %s\n", PQresultErrorMessage(res));
  1004. PQclear(res);
  1005. delete config;
  1006. config = nullptr;
  1007. continue;
  1008. }
  1009. PQclear(res);
  1010. const char *params[1] = {
  1011. id.c_str()
  1012. };
  1013. res = PQexecParams(conn,
  1014. "DELETE FROM ztc_network_assignment_pool WHERE network_id = $1",
  1015. 1,
  1016. NULL,
  1017. params,
  1018. NULL,
  1019. NULL,
  1020. 0);
  1021. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1022. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  1023. PQclear(res);
  1024. PQclear(PQexec(conn, "ROLLBACK"));
  1025. delete config;
  1026. config = nullptr;
  1027. continue;
  1028. }
  1029. PQclear(res);
  1030. auto pool = (*config)["ipAssignmentPools"];
  1031. bool err = false;
  1032. for (auto i = pool.begin(); i != pool.end(); ++i) {
  1033. std::string start = (*i)["ipRangeStart"];
  1034. std::string end = (*i)["ipRangeEnd"];
  1035. const char *p[3] = {
  1036. id.c_str(),
  1037. start.c_str(),
  1038. end.c_str()
  1039. };
  1040. res = PQexecParams(conn,
  1041. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  1042. "VALUES ($1, $2, $3)",
  1043. 3,
  1044. NULL,
  1045. p,
  1046. NULL,
  1047. NULL,
  1048. 0);
  1049. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1050. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  1051. PQclear(res);
  1052. err = true;
  1053. break;
  1054. }
  1055. PQclear(res);
  1056. }
  1057. if (err) {
  1058. PQclear(PQexec(conn, "ROLLBACK"));
  1059. delete config;
  1060. config = nullptr;
  1061. continue;
  1062. }
  1063. res = PQexecParams(conn,
  1064. "DELETE FROM ztc_network_route WHERE network_id = $1",
  1065. 1,
  1066. NULL,
  1067. params,
  1068. NULL,
  1069. NULL,
  1070. 0);
  1071. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1072. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  1073. PQclear(res);
  1074. PQclear(PQexec(conn, "ROLLBACK"));
  1075. delete config;
  1076. config = nullptr;
  1077. continue;
  1078. }
  1079. auto routes = (*config)["routes"];
  1080. err = false;
  1081. for (auto i = routes.begin(); i != routes.end(); ++i) {
  1082. std::string t = (*i)["target"];
  1083. std::vector<std::string> target;
  1084. std::istringstream f(t);
  1085. std::string s;
  1086. while(std::getline(f, s, '/')) {
  1087. target.push_back(s);
  1088. }
  1089. if (target.empty() || target.size() != 2) {
  1090. continue;
  1091. }
  1092. std::string targetAddr = target[0];
  1093. std::string targetBits = target[1];
  1094. std::string via = "NULL";
  1095. if (!(*i)["via"].is_null()) {
  1096. via = (*i)["via"];
  1097. }
  1098. const char *p[4] = {
  1099. id.c_str(),
  1100. targetAddr.c_str(),
  1101. targetBits.c_str(),
  1102. (via == "NULL" ? NULL : via.c_str()),
  1103. };
  1104. res = PQexecParams(conn,
  1105. "INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  1106. 4,
  1107. NULL,
  1108. p,
  1109. NULL,
  1110. NULL,
  1111. 0);
  1112. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1113. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  1114. PQclear(res);
  1115. err = true;
  1116. break;
  1117. }
  1118. PQclear(res);
  1119. }
  1120. if (err) {
  1121. PQclear(PQexec(conn, "ROLLBACK"));
  1122. delete config;
  1123. config = nullptr;
  1124. continue;
  1125. }
  1126. res = PQexec(conn, "COMMIT");
  1127. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1128. fprintf(stderr, "ERROR: Error committing network update: %s\n", PQresultErrorMessage(res));
  1129. }
  1130. PQclear(res);
  1131. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  1132. if (nwidInt) {
  1133. nlohmann::json nwOrig;
  1134. nlohmann::json nwNew(*config);
  1135. get(nwidInt, nwOrig);
  1136. _networkChanged(nwOrig, nwNew, qitem.second);
  1137. } else {
  1138. fprintf(stderr, "Can't notify network changed: %llu\n", (unsigned long long)nwidInt);
  1139. }
  1140. } catch (std::exception &e) {
  1141. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  1142. }
  1143. } else if (objtype == "_delete_network") {
  1144. try {
  1145. std::string networkId = (*config)["nwid"];
  1146. const char *values[1] = {
  1147. networkId.c_str()
  1148. };
  1149. PGresult * res = PQexecParams(conn,
  1150. "UPDATE ztc_network SET deleted = true WHERE id = $1",
  1151. 1,
  1152. NULL,
  1153. values,
  1154. NULL,
  1155. NULL,
  1156. 0);
  1157. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1158. fprintf(stderr, "ERROR: Error deleting network: %s\n", PQresultErrorMessage(res));
  1159. }
  1160. PQclear(res);
  1161. } catch (std::exception &e) {
  1162. fprintf(stderr, "ERROR: Error deleting network: %s\n", e.what());
  1163. }
  1164. } else if (objtype == "_delete_member") {
  1165. try {
  1166. std::string memberId = (*config)["id"];
  1167. std::string networkId = (*config)["nwid"];
  1168. const char *values[2] = {
  1169. memberId.c_str(),
  1170. networkId.c_str()
  1171. };
  1172. PGresult *res = PQexecParams(conn,
  1173. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  1174. 2,
  1175. NULL,
  1176. values,
  1177. NULL,
  1178. NULL,
  1179. 0);
  1180. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1181. fprintf(stderr, "ERROR: Error deleting member: %s\n", PQresultErrorMessage(res));
  1182. }
  1183. PQclear(res);
  1184. } catch (std::exception &e) {
  1185. fprintf(stderr, "ERROR: Error deleting member: %s\n", e.what());
  1186. }
  1187. } else {
  1188. fprintf(stderr, "ERROR: unknown objtype");
  1189. }
  1190. } catch (std::exception &e) {
  1191. fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
  1192. }
  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