PostgreSQL.cpp 43 KB

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