PostgreSQL.cpp 45 KB

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