PostgreSQL.cpp 44 KB

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