PostgreSQL.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486
  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::networksDbWatcher()
  666. {
  667. PGconn *conn = getPgConn(NO_OVERRIDE);
  668. if (PQstatus(conn) == CONNECTION_BAD) {
  669. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  670. PQfinish(conn);
  671. exit(1);
  672. }
  673. initializeNetworks(conn);
  674. if (this->_mqc != NULL) {
  675. PQfinish(conn);
  676. conn = NULL;
  677. _networksWatcher_RabbitMQ();
  678. } else {
  679. _networksWatcher_Postgres(conn);
  680. PQfinish(conn);
  681. conn = NULL;
  682. }
  683. if (_run == 1) {
  684. fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  685. exit(8);
  686. }
  687. fprintf(stderr, "Exited networksDbWatcher\n");
  688. }
  689. void PostgreSQL::_networksWatcher_Postgres(PGconn *conn) {
  690. char buf[11] = {0};
  691. std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
  692. PGresult *res = PQexec(conn, cmd.c_str());
  693. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  694. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  695. PQclear(res);
  696. PQfinish(conn);
  697. exit(1);
  698. }
  699. PQclear(res); res = NULL;
  700. while(_run == 1) {
  701. if (PQstatus(conn) != CONNECTION_OK) {
  702. fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
  703. exit(-1);
  704. }
  705. PGnotify *notify = NULL;
  706. PQconsumeInput(conn);
  707. while ((notify = PQnotifies(conn)) != NULL) {
  708. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  709. try {
  710. json tmp(json::parse(notify->extra));
  711. json &ov = tmp["old_val"];
  712. json &nv = tmp["new_val"];
  713. json oldConfig, newConfig;
  714. if (ov.is_object()) oldConfig = ov;
  715. if (nv.is_object()) newConfig = nv;
  716. if (oldConfig.is_object()||newConfig.is_object()) {
  717. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  718. }
  719. } catch (...) {} // ignore bad records
  720. free(notify);
  721. }
  722. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  723. }
  724. }
  725. void PostgreSQL::_networksWatcher_RabbitMQ() {
  726. char buf[11] = {0};
  727. std::string qname = "network_"+ std::string(_myAddress.toString(buf));
  728. RabbitMQ rmq(_mqc, qname.c_str());
  729. try {
  730. rmq.init();
  731. } catch (std::runtime_error &e) {
  732. fprintf(stderr, "RABBITMQ ERROR: %s\n", e.what());
  733. exit(11);
  734. }
  735. while (_run == 1) {
  736. try {
  737. std::string msg = rmq.consume();
  738. if (msg.empty()) {
  739. continue;
  740. }
  741. // fprintf(stderr, "Got network update: %s\n", msg.c_str());
  742. json tmp(json::parse(msg));
  743. json &ov = tmp["old_val"];
  744. json &nv = tmp["new_val"];
  745. json oldConfig, newConfig;
  746. if (ov.is_object()) oldConfig = ov;
  747. if (nv.is_object()) newConfig = nv;
  748. if (oldConfig.is_object()||newConfig.is_object()) {
  749. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  750. }
  751. } catch (std::runtime_error &e) {
  752. fprintf(stderr, "RABBITMQ ERROR: %s\n", e.what());
  753. break;
  754. } catch (std::exception &e) {
  755. fprintf(stderr, "RABBITMQ ERROR network watcher: %s\n", e.what());
  756. } catch(...) {
  757. fprintf(stderr, "RABBITMQ ERROR network watcher: unknown error\n");
  758. }
  759. }
  760. }
  761. void PostgreSQL::commitThread()
  762. {
  763. PGconn *conn = getPgConn();
  764. if (PQstatus(conn) == CONNECTION_BAD) {
  765. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  766. PQfinish(conn);
  767. exit(1);
  768. }
  769. std::pair<nlohmann::json,bool> qitem;
  770. while(_commitQueue.get(qitem)&(_run == 1)) {
  771. if (!qitem.first.is_object()) {
  772. continue;
  773. }
  774. if (PQstatus(conn) == CONNECTION_BAD) {
  775. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  776. PQfinish(conn);
  777. exit(1);
  778. }
  779. try {
  780. nlohmann::json *config = &(qitem.first);
  781. const std::string objtype = (*config)["objtype"];
  782. if (objtype == "member") {
  783. try {
  784. std::string memberId = (*config)["id"];
  785. std::string networkId = (*config)["nwid"];
  786. std::string identity = (*config)["identity"];
  787. std::string target = "NULL";
  788. if (!(*config)["remoteTraceTarget"].is_null()) {
  789. target = (*config)["remoteTraceTarget"];
  790. }
  791. std::string caps = OSUtils::jsonDump((*config)["capabilities"], -1);
  792. std::string lastAuthTime = std::to_string((long long)(*config)["lastAuthorizedTime"]);
  793. std::string lastDeauthTime = std::to_string((long long)(*config)["lastDeauthorizedTime"]);
  794. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  795. std::string rev = std::to_string((unsigned long long)(*config)["revision"]);
  796. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  797. std::string vmajor = std::to_string((int)(*config)["vMajor"]);
  798. std::string vminor = std::to_string((int)(*config)["vMinor"]);
  799. std::string vrev = std::to_string((int)(*config)["vRev"]);
  800. std::string vproto = std::to_string((int)(*config)["vProto"]);
  801. const char *values[19] = {
  802. memberId.c_str(),
  803. networkId.c_str(),
  804. ((*config)["activeBridge"] ? "true" : "false"),
  805. ((*config)["authorized"] ? "true" : "false"),
  806. caps.c_str(),
  807. identity.c_str(),
  808. lastAuthTime.c_str(),
  809. lastDeauthTime.c_str(),
  810. ((*config)["noAutoAssignIps"] ? "true" : "false"),
  811. rtraceLevel.c_str(),
  812. (target == "NULL") ? NULL : target.c_str(),
  813. rev.c_str(),
  814. tags.c_str(),
  815. vmajor.c_str(),
  816. vminor.c_str(),
  817. vrev.c_str(),
  818. vproto.c_str()
  819. };
  820. PGresult *res = PQexecParams(conn,
  821. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  822. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  823. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  824. "VALUES ($1, $2, $3, $4, $5, $6, "
  825. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  826. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  827. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  828. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  829. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  830. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  831. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  832. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  833. 17,
  834. NULL,
  835. values,
  836. NULL,
  837. NULL,
  838. 0);
  839. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  840. fprintf(stderr, "ERROR: Error updating member: %s\n", PQresultErrorMessage(res));
  841. fprintf(stderr, "%s", OSUtils::jsonDump(*config, 2).c_str());
  842. PQclear(res);
  843. delete config;
  844. config = nullptr;
  845. continue;
  846. }
  847. PQclear(res);
  848. res = PQexec(conn, "BEGIN");
  849. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  850. fprintf(stderr, "ERROR: Error beginning transaction: %s\n", PQresultErrorMessage(res));
  851. PQclear(res);
  852. delete config;
  853. config = nullptr;
  854. continue;
  855. }
  856. PQclear(res);
  857. const char *v2[2] = {
  858. memberId.c_str(),
  859. networkId.c_str()
  860. };
  861. res = PQexecParams(conn,
  862. "DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  863. 2,
  864. NULL,
  865. v2,
  866. NULL,
  867. NULL,
  868. 0);
  869. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  870. fprintf(stderr, "ERROR: Error updating IP address assignments: %s\n", PQresultErrorMessage(res));
  871. PQclear(res);
  872. PQclear(PQexec(conn, "ROLLBACK"));;
  873. delete config;
  874. config = nullptr;
  875. continue;
  876. }
  877. PQclear(res);
  878. std::vector<std::string> assignments;
  879. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  880. std::string addr = *i;
  881. if (std::find(assignments.begin(), assignments.end(), addr) != assignments.end()) {
  882. continue;
  883. }
  884. const char *v3[3] = {
  885. memberId.c_str(),
  886. networkId.c_str(),
  887. addr.c_str()
  888. };
  889. res = PQexecParams(conn,
  890. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3)",
  891. 3,
  892. NULL,
  893. v3,
  894. NULL,
  895. NULL,
  896. 0);
  897. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  898. fprintf(stderr, "ERROR: Error setting IP addresses for member: %s\n", PQresultErrorMessage(res));
  899. PQclear(res);
  900. PQclear(PQexec(conn, "ROLLBACK"));
  901. break;;
  902. }
  903. assignments.push_back(addr);
  904. }
  905. res = PQexec(conn, "COMMIT");
  906. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  907. fprintf(stderr, "ERROR: Error committing ip address data: %s\n", PQresultErrorMessage(res));
  908. }
  909. PQclear(res);
  910. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  911. const uint64_t memberidInt = OSUtils::jsonIntHex((*config)["id"], 0ULL);
  912. if (nwidInt && memberidInt) {
  913. nlohmann::json nwOrig;
  914. nlohmann::json memOrig;
  915. nlohmann::json memNew(*config);
  916. get(nwidInt, nwOrig, memberidInt, memOrig);
  917. _memberChanged(memOrig, memNew, qitem.second);
  918. } else {
  919. fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %llu-%llu\n", (unsigned long long)nwidInt, (unsigned long long)memberidInt);
  920. }
  921. } catch (std::exception &e) {
  922. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  923. }
  924. } else if (objtype == "network") {
  925. try {
  926. std::string id = (*config)["id"];
  927. std::string controllerId = _myAddressStr.c_str();
  928. std::string name = (*config)["name"];
  929. std::string remoteTraceTarget("NULL");
  930. if (!(*config)["remoteTraceTarget"].is_null()) {
  931. remoteTraceTarget = (*config)["remoteTraceTarget"];
  932. }
  933. std::string rulesSource;
  934. if ((*config)["rulesSource"].is_string()) {
  935. rulesSource = (*config)["rulesSource"];
  936. }
  937. std::string caps = OSUtils::jsonDump((*config)["capabilitles"], -1);
  938. std::string now = std::to_string(OSUtils::now());
  939. std::string mtu = std::to_string((int)(*config)["mtu"]);
  940. std::string mcastLimit = std::to_string((int)(*config)["multicastLimit"]);
  941. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  942. std::string rules = OSUtils::jsonDump((*config)["rules"], -1);
  943. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  944. std::string v4mode = OSUtils::jsonDump((*config)["v4AssignMode"],-1);
  945. std::string v6mode = OSUtils::jsonDump((*config)["v6AssignMode"], -1);
  946. bool enableBroadcast = (*config)["enableBroadcast"];
  947. bool isPrivate = (*config)["private"];
  948. const char *values[16] = {
  949. id.c_str(),
  950. controllerId.c_str(),
  951. caps.c_str(),
  952. enableBroadcast ? "true" : "false",
  953. now.c_str(),
  954. mtu.c_str(),
  955. mcastLimit.c_str(),
  956. name.c_str(),
  957. isPrivate ? "true" : "false",
  958. rtraceLevel.c_str(),
  959. (remoteTraceTarget == "NULL" ? NULL : remoteTraceTarget.c_str()),
  960. rules.c_str(),
  961. rulesSource.c_str(),
  962. tags.c_str(),
  963. v4mode.c_str(),
  964. v6mode.c_str(),
  965. };
  966. // This ugly query exists because when we want to mirror networks to/from
  967. // another data store (e.g. FileDB or LFDB) it is possible to get a network
  968. // that doesn't exist in Central's database. This does an upsert and sets
  969. // the owner_id to the "first" global admin in the user DB if the record
  970. // did not previously exist. If the record already exists owner_id is left
  971. // unchanged, so owner_id should be left out of the update clause.
  972. PGresult *res = PQexecParams(conn,
  973. "INSERT INTO ztc_network (id, creation_time, owner_id, controller_id, capabilities, enable_broadcast, "
  974. "last_modified, mtu, multicast_limit, name, private, "
  975. "remote_trace_level, remote_trace_target, rules, rules_source, "
  976. "tags, v4_assign_mode, v6_assign_mode) VALUES ("
  977. "$1, TO_TIMESTAMP($5::double precision/1000), "
  978. "(SELECT user_id AS owner_id FROM ztc_global_permissions WHERE authorize = true AND del = true AND modify = true AND read = true LIMIT 1),"
  979. "$2, $3, $4, TO_TIMESTAMP($5::double precision/1000), "
  980. "$6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) "
  981. "ON CONFLICT (id) DO UPDATE set controller_id = EXCLUDED.controller_id, "
  982. "capabilities = EXCLUDED.capabilities, enable_broadcast = EXCLUDED.enable_broadcast, "
  983. "last_modified = EXCLUDED.last_modified, mtu = EXCLUDED.mtu, "
  984. "multicast_limit = EXCLUDED.multicast_limit, name = EXCLUDED.name, "
  985. "private = EXCLUDED.private, remote_trace_level = EXCLUDED.remote_trace_level, "
  986. "remote_trace_target = EXCLUDED.remote_trace_target, rules = EXCLUDED.rules, "
  987. "rules_source = EXCLUDED.rules_source, tags = EXCLUDED.tags, "
  988. "v4_assign_mode = EXCLUDED.v4_assign_mode, v6_assign_mode = EXCLUDED.v6_assign_mode",
  989. 16,
  990. NULL,
  991. values,
  992. NULL,
  993. NULL,
  994. 0);
  995. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  996. fprintf(stderr, "ERROR: Error updating network record: %s\n", PQresultErrorMessage(res));
  997. PQclear(res);
  998. delete config;
  999. config = nullptr;
  1000. continue;
  1001. }
  1002. PQclear(res);
  1003. res = PQexec(conn, "BEGIN");
  1004. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1005. fprintf(stderr, "ERROR: Error beginnning transaction: %s\n", PQresultErrorMessage(res));
  1006. PQclear(res);
  1007. delete config;
  1008. config = nullptr;
  1009. continue;
  1010. }
  1011. PQclear(res);
  1012. const char *params[1] = {
  1013. id.c_str()
  1014. };
  1015. res = PQexecParams(conn,
  1016. "DELETE FROM ztc_network_assignment_pool WHERE network_id = $1",
  1017. 1,
  1018. NULL,
  1019. params,
  1020. NULL,
  1021. NULL,
  1022. 0);
  1023. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1024. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  1025. PQclear(res);
  1026. PQclear(PQexec(conn, "ROLLBACK"));
  1027. delete config;
  1028. config = nullptr;
  1029. continue;
  1030. }
  1031. PQclear(res);
  1032. auto pool = (*config)["ipAssignmentPools"];
  1033. bool err = false;
  1034. for (auto i = pool.begin(); i != pool.end(); ++i) {
  1035. std::string start = (*i)["ipRangeStart"];
  1036. std::string end = (*i)["ipRangeEnd"];
  1037. const char *p[3] = {
  1038. id.c_str(),
  1039. start.c_str(),
  1040. end.c_str()
  1041. };
  1042. res = PQexecParams(conn,
  1043. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  1044. "VALUES ($1, $2, $3)",
  1045. 3,
  1046. NULL,
  1047. p,
  1048. NULL,
  1049. NULL,
  1050. 0);
  1051. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1052. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  1053. PQclear(res);
  1054. err = true;
  1055. break;
  1056. }
  1057. PQclear(res);
  1058. }
  1059. if (err) {
  1060. PQclear(PQexec(conn, "ROLLBACK"));
  1061. delete config;
  1062. config = nullptr;
  1063. continue;
  1064. }
  1065. res = PQexecParams(conn,
  1066. "DELETE FROM ztc_network_route WHERE network_id = $1",
  1067. 1,
  1068. NULL,
  1069. params,
  1070. NULL,
  1071. NULL,
  1072. 0);
  1073. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1074. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  1075. PQclear(res);
  1076. PQclear(PQexec(conn, "ROLLBACK"));
  1077. delete config;
  1078. config = nullptr;
  1079. continue;
  1080. }
  1081. auto routes = (*config)["routes"];
  1082. err = false;
  1083. for (auto i = routes.begin(); i != routes.end(); ++i) {
  1084. std::string t = (*i)["target"];
  1085. std::vector<std::string> target;
  1086. std::istringstream f(t);
  1087. std::string s;
  1088. while(std::getline(f, s, '/')) {
  1089. target.push_back(s);
  1090. }
  1091. if (target.empty() || target.size() != 2) {
  1092. continue;
  1093. }
  1094. std::string targetAddr = target[0];
  1095. std::string targetBits = target[1];
  1096. std::string via = "NULL";
  1097. if (!(*i)["via"].is_null()) {
  1098. via = (*i)["via"];
  1099. }
  1100. const char *p[4] = {
  1101. id.c_str(),
  1102. targetAddr.c_str(),
  1103. targetBits.c_str(),
  1104. (via == "NULL" ? NULL : via.c_str()),
  1105. };
  1106. res = PQexecParams(conn,
  1107. "INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  1108. 4,
  1109. NULL,
  1110. p,
  1111. NULL,
  1112. NULL,
  1113. 0);
  1114. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1115. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  1116. PQclear(res);
  1117. err = true;
  1118. break;
  1119. }
  1120. PQclear(res);
  1121. }
  1122. if (err) {
  1123. PQclear(PQexec(conn, "ROLLBACK"));
  1124. delete config;
  1125. config = nullptr;
  1126. continue;
  1127. }
  1128. res = PQexec(conn, "COMMIT");
  1129. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1130. fprintf(stderr, "ERROR: Error committing network update: %s\n", PQresultErrorMessage(res));
  1131. }
  1132. PQclear(res);
  1133. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  1134. if (nwidInt) {
  1135. nlohmann::json nwOrig;
  1136. nlohmann::json nwNew(*config);
  1137. get(nwidInt, nwOrig);
  1138. _networkChanged(nwOrig, nwNew, qitem.second);
  1139. } else {
  1140. fprintf(stderr, "Can't notify network changed: %llu\n", (unsigned long long)nwidInt);
  1141. }
  1142. } catch (std::exception &e) {
  1143. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  1144. }
  1145. } else if (objtype == "_delete_network") {
  1146. try {
  1147. std::string networkId = (*config)["nwid"];
  1148. const char *values[1] = {
  1149. networkId.c_str()
  1150. };
  1151. PGresult * res = PQexecParams(conn,
  1152. "UPDATE ztc_network SET deleted = true WHERE id = $1",
  1153. 1,
  1154. NULL,
  1155. values,
  1156. NULL,
  1157. NULL,
  1158. 0);
  1159. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1160. fprintf(stderr, "ERROR: Error deleting network: %s\n", PQresultErrorMessage(res));
  1161. }
  1162. PQclear(res);
  1163. } catch (std::exception &e) {
  1164. fprintf(stderr, "ERROR: Error deleting network: %s\n", e.what());
  1165. }
  1166. } else if (objtype == "_delete_member") {
  1167. try {
  1168. std::string memberId = (*config)["id"];
  1169. std::string networkId = (*config)["nwid"];
  1170. const char *values[2] = {
  1171. memberId.c_str(),
  1172. networkId.c_str()
  1173. };
  1174. PGresult *res = PQexecParams(conn,
  1175. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  1176. 2,
  1177. NULL,
  1178. values,
  1179. NULL,
  1180. NULL,
  1181. 0);
  1182. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1183. fprintf(stderr, "ERROR: Error deleting member: %s\n", PQresultErrorMessage(res));
  1184. }
  1185. PQclear(res);
  1186. } catch (std::exception &e) {
  1187. fprintf(stderr, "ERROR: Error deleting member: %s\n", e.what());
  1188. }
  1189. } else {
  1190. fprintf(stderr, "ERROR: unknown objtype");
  1191. }
  1192. } catch (std::exception &e) {
  1193. fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
  1194. }
  1195. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1196. }
  1197. PQfinish(conn);
  1198. if (_run == 1) {
  1199. fprintf(stderr, "ERROR: %s commitThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1200. exit(7);
  1201. }
  1202. }
  1203. void PostgreSQL::onlineNotificationThread()
  1204. {
  1205. PGconn *conn = getPgConn();
  1206. if (PQstatus(conn) == CONNECTION_BAD) {
  1207. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  1208. PQfinish(conn);
  1209. exit(1);
  1210. }
  1211. _connected = 1;
  1212. //int64_t lastUpdatedNetworkStatus = 0;
  1213. std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative;
  1214. while (_run == 1) {
  1215. if (PQstatus(conn) != CONNECTION_OK) {
  1216. fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres.");
  1217. PQfinish(conn);
  1218. exit(5);
  1219. }
  1220. // map used to send notifications to front end
  1221. std::unordered_map<std::string, std::vector<std::string>> updateMap;
  1222. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1223. {
  1224. std::lock_guard<std::mutex> l(_lastOnline_l);
  1225. lastOnline.swap(_lastOnline);
  1226. }
  1227. PGresult *res = NULL;
  1228. std::stringstream memberUpdate;
  1229. memberUpdate << "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ";
  1230. bool firstRun = true;
  1231. bool memberAdded = false;
  1232. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1233. uint64_t nwid_i = i->first.first;
  1234. char nwidTmp[64];
  1235. char memTmp[64];
  1236. char ipTmp[64];
  1237. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1238. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  1239. auto found = _networks.find(nwid_i);
  1240. if (found == _networks.end()) {
  1241. continue; // skip members trying to join non-existant networks
  1242. }
  1243. std::string networkId(nwidTmp);
  1244. std::string memberId(memTmp);
  1245. std::vector<std::string> &members = updateMap[networkId];
  1246. members.push_back(memberId);
  1247. lastOnlineCumulative[i->first] = i->second.first;
  1248. const char *qvals[2] = {
  1249. networkId.c_str(),
  1250. memberId.c_str()
  1251. };
  1252. res = PQexecParams(conn,
  1253. "SELECT id, network_id FROM ztc_member WHERE network_id = $1 AND id = $2",
  1254. 2,
  1255. NULL,
  1256. qvals,
  1257. NULL,
  1258. NULL,
  1259. 0);
  1260. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  1261. fprintf(stderr, "Member count failed: %s", PQerrorMessage(conn));
  1262. PQclear(res);
  1263. continue;
  1264. }
  1265. int nrows = PQntuples(res);
  1266. PQclear(res);
  1267. if (nrows == 1) {
  1268. int64_t ts = i->second.first;
  1269. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1270. std::string timestamp = std::to_string(ts);
  1271. if (firstRun) {
  1272. firstRun = false;
  1273. } else {
  1274. memberUpdate << ", ";
  1275. }
  1276. memberUpdate << "('" << networkId << "', '" << memberId << "', ";
  1277. if (ipAddr.empty()) {
  1278. memberUpdate << "NULL, ";
  1279. } else {
  1280. memberUpdate << "'" << ipAddr << "', ";
  1281. }
  1282. memberUpdate << "TO_TIMESTAMP(" << timestamp << "::double precision/1000))";
  1283. memberAdded = true;
  1284. } else if (nrows > 1) {
  1285. fprintf(stderr, "nrows > 1?!?");
  1286. continue;
  1287. } else {
  1288. continue;
  1289. }
  1290. }
  1291. memberUpdate << " ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated;";
  1292. if (memberAdded) {
  1293. res = PQexec(conn, memberUpdate.str().c_str());
  1294. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1295. fprintf(stderr, "Multiple insert failed: %s", PQerrorMessage(conn));
  1296. }
  1297. PQclear(res);
  1298. }
  1299. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1300. }
  1301. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  1302. PQfinish(conn);
  1303. if (_run == 1) {
  1304. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1305. exit(6);
  1306. }
  1307. }
  1308. PGconn *PostgreSQL::getPgConn(OverrideMode m)
  1309. {
  1310. if (m == ALLOW_PGBOUNCER_OVERRIDE) {
  1311. char *connStr = getenv("PGBOUNCER_CONNSTR");
  1312. if (connStr != NULL) {
  1313. fprintf(stderr, "PGBouncer Override\n");
  1314. std::string conn(connStr);
  1315. conn += " application_name=controller-";
  1316. conn += _myAddressStr.c_str();
  1317. return PQconnectdb(conn.c_str());
  1318. }
  1319. }
  1320. return PQconnectdb(_connString.c_str());
  1321. }
  1322. #endif //ZT_CONTROLLER_USE_LIBPQ