PostgreSQL.cpp 43 KB

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