PostgreSQL.cpp 41 KB

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