PostgreSQL.cpp 42 KB

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