PostgreSQL.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975
  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: 2025-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 "../node/SHA512.hpp"
  17. #include "EmbeddedNetworkController.hpp"
  18. #include "../version.h"
  19. #include "Redis.hpp"
  20. #include <libpq-fe.h>
  21. #include <sstream>
  22. #include <climits>
  23. using json = nlohmann::json;
  24. namespace {
  25. static const int DB_MINIMUM_VERSION = 5;
  26. static const char *_timestr()
  27. {
  28. time_t t = time(0);
  29. char *ts = ctime(&t);
  30. char *p = ts;
  31. if (!p)
  32. return "";
  33. while (*p) {
  34. if (*p == '\n') {
  35. *p = (char)0;
  36. break;
  37. }
  38. ++p;
  39. }
  40. return ts;
  41. }
  42. /*
  43. std::string join(const std::vector<std::string> &elements, const char * const separator)
  44. {
  45. switch(elements.size()) {
  46. case 0:
  47. return "";
  48. case 1:
  49. return elements[0];
  50. default:
  51. std::ostringstream os;
  52. std::copy(elements.begin(), elements.end()-1, std::ostream_iterator<std::string>(os, separator));
  53. os << *elements.rbegin();
  54. return os.str();
  55. }
  56. }
  57. */
  58. } // anonymous namespace
  59. using namespace ZeroTier;
  60. using Attrs = std::vector<std::pair<std::string, std::string>>;
  61. using Item = std::pair<std::string, Attrs>;
  62. using ItemStream = std::vector<Item>;
  63. PostgreSQL::PostgreSQL(const Identity &myId, const char *path, int listenPort, RedisConfig *rc)
  64. : DB()
  65. , _myId(myId)
  66. , _myAddress(myId.address())
  67. , _ready(0)
  68. , _connected(1)
  69. , _run(1)
  70. , _waitNoticePrinted(false)
  71. , _listenPort(listenPort)
  72. , _rc(rc)
  73. , _redis(NULL)
  74. , _cluster(NULL)
  75. {
  76. char myAddress[64];
  77. _myAddressStr = myId.address().toString(myAddress);
  78. _connString = std::string(path) + " application_name=controller_" + _myAddressStr;
  79. memset(_ssoPsk, 0, sizeof(_ssoPsk));
  80. char *const ssoPskHex = getenv("ZT_SSO_PSK");
  81. if (ssoPskHex) {
  82. // SECURITY: note that ssoPskHex will always be null-terminated if libc acatually
  83. // returns something non-NULL. If the hex encodes something shorter than 48 bytes,
  84. // it will be padded at the end with zeroes. If longer, it'll be truncated.
  85. Utils::unhex(ssoPskHex, _ssoPsk, sizeof(_ssoPsk));
  86. }
  87. // Database Schema Version Check
  88. PGconn *conn = getPgConn();
  89. if (PQstatus(conn) != CONNECTION_OK) {
  90. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  91. exit(1);
  92. }
  93. PGresult *res = PQexec(conn, "SELECT version FROM ztc_database");
  94. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  95. fprintf(stderr, "Error determining database version");
  96. exit(1);
  97. }
  98. if (PQntuples(res) != 1) {
  99. fprintf(stderr, "Invalid number of db version tuples returned.");
  100. exit(1);
  101. }
  102. int dbVersion = std::stoi(PQgetvalue(res, 0, 0));
  103. if (dbVersion < DB_MINIMUM_VERSION) {
  104. 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);
  105. exit(1);
  106. }
  107. PQclear(res);
  108. res = NULL;
  109. if (_rc != NULL) {
  110. sw::redis::ConnectionOptions opts;
  111. sw::redis::ConnectionPoolOptions poolOpts;
  112. opts.host = _rc->hostname;
  113. opts.port = _rc->port;
  114. opts.password = _rc->password;
  115. opts.db = 0;
  116. poolOpts.size = 10;
  117. if (_rc->clusterMode) {
  118. fprintf(stderr, "Using Redis in Cluster Mode\n");
  119. _cluster = std::make_shared<sw::redis::RedisCluster>(opts, poolOpts);
  120. } else {
  121. fprintf(stderr, "Using Redis in Standalone Mode\n");
  122. _redis = std::make_shared<sw::redis::Redis>(opts, poolOpts);
  123. }
  124. }
  125. _readyLock.lock();
  126. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S, ::_timestr(), (unsigned long long)_myAddress.toInt());
  127. _waitNoticePrinted = true;
  128. initializeNetworks(conn);
  129. initializeMembers(conn);
  130. PQfinish(conn);
  131. conn = NULL;
  132. _heartbeatThread = std::thread(&PostgreSQL::heartbeat, this);
  133. _membersDbWatcher = std::thread(&PostgreSQL::membersDbWatcher, this);
  134. _networksDbWatcher = std::thread(&PostgreSQL::networksDbWatcher, this);
  135. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  136. _commitThread[i] = std::thread(&PostgreSQL::commitThread, this);
  137. }
  138. _onlineNotificationThread = std::thread(&PostgreSQL::onlineNotificationThread, this);
  139. }
  140. PostgreSQL::~PostgreSQL()
  141. {
  142. _run = 0;
  143. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  144. _heartbeatThread.join();
  145. _membersDbWatcher.join();
  146. _networksDbWatcher.join();
  147. _commitQueue.stop();
  148. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  149. _commitThread[i].join();
  150. }
  151. _onlineNotificationThread.join();
  152. }
  153. bool PostgreSQL::waitForReady()
  154. {
  155. while (_ready < 2) {
  156. _readyLock.lock();
  157. _readyLock.unlock();
  158. }
  159. return true;
  160. }
  161. bool PostgreSQL::isReady()
  162. {
  163. return ((_ready == 2)&&(_connected));
  164. }
  165. bool PostgreSQL::save(nlohmann::json &record,bool notifyListeners)
  166. {
  167. bool modified = false;
  168. try {
  169. if (!record.is_object())
  170. return false;
  171. const std::string objtype = record["objtype"];
  172. if (objtype == "network") {
  173. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  174. if (nwid) {
  175. nlohmann::json old;
  176. get(nwid,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. } else if (objtype == "member") {
  184. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  185. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  186. if ((id)&&(nwid)) {
  187. nlohmann::json network,old;
  188. get(nwid,network,id,old);
  189. if ((!old.is_object())||(!_compareRecords(old,record))) {
  190. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  191. _commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
  192. modified = true;
  193. }
  194. }
  195. }
  196. } catch (std::exception &e) {
  197. fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what());
  198. } catch (...) {
  199. fprintf(stderr, "Unknown error on PostgreSQL::save\n");
  200. }
  201. return modified;
  202. }
  203. void PostgreSQL::eraseNetwork(const uint64_t networkId)
  204. {
  205. char tmp2[24];
  206. waitForReady();
  207. Utils::hex(networkId, tmp2);
  208. std::pair<nlohmann::json,bool> tmp;
  209. tmp.first["id"] = tmp2;
  210. tmp.first["objtype"] = "_delete_network";
  211. tmp.second = true;
  212. _commitQueue.post(tmp);
  213. nlohmann::json nullJson;
  214. _networkChanged(tmp.first, nullJson, true);
  215. }
  216. void PostgreSQL::eraseMember(const uint64_t networkId, const uint64_t memberId)
  217. {
  218. char tmp2[24];
  219. waitForReady();
  220. std::pair<nlohmann::json,bool> tmp, nw;
  221. Utils::hex(networkId, tmp2);
  222. tmp.first["nwid"] = tmp2;
  223. Utils::hex(memberId, tmp2);
  224. tmp.first["id"] = tmp2;
  225. tmp.first["objtype"] = "_delete_member";
  226. tmp.second = true;
  227. _commitQueue.post(tmp);
  228. nlohmann::json nullJson;
  229. _memberChanged(tmp.first, nullJson, true);
  230. }
  231. void PostgreSQL::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress)
  232. {
  233. std::lock_guard<std::mutex> l(_lastOnline_l);
  234. std::pair<int64_t, InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId, memberId)];
  235. i.first = OSUtils::now();
  236. if (physicalAddress) {
  237. i.second = physicalAddress;
  238. }
  239. }
  240. void PostgreSQL::updateMemberOnLoad(const uint64_t networkId, const uint64_t memberId, nlohmann::json &member)
  241. {
  242. const uint64_t nwid = OSUtils::jsonIntHex(member["nwid"],0ULL);
  243. const uint64_t id = OSUtils::jsonIntHex(member["id"],0ULL);
  244. char nwids[24],ids[24];
  245. OSUtils::ztsnprintf(nwids, sizeof(nwids), "%.16llx", nwid);
  246. OSUtils::ztsnprintf(ids, sizeof(ids), "%.10llx", id);
  247. bool have_auth = false;
  248. try {
  249. PGconn *conn = getPgConn();
  250. if (PQstatus(conn) != CONNECTION_OK) {
  251. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  252. exit(1);
  253. }
  254. const char *params[1] = { nwids };
  255. PGresult *res = PQexecParams(conn, "SELECT org.client_id, org.authorization_endpoint FROM ztc_network AS nw, ztc_org AS org WHERE nw.id = $1 AND nw.sso_enabled = true AND org.owner_id = nw.owner_id",
  256. 1,
  257. NULL,
  258. params,
  259. NULL,
  260. NULL,
  261. 0);
  262. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  263. fprintf(stderr, "Org client_id and authorization_endpoint lookup failed: %s", PQerrorMessage(conn));
  264. PQclear(res);
  265. exit(1);
  266. }
  267. if (PQntuples(res) >= 1) {
  268. std::string client_id = PQgetvalue(res, 0, 0);
  269. std::string authorization_endpoint = PQgetvalue(res, 0, 1);
  270. PQclear(res);
  271. if ((!client_id.empty())&&(!authorization_endpoint.empty())) {
  272. const char *params2[2] = { nwids, ids };
  273. res = PQexecParams(conn, "SELECT e.nonce, e.authentication_expiry_time FROM ztc_sso_expiry AS e WHERE e.network_id = $1 AND e.member_id = $2 ORDER BY n.authentication_expiry_time DESC LIMIT 1",
  274. 1,
  275. NULL,
  276. params2,
  277. NULL,
  278. NULL,
  279. 0);
  280. if (PQntuples(res) >= 1) {
  281. std::string nonce = PQgetvalue(res, 0, 0);
  282. int64_t authentication_expiry_time = std::stoll(PQgetvalue(res, 0, 1));
  283. if ((authentication_expiry_time >= 0)&&(!nonce.empty())) {
  284. have_auth = true;
  285. uint8_t state[48];
  286. HMACSHA384(_ssoPsk, nonce.data(), (unsigned int)nonce.length(), state);
  287. char state_hex[256];
  288. Utils::hex(state, 48, state_hex);
  289. char authenticationURL[4096];
  290. const char *redirect_url = "redirect_uri=http%3A%2F%2Fmy.zerotier.com%2Fapi%2Fnetwork%2Fsso-auth"; // TODO: this should be configurable
  291. Utils::ztsnprintf(authenticationURL, sizeof(authenticationURL),
  292. "%s?response_type=id_token&response_mode=form_post&scope=openid+email+profile&redriect_uri=%s&nonce=%s&state=%s&client_id=%s",
  293. authorization_endpoint.c_str(),
  294. redirect_url,
  295. nonce.c_str(),
  296. state_hex, // NOTE: should these be URL escaped? Don't think there's a risk as they are not user definable.
  297. client_id.c_str());
  298. member["authenticationExpiryTime"] = authentication_expiry_time;
  299. member["authenticationURL"] = authenticationURL;
  300. }
  301. }
  302. PQclear(res);
  303. }
  304. } else {
  305. PQclear(res);
  306. }
  307. } catch (sw::redis::Error &e) {
  308. fprintf(stderr, "ERROR: Error updating member on load, in Redis: %s\n", e.what());
  309. exit(-1);
  310. } catch (std::exception &e) {
  311. fprintf(stderr, "ERROR: Error updating member on load: %s\n", e.what());
  312. exit(-1);
  313. }
  314. }
  315. void PostgreSQL::initializeNetworks(PGconn *conn)
  316. {
  317. try {
  318. if (PQstatus(conn) != CONNECTION_OK) {
  319. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  320. exit(1);
  321. }
  322. std::string setKey = "networks:{" + _myAddressStr + "}";
  323. // if (_rc != NULL) {
  324. // try {
  325. // if (_rc->clusterMode) {
  326. // _cluster->del(setKey);
  327. // } else {
  328. // _redis->del(setKey);
  329. // }
  330. // } catch (sw::redis::Error &e) {
  331. // // del can throw an error if the key doesn't exist
  332. // // swallow it and move along
  333. // }
  334. // }
  335. std::unordered_set<std::string> networkSet;
  336. const char *params[1] = {
  337. _myAddressStr.c_str()
  338. };
  339. fprintf(stderr, "Initializing Networks...\n");
  340. PGresult *res = PQexecParams(conn, "SELECT id, EXTRACT(EPOCH FROM creation_time AT TIME ZONE 'UTC')*1000, capabilities, "
  341. "enable_broadcast, EXTRACT(EPOCH FROM last_modified AT TIME ZONE 'UTC')*1000, mtu, multicast_limit, name, private, remote_trace_level, "
  342. "remote_trace_target, revision, rules, tags, v4_assign_mode, v6_assign_mode FROM ztc_network "
  343. "WHERE deleted = false AND controller_id = $1",
  344. 1,
  345. NULL,
  346. params,
  347. NULL,
  348. NULL,
  349. 0);
  350. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  351. fprintf(stderr, "Networks Initialization Failed: %s", PQerrorMessage(conn));
  352. PQclear(res);
  353. exit(1);
  354. }
  355. int numRows = PQntuples(res);
  356. for (int i = 0; i < numRows; ++i) {
  357. json empty;
  358. json config;
  359. const char *nwidparam[1] = {
  360. PQgetvalue(res, i, 0)
  361. };
  362. std::string nwid = PQgetvalue(res, i, 0);
  363. networkSet.insert(nwid);
  364. config["id"] = nwid;
  365. config["nwid"] = nwid;
  366. try {
  367. config["creationTime"] = std::stoull(PQgetvalue(res, i, 1));
  368. } catch (std::exception &e) {
  369. config["creationTime"] = 0ULL;
  370. //fprintf(stderr, "Error converting creation time: %s\n", PQgetvalue(res, i, 1));
  371. }
  372. config["capabilities"] = json::parse(PQgetvalue(res, i, 2));
  373. config["enableBroadcast"] = (strcmp(PQgetvalue(res, i, 3),"t")==0);
  374. try {
  375. config["lastModified"] = std::stoull(PQgetvalue(res, i, 4));
  376. } catch (std::exception &e) {
  377. config["lastModified"] = 0ULL;
  378. //fprintf(stderr, "Error converting last modified: %s\n", PQgetvalue(res, i, 4));
  379. }
  380. try {
  381. config["mtu"] = std::stoi(PQgetvalue(res, i, 5));
  382. } catch (std::exception &e) {
  383. config["mtu"] = 2800;
  384. }
  385. try {
  386. config["multicastLimit"] = std::stoi(PQgetvalue(res, i, 6));
  387. } catch (std::exception &e) {
  388. config["multicastLimit"] = 64;
  389. }
  390. config["name"] = PQgetvalue(res, i, 7);
  391. config["private"] = (strcmp(PQgetvalue(res, i, 8),"t")==0);
  392. try {
  393. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
  394. } catch (std::exception &e) {
  395. config["remoteTraceLevel"] = 0;
  396. }
  397. config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
  398. try {
  399. config["revision"] = std::stoull(PQgetvalue(res, i, 11));
  400. } catch (std::exception &e) {
  401. config["revision"] = 0ULL;
  402. //fprintf(stderr, "Error converting revision: %s\n", PQgetvalue(res, i, 11));
  403. }
  404. config["rules"] = json::parse(PQgetvalue(res, i, 12));
  405. config["tags"] = json::parse(PQgetvalue(res, i, 13));
  406. config["v4AssignMode"] = json::parse(PQgetvalue(res, i, 14));
  407. config["v6AssignMode"] = json::parse(PQgetvalue(res, i, 15));
  408. config["objtype"] = "network";
  409. config["ipAssignmentPools"] = json::array();
  410. config["routes"] = json::array();
  411. PGresult *r2 = PQexecParams(conn,
  412. "SELECT host(ip_range_start), host(ip_range_end) FROM ztc_network_assignment_pool WHERE network_id = $1",
  413. 1,
  414. NULL,
  415. nwidparam,
  416. NULL,
  417. NULL,
  418. 0);
  419. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  420. fprintf(stderr, "ERROR: Error retreiving IP pools for network: %s\n", PQresultErrorMessage(r2));
  421. PQclear(r2);
  422. PQclear(res);
  423. exit(1);
  424. }
  425. int n = PQntuples(r2);
  426. for (int j = 0; j < n; ++j) {
  427. json ip;
  428. ip["ipRangeStart"] = PQgetvalue(r2, j, 0);
  429. ip["ipRangeEnd"] = PQgetvalue(r2, j, 1);
  430. config["ipAssignmentPools"].push_back(ip);
  431. }
  432. PQclear(r2);
  433. r2 = PQexecParams(conn,
  434. "SELECT host(address), bits, host(via) FROM ztc_network_route WHERE network_id = $1",
  435. 1,
  436. NULL,
  437. nwidparam,
  438. NULL,
  439. NULL,
  440. 0);
  441. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  442. fprintf(stderr, "ERROR: Error retreiving routes for network: %s\n", PQresultErrorMessage(r2));
  443. PQclear(r2);
  444. PQclear(res);
  445. exit(1);
  446. }
  447. n = PQntuples(r2);
  448. for (int j = 0; j < n; ++j) {
  449. std::string addr = PQgetvalue(r2, j, 0);
  450. std::string bits = PQgetvalue(r2, j, 1);
  451. std::string via = PQgetvalue(r2, j, 2);
  452. json route;
  453. route["target"] = addr + "/" + bits;
  454. if (via == "NULL") {
  455. route["via"] = nullptr;
  456. } else {
  457. route["via"] = via;
  458. }
  459. config["routes"].push_back(route);
  460. }
  461. r2 = PQexecParams(conn,
  462. "SELECT domain, servers FROM ztc_network_dns WHERE network_id = $1",
  463. 1,
  464. NULL,
  465. nwidparam,
  466. NULL,
  467. NULL,
  468. 0);
  469. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  470. fprintf(stderr, "ERROR: Error retrieving DNS settings for network: %s\n", PQresultErrorMessage(r2));
  471. PQclear(r2);
  472. PQclear(res);
  473. exit(1);
  474. }
  475. n = PQntuples(r2);
  476. if (n > 1) {
  477. fprintf(stderr, "ERROR: invalid number of DNS configurations for network %s. Must be 0 or 1\n", nwid.c_str());
  478. } else if (n == 1) {
  479. json obj;
  480. std::string domain = PQgetvalue(r2, 0, 0);
  481. std::string serverList = PQgetvalue(r2, 0, 1);
  482. auto servers = json::array();
  483. if (serverList.rfind("{",0) != std::string::npos) {
  484. serverList = serverList.substr(1, serverList.size()-2);
  485. std::stringstream ss(serverList);
  486. while(ss.good()) {
  487. std::string server;
  488. std::getline(ss, server, ',');
  489. servers.push_back(server);
  490. }
  491. }
  492. obj["domain"] = domain;
  493. obj["servers"] = servers;
  494. config["dns"] = obj;
  495. }
  496. PQclear(r2);
  497. _networkChanged(empty, config, false);
  498. }
  499. PQclear(res);
  500. // if(!networkSet.empty()) {
  501. // if (_rc && _rc->clusterMode) {
  502. // auto tx = _cluster->transaction(_myAddressStr, true);
  503. // tx.sadd(setKey, networkSet.begin(), networkSet.end());
  504. // tx.exec();
  505. // } else if (_rc && !_rc->clusterMode) {
  506. // auto tx = _redis->transaction(true);
  507. // tx.sadd(setKey, networkSet.begin(), networkSet.end());
  508. // tx.exec();
  509. // }
  510. // }
  511. if (++this->_ready == 2) {
  512. if (_waitNoticePrinted) {
  513. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  514. }
  515. _readyLock.unlock();
  516. }
  517. } catch (sw::redis::Error &e) {
  518. fprintf(stderr, "ERROR: Error initializing networks in Redis: %s\n", e.what());
  519. exit(-1);
  520. } catch (std::exception &e) {
  521. fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
  522. exit(-1);
  523. }
  524. }
  525. void PostgreSQL::initializeMembers(PGconn *conn)
  526. {
  527. try {
  528. if (PQstatus(conn) != CONNECTION_OK) {
  529. fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
  530. exit(1);
  531. }
  532. // std::string setKeyBase = "network-nodes-all:{" + _myAddressStr + "}:";
  533. // if (_rc != NULL) {
  534. // std::lock_guard<std::mutex> l(_networks_l);
  535. // std::unordered_set<std::string> deletes;
  536. // for ( auto it : _networks) {
  537. // uint64_t nwid_i = it.first;
  538. // char nwidTmp[64] = {0};
  539. // OSUtils::ztsnprintf(nwidTmp, sizeof(nwidTmp), "%.16llx", nwid_i);
  540. // std::string nwid(nwidTmp);
  541. // std::string key = setKeyBase + nwid;
  542. // deletes.insert(key);
  543. // }
  544. // if (!deletes.empty()) {
  545. // if (_rc->clusterMode) {
  546. // auto tx = _cluster->transaction(_myAddressStr, true);
  547. // for (std::string k : deletes) {
  548. // tx.del(k);
  549. // }
  550. // tx.exec();
  551. // } else {
  552. // auto tx = _redis->transaction(true);
  553. // for (std::string k : deletes) {
  554. // tx.del(k);
  555. // }
  556. // tx.exec();
  557. // }
  558. // }
  559. // }
  560. const char *params[1] = {
  561. _myAddressStr.c_str()
  562. };
  563. std::unordered_map<std::string, std::string> networkMembers;
  564. fprintf(stderr, "Initializing Members...\n");
  565. PGresult *res = PQexecParams(conn,
  566. "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, "
  567. " EXTRACT(EPOCH FROM m.last_authorized_time AT TIME ZONE 'UTC')*1000, "
  568. " EXTRACT(EPOCH FROM m.last_deauthorized_time AT TIME ZONE 'UTC')*1000, "
  569. " m.remote_trace_level, m.remote_trace_target, m.tags, m.v_major, m.v_minor, m.v_rev, m.v_proto, "
  570. " m.no_auto_assign_ips, m.revision "
  571. "FROM ztc_member m "
  572. "INNER JOIN ztc_network n "
  573. " ON n.id = m.network_id "
  574. "WHERE n.controller_id = $1 AND m.deleted = false",
  575. 1,
  576. NULL,
  577. params,
  578. NULL,
  579. NULL,
  580. 0);
  581. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  582. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  583. PQclear(res);
  584. exit(1);
  585. }
  586. int numRows = PQntuples(res);
  587. for (int i = 0; i < numRows; ++i) {
  588. json empty;
  589. json config;
  590. std::string memberId(PQgetvalue(res, i, 0));
  591. std::string networkId(PQgetvalue(res, i, 1));
  592. // networkMembers.insert(std::pair<std::string, std::string>(setKeyBase+networkId, memberId));
  593. std::string ctime = PQgetvalue(res, i, 5);
  594. config["id"] = memberId;
  595. config["nwid"] = networkId;
  596. config["activeBridge"] = (strcmp(PQgetvalue(res, i, 2), "t") == 0);
  597. config["authorized"] = (strcmp(PQgetvalue(res, i, 3), "t") == 0);
  598. try {
  599. config["capabilities"] = json::parse(PQgetvalue(res, i, 4));
  600. } catch (std::exception &e) {
  601. config["capabilities"] = json::array();
  602. }
  603. try {
  604. config["creationTime"] = std::stoull(PQgetvalue(res, i, 5));
  605. } catch (std::exception &e) {
  606. config["creationTime"] = 0ULL;
  607. //fprintf(stderr, "Error upding creation time (member): %s\n", PQgetvalue(res, i, 5));
  608. }
  609. config["identity"] = PQgetvalue(res, i, 6);
  610. try {
  611. config["lastAuthorizedTime"] = std::stoull(PQgetvalue(res, i, 7));
  612. } catch(std::exception &e) {
  613. config["lastAuthorizedTime"] = 0ULL;
  614. //fprintf(stderr, "Error updating last auth time (member): %s\n", PQgetvalue(res, i, 7));
  615. }
  616. try {
  617. config["lastDeauthorizedTime"] = std::stoull(PQgetvalue(res, i, 8));
  618. } catch( std::exception &e) {
  619. config["lastDeauthorizedTime"] = 0ULL;
  620. //fprintf(stderr, "Error updating last deauth time (member): %s\n", PQgetvalue(res, i, 8));
  621. }
  622. try {
  623. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
  624. } catch (std::exception &e) {
  625. config["remoteTraceLevel"] = 0;
  626. }
  627. config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
  628. try {
  629. config["tags"] = json::parse(PQgetvalue(res, i, 11));
  630. } catch (std::exception &e) {
  631. config["tags"] = json::array();
  632. }
  633. try {
  634. config["vMajor"] = std::stoi(PQgetvalue(res, i, 12));
  635. } catch(std::exception &e) {
  636. config["vMajor"] = -1;
  637. }
  638. try {
  639. config["vMinor"] = std::stoi(PQgetvalue(res, i, 13));
  640. } catch (std::exception &e) {
  641. config["vMinor"] = -1;
  642. }
  643. try {
  644. config["vRev"] = std::stoi(PQgetvalue(res, i, 14));
  645. } catch (std::exception &e) {
  646. config["vRev"] = -1;
  647. }
  648. try {
  649. config["vProto"] = std::stoi(PQgetvalue(res, i, 15));
  650. } catch (std::exception &e) {
  651. config["vProto"] = -1;
  652. }
  653. config["noAutoAssignIps"] = (strcmp(PQgetvalue(res, i, 16), "t") == 0);
  654. try {
  655. config["revision"] = std::stoull(PQgetvalue(res, i, 17));
  656. } catch (std::exception &e) {
  657. config["revision"] = 0ULL;
  658. //fprintf(stderr, "Error updating revision (member): %s\n", PQgetvalue(res, i, 17));
  659. }
  660. config["objtype"] = "member";
  661. config["ipAssignments"] = json::array();
  662. const char *p2[2] = {
  663. memberId.c_str(),
  664. networkId.c_str()
  665. };
  666. PGresult *r2 = PQexecParams(conn,
  667. "SELECT DISTINCT address FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  668. 2,
  669. NULL,
  670. p2,
  671. NULL,
  672. NULL,
  673. 0);
  674. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  675. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  676. PQclear(r2);
  677. PQclear(res);
  678. exit(1);
  679. }
  680. int n = PQntuples(r2);
  681. for (int j = 0; j < n; ++j) {
  682. std::string ipaddr = PQgetvalue(r2, j, 0);
  683. std::size_t pos = ipaddr.find('/');
  684. if (pos != std::string::npos) {
  685. ipaddr = ipaddr.substr(0, pos);
  686. }
  687. config["ipAssignments"].push_back(ipaddr);
  688. }
  689. _memberChanged(empty, config, false);
  690. }
  691. PQclear(res);
  692. // if (!networkMembers.empty()) {
  693. // if (_rc != NULL) {
  694. // if (_rc->clusterMode) {
  695. // auto tx = _cluster->transaction(_myAddressStr, true);
  696. // for (auto it : networkMembers) {
  697. // tx.sadd(it.first, it.second);
  698. // }
  699. // tx.exec();
  700. // } else {
  701. // auto tx = _redis->transaction(true);
  702. // for (auto it : networkMembers) {
  703. // tx.sadd(it.first, it.second);
  704. // }
  705. // tx.exec();
  706. // }
  707. // }
  708. // }
  709. if (++this->_ready == 2) {
  710. if (_waitNoticePrinted) {
  711. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  712. }
  713. _readyLock.unlock();
  714. }
  715. } catch (sw::redis::Error &e) {
  716. fprintf(stderr, "ERROR: Error initializing members (redis): %s\n", e.what());
  717. } catch (std::exception &e) {
  718. fprintf(stderr, "ERROR: Error initializing members: %s\n", e.what());
  719. exit(-1);
  720. }
  721. }
  722. void PostgreSQL::heartbeat()
  723. {
  724. char publicId[1024];
  725. char hostnameTmp[1024];
  726. _myId.toString(false,publicId);
  727. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  728. hostnameTmp[0] = (char)0;
  729. } else {
  730. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  731. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  732. hostnameTmp[i] = (char)0;
  733. break;
  734. }
  735. }
  736. }
  737. const char *controllerId = _myAddressStr.c_str();
  738. const char *publicIdentity = publicId;
  739. const char *hostname = hostnameTmp;
  740. PGconn *conn = getPgConn();
  741. if (PQstatus(conn) == CONNECTION_BAD) {
  742. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  743. PQfinish(conn);
  744. exit(1);
  745. }
  746. while (_run == 1) {
  747. if(PQstatus(conn) != CONNECTION_OK) {
  748. fprintf(stderr, "%s heartbeat thread lost connection to Database\n", _myAddressStr.c_str());
  749. PQfinish(conn);
  750. exit(6);
  751. }
  752. int64_t ts = OSUtils::now();
  753. if (conn) {
  754. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  755. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  756. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  757. std::string build = std::to_string(ZEROTIER_ONE_VERSION_BUILD);
  758. std::string now = std::to_string(ts);
  759. std::string host_port = std::to_string(_listenPort);
  760. std::string use_redis = "false"; // (_rc != NULL) ? "true" : "false";
  761. const char *values[10] = {
  762. controllerId,
  763. hostname,
  764. now.c_str(),
  765. publicIdentity,
  766. major.c_str(),
  767. minor.c_str(),
  768. rev.c_str(),
  769. build.c_str(),
  770. host_port.c_str(),
  771. use_redis.c_str()
  772. };
  773. PGresult *res = PQexecParams(conn,
  774. "INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build, host_port, use_redis) "
  775. "VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8, $9, $10) "
  776. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  777. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  778. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev, host_port = EXCLUDED.host_port, "
  779. "use_redis = EXCLUDED.use_redis",
  780. 10, // number of parameters
  781. NULL, // oid field. ignore
  782. values, // values for substitution
  783. NULL, // lengths in bytes of each value
  784. NULL, // binary?
  785. 0);
  786. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  787. fprintf(stderr, "Heartbeat Update Failed: %s\n", PQresultErrorMessage(res));
  788. }
  789. PQclear(res);
  790. }
  791. // if (_rc != NULL) {
  792. // if (_rc->clusterMode) {
  793. // _cluster->zadd("controllers", controllerId, ts);
  794. // } else {
  795. // _redis->zadd("controllers", controllerId, ts);
  796. // }
  797. // }
  798. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  799. }
  800. PQfinish(conn);
  801. conn = NULL;
  802. fprintf(stderr, "Exited heartbeat thread\n");
  803. }
  804. void PostgreSQL::membersDbWatcher()
  805. {
  806. PGconn *conn = getPgConn(NO_OVERRIDE);
  807. if (PQstatus(conn) == CONNECTION_BAD) {
  808. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  809. PQfinish(conn);
  810. exit(1);
  811. }
  812. if (_rc) {
  813. PQfinish(conn);
  814. conn = NULL;
  815. _membersWatcher_Redis();
  816. } else {
  817. _membersWatcher_Postgres(conn);
  818. PQfinish(conn);
  819. conn = NULL;
  820. }
  821. if (_run == 1) {
  822. fprintf(stderr, "ERROR: %s membersDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  823. exit(9);
  824. }
  825. fprintf(stderr, "Exited membersDbWatcher\n");
  826. }
  827. void PostgreSQL::_membersWatcher_Postgres(PGconn *conn) {
  828. char buf[11] = {0};
  829. std::string cmd = "LISTEN member_" + std::string(_myAddress.toString(buf));
  830. fprintf(stderr, "Listening to member stream: %s\n", cmd.c_str());
  831. PGresult *res = PQexec(conn, cmd.c_str());
  832. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  833. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  834. PQclear(res);
  835. PQfinish(conn);
  836. exit(1);
  837. }
  838. PQclear(res); res = NULL;
  839. while(_run == 1) {
  840. if (PQstatus(conn) != CONNECTION_OK) {
  841. fprintf(stderr, "ERROR: Member Watcher lost connection to Postgres.");
  842. exit(-1);
  843. }
  844. PGnotify *notify = NULL;
  845. PQconsumeInput(conn);
  846. while ((notify = PQnotifies(conn)) != NULL) {
  847. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  848. try {
  849. json tmp(json::parse(notify->extra));
  850. json &ov = tmp["old_val"];
  851. json &nv = tmp["new_val"];
  852. json oldConfig, newConfig;
  853. if (ov.is_object()) oldConfig = ov;
  854. if (nv.is_object()) newConfig = nv;
  855. if (oldConfig.is_object() || newConfig.is_object()) {
  856. _memberChanged(oldConfig,newConfig,(this->_ready>=2));
  857. }
  858. } catch (...) {} // ignore bad records
  859. free(notify);
  860. }
  861. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  862. }
  863. }
  864. void PostgreSQL::_membersWatcher_Redis() {
  865. char buf[11] = {0};
  866. std::string key = "member-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  867. fprintf(stderr, "Listening to member stream: %s\n", key.c_str());
  868. while (_run == 1) {
  869. try {
  870. json tmp;
  871. std::unordered_map<std::string, ItemStream> result;
  872. if (_rc->clusterMode) {
  873. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  874. } else {
  875. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  876. }
  877. if (!result.empty()) {
  878. for (auto element : result) {
  879. #ifdef ZT_TRACE
  880. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  881. #endif
  882. for (auto rec : element.second) {
  883. std::string id = rec.first;
  884. auto attrs = rec.second;
  885. #ifdef ZT_TRACE
  886. fprintf(stdout, "Record ID: %s\n", id.c_str());
  887. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  888. #endif
  889. for (auto a : attrs) {
  890. #ifdef ZT_TRACE
  891. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  892. #endif
  893. try {
  894. tmp = json::parse(a.second);
  895. json &ov = tmp["old_val"];
  896. json &nv = tmp["new_val"];
  897. json oldConfig, newConfig;
  898. if (ov.is_object()) oldConfig = ov;
  899. if (nv.is_object()) newConfig = nv;
  900. if (oldConfig.is_object()||newConfig.is_object()) {
  901. _memberChanged(oldConfig,newConfig,(this->_ready >= 2));
  902. }
  903. } catch (...) {
  904. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  905. }
  906. }
  907. if (_rc->clusterMode) {
  908. _cluster->xdel(key, id);
  909. } else {
  910. _redis->xdel(key, id);
  911. }
  912. }
  913. }
  914. }
  915. } catch (sw::redis::Error &e) {
  916. fprintf(stderr, "Error in Redis members watcher: %s\n", e.what());
  917. }
  918. }
  919. fprintf(stderr, "membersWatcher ended\n");
  920. }
  921. void PostgreSQL::networksDbWatcher()
  922. {
  923. PGconn *conn = getPgConn(NO_OVERRIDE);
  924. if (PQstatus(conn) == CONNECTION_BAD) {
  925. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  926. PQfinish(conn);
  927. exit(1);
  928. }
  929. if (_rc) {
  930. PQfinish(conn);
  931. conn = NULL;
  932. _networksWatcher_Redis();
  933. } else {
  934. _networksWatcher_Postgres(conn);
  935. PQfinish(conn);
  936. conn = NULL;
  937. }
  938. if (_run == 1) {
  939. fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  940. exit(8);
  941. }
  942. fprintf(stderr, "Exited networksDbWatcher\n");
  943. }
  944. void PostgreSQL::_networksWatcher_Postgres(PGconn *conn) {
  945. char buf[11] = {0};
  946. std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
  947. PGresult *res = PQexec(conn, cmd.c_str());
  948. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  949. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  950. PQclear(res);
  951. PQfinish(conn);
  952. exit(1);
  953. }
  954. PQclear(res); res = NULL;
  955. while(_run == 1) {
  956. if (PQstatus(conn) != CONNECTION_OK) {
  957. fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
  958. exit(-1);
  959. }
  960. PGnotify *notify = NULL;
  961. PQconsumeInput(conn);
  962. while ((notify = PQnotifies(conn)) != NULL) {
  963. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  964. try {
  965. json tmp(json::parse(notify->extra));
  966. json &ov = tmp["old_val"];
  967. json &nv = tmp["new_val"];
  968. json oldConfig, newConfig;
  969. if (ov.is_object()) oldConfig = ov;
  970. if (nv.is_object()) newConfig = nv;
  971. if (oldConfig.is_object()||newConfig.is_object()) {
  972. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  973. }
  974. } catch (...) {} // ignore bad records
  975. free(notify);
  976. }
  977. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  978. }
  979. }
  980. void PostgreSQL::_networksWatcher_Redis() {
  981. char buf[11] = {0};
  982. std::string key = "network-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  983. while (_run == 1) {
  984. try {
  985. json tmp;
  986. std::unordered_map<std::string, ItemStream> result;
  987. if (_rc->clusterMode) {
  988. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  989. } else {
  990. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  991. }
  992. if (!result.empty()) {
  993. for (auto element : result) {
  994. #ifdef ZT_TRACE
  995. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  996. #endif
  997. for (auto rec : element.second) {
  998. std::string id = rec.first;
  999. auto attrs = rec.second;
  1000. #ifdef ZT_TRACE
  1001. fprintf(stdout, "Record ID: %s\n", id.c_str());
  1002. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  1003. #endif
  1004. for (auto a : attrs) {
  1005. #ifdef ZT_TRACE
  1006. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  1007. #endif
  1008. try {
  1009. tmp = json::parse(a.second);
  1010. json &ov = tmp["old_val"];
  1011. json &nv = tmp["new_val"];
  1012. json oldConfig, newConfig;
  1013. if (ov.is_object()) oldConfig = ov;
  1014. if (nv.is_object()) newConfig = nv;
  1015. if (oldConfig.is_object()||newConfig.is_object()) {
  1016. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  1017. }
  1018. } catch (...) {
  1019. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  1020. }
  1021. }
  1022. if (_rc->clusterMode) {
  1023. _cluster->xdel(key, id);
  1024. } else {
  1025. _redis->xdel(key, id);
  1026. }
  1027. }
  1028. }
  1029. }
  1030. } catch (sw::redis::Error &e) {
  1031. fprintf(stderr, "Error in Redis networks watcher: %s\n", e.what());
  1032. }
  1033. }
  1034. fprintf(stderr, "networksWatcher ended\n");
  1035. }
  1036. void PostgreSQL::commitThread()
  1037. {
  1038. PGconn *conn = getPgConn();
  1039. if (PQstatus(conn) == CONNECTION_BAD) {
  1040. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  1041. PQfinish(conn);
  1042. exit(1);
  1043. }
  1044. std::pair<nlohmann::json,bool> qitem;
  1045. while(_commitQueue.get(qitem)&(_run == 1)) {
  1046. if (!qitem.first.is_object()) {
  1047. continue;
  1048. }
  1049. if (PQstatus(conn) == CONNECTION_BAD) {
  1050. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  1051. PQfinish(conn);
  1052. exit(1);
  1053. }
  1054. try {
  1055. nlohmann::json *config = &(qitem.first);
  1056. const std::string objtype = (*config)["objtype"];
  1057. if (objtype == "member") {
  1058. try {
  1059. std::string memberId = (*config)["id"];
  1060. std::string networkId = (*config)["nwid"];
  1061. std::string identity = (*config)["identity"];
  1062. std::string target = "NULL";
  1063. if (!(*config)["remoteTraceTarget"].is_null()) {
  1064. target = (*config)["remoteTraceTarget"];
  1065. }
  1066. std::string caps = OSUtils::jsonDump((*config)["capabilities"], -1);
  1067. std::string lastAuthTime = std::to_string((long long)(*config)["lastAuthorizedTime"]);
  1068. std::string lastDeauthTime = std::to_string((long long)(*config)["lastDeauthorizedTime"]);
  1069. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  1070. std::string rev = std::to_string((unsigned long long)(*config)["revision"]);
  1071. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  1072. std::string vmajor = std::to_string((int)(*config)["vMajor"]);
  1073. std::string vminor = std::to_string((int)(*config)["vMinor"]);
  1074. std::string vrev = std::to_string((int)(*config)["vRev"]);
  1075. std::string vproto = std::to_string((int)(*config)["vProto"]);
  1076. const char *values[19] = {
  1077. memberId.c_str(),
  1078. networkId.c_str(),
  1079. ((*config)["activeBridge"] ? "true" : "false"),
  1080. ((*config)["authorized"] ? "true" : "false"),
  1081. caps.c_str(),
  1082. identity.c_str(),
  1083. lastAuthTime.c_str(),
  1084. lastDeauthTime.c_str(),
  1085. ((*config)["noAutoAssignIps"] ? "true" : "false"),
  1086. rtraceLevel.c_str(),
  1087. (target == "NULL") ? NULL : target.c_str(),
  1088. rev.c_str(),
  1089. tags.c_str(),
  1090. vmajor.c_str(),
  1091. vminor.c_str(),
  1092. vrev.c_str(),
  1093. vproto.c_str()
  1094. };
  1095. PGresult *res = PQexec(conn, "BEGIN");
  1096. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1097. fprintf(stderr, "ERROR: Error beginning update transaction: %s\n", PQresultErrorMessage(res));
  1098. PQclear(res);
  1099. delete config;
  1100. config = nullptr;
  1101. continue;
  1102. }
  1103. res = PQexecParams(conn,
  1104. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  1105. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  1106. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  1107. "VALUES ($1, $2, $3, $4, $5, $6, "
  1108. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  1109. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  1110. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  1111. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  1112. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  1113. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  1114. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  1115. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  1116. 17,
  1117. NULL,
  1118. values,
  1119. NULL,
  1120. NULL,
  1121. 0);
  1122. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1123. fprintf(stderr, "ERROR: Error updating member: %s\n", PQresultErrorMessage(res));
  1124. fprintf(stderr, "%s", OSUtils::jsonDump(*config, 2).c_str());
  1125. PQclear(res);
  1126. PQclear(PQexec(conn, "ROLLBACK"));
  1127. delete config;
  1128. config = nullptr;
  1129. continue;
  1130. }
  1131. PQclear(res);
  1132. const char *v2[2] = {
  1133. memberId.c_str(),
  1134. networkId.c_str()
  1135. };
  1136. res = PQexecParams(conn,
  1137. "DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  1138. 2,
  1139. NULL,
  1140. v2,
  1141. NULL,
  1142. NULL,
  1143. 0);
  1144. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1145. fprintf(stderr, "ERROR: Error updating IP address assignments: %s\n", PQresultErrorMessage(res));
  1146. PQclear(res);
  1147. PQclear(PQexec(conn, "ROLLBACK"));;
  1148. delete config;
  1149. config = nullptr;
  1150. continue;
  1151. }
  1152. PQclear(res);
  1153. std::vector<std::string> assignments;
  1154. bool ipAssignError = false;
  1155. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  1156. std::string addr = *i;
  1157. if (std::find(assignments.begin(), assignments.end(), addr) != assignments.end()) {
  1158. continue;
  1159. }
  1160. const char *v3[3] = {
  1161. memberId.c_str(),
  1162. networkId.c_str(),
  1163. addr.c_str()
  1164. };
  1165. res = PQexecParams(conn,
  1166. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3) ON CONFLICT (network_id, member_id, address) DO NOTHING",
  1167. 3,
  1168. NULL,
  1169. v3,
  1170. NULL,
  1171. NULL,
  1172. 0);
  1173. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1174. fprintf(stderr, "ERROR: Error setting IP addresses for member: %s\n", PQresultErrorMessage(res));
  1175. PQclear(res);
  1176. PQclear(PQexec(conn, "ROLLBACK"));
  1177. ipAssignError = true;
  1178. break;
  1179. }
  1180. PQclear(res);
  1181. assignments.push_back(addr);
  1182. }
  1183. if (ipAssignError) {
  1184. delete config;
  1185. config = nullptr;
  1186. continue;
  1187. }
  1188. res = PQexec(conn, "COMMIT");
  1189. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1190. fprintf(stderr, "ERROR: Error committing member transaction: %s\n", PQresultErrorMessage(res));
  1191. PQclear(res);
  1192. PQclear(PQexec(conn, "ROLLBACK"));
  1193. delete config;
  1194. config = nullptr;
  1195. continue;
  1196. }
  1197. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  1198. const uint64_t memberidInt = OSUtils::jsonIntHex((*config)["id"], 0ULL);
  1199. if (nwidInt && memberidInt) {
  1200. nlohmann::json nwOrig;
  1201. nlohmann::json memOrig;
  1202. nlohmann::json memNew(*config);
  1203. get(nwidInt, nwOrig, memberidInt, memOrig);
  1204. _memberChanged(memOrig, memNew, qitem.second);
  1205. } else {
  1206. fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %llu-%llu\n", (unsigned long long)nwidInt, (unsigned long long)memberidInt);
  1207. }
  1208. } catch (std::exception &e) {
  1209. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  1210. }
  1211. } else if (objtype == "network") {
  1212. try {
  1213. std::string id = (*config)["id"];
  1214. std::string controllerId = _myAddressStr.c_str();
  1215. std::string name = (*config)["name"];
  1216. std::string remoteTraceTarget("NULL");
  1217. if (!(*config)["remoteTraceTarget"].is_null()) {
  1218. remoteTraceTarget = (*config)["remoteTraceTarget"];
  1219. }
  1220. std::string rulesSource;
  1221. if ((*config)["rulesSource"].is_string()) {
  1222. rulesSource = (*config)["rulesSource"];
  1223. }
  1224. std::string caps = OSUtils::jsonDump((*config)["capabilitles"], -1);
  1225. std::string now = std::to_string(OSUtils::now());
  1226. std::string mtu = std::to_string((int)(*config)["mtu"]);
  1227. std::string mcastLimit = std::to_string((int)(*config)["multicastLimit"]);
  1228. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  1229. std::string rules = OSUtils::jsonDump((*config)["rules"], -1);
  1230. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  1231. std::string v4mode = OSUtils::jsonDump((*config)["v4AssignMode"],-1);
  1232. std::string v6mode = OSUtils::jsonDump((*config)["v6AssignMode"], -1);
  1233. bool enableBroadcast = (*config)["enableBroadcast"];
  1234. bool isPrivate = (*config)["private"];
  1235. const char *values[16] = {
  1236. id.c_str(),
  1237. controllerId.c_str(),
  1238. caps.c_str(),
  1239. enableBroadcast ? "true" : "false",
  1240. now.c_str(),
  1241. mtu.c_str(),
  1242. mcastLimit.c_str(),
  1243. name.c_str(),
  1244. isPrivate ? "true" : "false",
  1245. rtraceLevel.c_str(),
  1246. (remoteTraceTarget == "NULL" ? NULL : remoteTraceTarget.c_str()),
  1247. rules.c_str(),
  1248. rulesSource.c_str(),
  1249. tags.c_str(),
  1250. v4mode.c_str(),
  1251. v6mode.c_str(),
  1252. };
  1253. PGresult *res = PQexec(conn, "BEGIN");
  1254. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1255. fprintf(stderr, "ERROR: Error beginnning transaction: %s\n", PQresultErrorMessage(res));
  1256. PQclear(res);
  1257. delete config;
  1258. config = nullptr;
  1259. continue;
  1260. }
  1261. PQclear(res);
  1262. // This ugly query exists because when we want to mirror networks to/from
  1263. // another data store (e.g. FileDB or LFDB) it is possible to get a network
  1264. // that doesn't exist in Central's database. This does an upsert and sets
  1265. // the owner_id to the "first" global admin in the user DB if the record
  1266. // did not previously exist. If the record already exists owner_id is left
  1267. // unchanged, so owner_id should be left out of the update clause.
  1268. res = PQexecParams(conn,
  1269. "INSERT INTO ztc_network (id, creation_time, owner_id, controller_id, capabilities, enable_broadcast, "
  1270. "last_modified, mtu, multicast_limit, name, private, "
  1271. "remote_trace_level, remote_trace_target, rules, rules_source, "
  1272. "tags, v4_assign_mode, v6_assign_mode) VALUES ("
  1273. "$1, TO_TIMESTAMP($5::double precision/1000), "
  1274. "(SELECT user_id AS owner_id FROM ztc_global_permissions WHERE authorize = true AND del = true AND modify = true AND read = true LIMIT 1),"
  1275. "$2, $3, $4, TO_TIMESTAMP($5::double precision/1000), "
  1276. "$6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) "
  1277. "ON CONFLICT (id) DO UPDATE set controller_id = EXCLUDED.controller_id, "
  1278. "capabilities = EXCLUDED.capabilities, enable_broadcast = EXCLUDED.enable_broadcast, "
  1279. "last_modified = EXCLUDED.last_modified, mtu = EXCLUDED.mtu, "
  1280. "multicast_limit = EXCLUDED.multicast_limit, name = EXCLUDED.name, "
  1281. "private = EXCLUDED.private, remote_trace_level = EXCLUDED.remote_trace_level, "
  1282. "remote_trace_target = EXCLUDED.remote_trace_target, rules = EXCLUDED.rules, "
  1283. "rules_source = EXCLUDED.rules_source, tags = EXCLUDED.tags, "
  1284. "v4_assign_mode = EXCLUDED.v4_assign_mode, v6_assign_mode = EXCLUDED.v6_assign_mode",
  1285. 16,
  1286. NULL,
  1287. values,
  1288. NULL,
  1289. NULL,
  1290. 0);
  1291. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1292. fprintf(stderr, "ERROR: Error updating network record: %s\n", PQresultErrorMessage(res));
  1293. PQclear(res);
  1294. PQclear(PQexec(conn, "ROLLBACK"));
  1295. delete config;
  1296. config = nullptr;
  1297. continue;
  1298. }
  1299. PQclear(res);
  1300. const char *params[1] = {
  1301. id.c_str()
  1302. };
  1303. res = PQexecParams(conn,
  1304. "DELETE FROM ztc_network_assignment_pool WHERE network_id = $1",
  1305. 1,
  1306. NULL,
  1307. params,
  1308. NULL,
  1309. NULL,
  1310. 0);
  1311. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1312. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  1313. PQclear(res);
  1314. PQclear(PQexec(conn, "ROLLBACK"));
  1315. delete config;
  1316. config = nullptr;
  1317. continue;
  1318. }
  1319. PQclear(res);
  1320. auto pool = (*config)["ipAssignmentPools"];
  1321. bool err = false;
  1322. for (auto i = pool.begin(); i != pool.end(); ++i) {
  1323. std::string start = (*i)["ipRangeStart"];
  1324. std::string end = (*i)["ipRangeEnd"];
  1325. const char *p[3] = {
  1326. id.c_str(),
  1327. start.c_str(),
  1328. end.c_str()
  1329. };
  1330. res = PQexecParams(conn,
  1331. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  1332. "VALUES ($1, $2, $3)",
  1333. 3,
  1334. NULL,
  1335. p,
  1336. NULL,
  1337. NULL,
  1338. 0);
  1339. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1340. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  1341. PQclear(res);
  1342. err = true;
  1343. break;
  1344. }
  1345. PQclear(res);
  1346. }
  1347. if (err) {
  1348. PQclear(res);
  1349. PQclear(PQexec(conn, "ROLLBACK"));
  1350. delete config;
  1351. config = nullptr;
  1352. continue;
  1353. }
  1354. res = PQexecParams(conn,
  1355. "DELETE FROM ztc_network_route WHERE network_id = $1",
  1356. 1,
  1357. NULL,
  1358. params,
  1359. NULL,
  1360. NULL,
  1361. 0);
  1362. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1363. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  1364. PQclear(res);
  1365. PQclear(PQexec(conn, "ROLLBACK"));
  1366. delete config;
  1367. config = nullptr;
  1368. continue;
  1369. }
  1370. auto routes = (*config)["routes"];
  1371. err = false;
  1372. for (auto i = routes.begin(); i != routes.end(); ++i) {
  1373. std::string t = (*i)["target"];
  1374. std::vector<std::string> target;
  1375. std::istringstream f(t);
  1376. std::string s;
  1377. while(std::getline(f, s, '/')) {
  1378. target.push_back(s);
  1379. }
  1380. if (target.empty() || target.size() != 2) {
  1381. continue;
  1382. }
  1383. std::string targetAddr = target[0];
  1384. std::string targetBits = target[1];
  1385. std::string via = "NULL";
  1386. if (!(*i)["via"].is_null()) {
  1387. via = (*i)["via"];
  1388. }
  1389. const char *p[4] = {
  1390. id.c_str(),
  1391. targetAddr.c_str(),
  1392. targetBits.c_str(),
  1393. (via == "NULL" ? NULL : via.c_str()),
  1394. };
  1395. res = PQexecParams(conn,
  1396. "INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  1397. 4,
  1398. NULL,
  1399. p,
  1400. NULL,
  1401. NULL,
  1402. 0);
  1403. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1404. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  1405. PQclear(res);
  1406. err = true;
  1407. break;
  1408. }
  1409. PQclear(res);
  1410. }
  1411. if (err) {
  1412. PQclear(PQexec(conn, "ROLLBACK"));
  1413. delete config;
  1414. config = nullptr;
  1415. continue;
  1416. }
  1417. auto dns = (*config)["dns"];
  1418. std::string domain = dns["domain"];
  1419. std::stringstream servers;
  1420. servers << "{";
  1421. for (auto j = dns["servers"].begin(); j < dns["servers"].end(); ++j) {
  1422. servers << *j;
  1423. if ( (j+1) != dns["servers"].end()) {
  1424. servers << ",";
  1425. }
  1426. }
  1427. servers << "}";
  1428. const char *p[3] = {
  1429. id.c_str(),
  1430. domain.c_str(),
  1431. servers.str().c_str()
  1432. };
  1433. res = PQexecParams(conn, "INSERT INTO ztc_network_dns (network_id, domain, servers) VALUES ($1, $2, $3) ON CONFLICT (network_id) DO UPDATE SET domain = EXCLUDED.domain, servers = EXCLUDED.servers",
  1434. 3,
  1435. NULL,
  1436. p,
  1437. NULL,
  1438. NULL,
  1439. 0);
  1440. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1441. fprintf(stderr, "ERROR: Error updating DNS: %s\n", PQresultErrorMessage(res));
  1442. PQclear(res);
  1443. PQclear(PQexec(conn, "ROLLBACK"));
  1444. err = true;
  1445. break;
  1446. }
  1447. PQclear(res);
  1448. res = PQexec(conn, "COMMIT");
  1449. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1450. fprintf(stderr, "ERROR: Error committing network update: %s\n", PQresultErrorMessage(res));
  1451. PQclear(res);
  1452. PQclear(PQexec(conn, "ROLLBACK"));
  1453. delete config;
  1454. config = nullptr;
  1455. continue;
  1456. }
  1457. PQclear(res);
  1458. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  1459. if (nwidInt) {
  1460. nlohmann::json nwOrig;
  1461. nlohmann::json nwNew(*config);
  1462. get(nwidInt, nwOrig);
  1463. _networkChanged(nwOrig, nwNew, qitem.second);
  1464. } else {
  1465. fprintf(stderr, "Can't notify network changed: %llu\n", (unsigned long long)nwidInt);
  1466. }
  1467. } catch (std::exception &e) {
  1468. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  1469. }
  1470. // if (_rc != NULL) {
  1471. // try {
  1472. // std::string id = (*config)["id"];
  1473. // std::string controllerId = _myAddressStr.c_str();
  1474. // std::string key = "networks:{" + controllerId + "}";
  1475. // if (_rc->clusterMode) {
  1476. // _cluster->sadd(key, id);
  1477. // } else {
  1478. // _redis->sadd(key, id);
  1479. // }
  1480. // } catch (sw::redis::Error &e) {
  1481. // fprintf(stderr, "ERROR: Error adding network to Redis: %s\n", e.what());
  1482. // }
  1483. // }
  1484. } else if (objtype == "_delete_network") {
  1485. try {
  1486. std::string networkId = (*config)["nwid"];
  1487. const char *values[1] = {
  1488. networkId.c_str()
  1489. };
  1490. PGresult * res = PQexecParams(conn,
  1491. "UPDATE ztc_network SET deleted = true WHERE id = $1",
  1492. 1,
  1493. NULL,
  1494. values,
  1495. NULL,
  1496. NULL,
  1497. 0);
  1498. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1499. fprintf(stderr, "ERROR: Error deleting network: %s\n", PQresultErrorMessage(res));
  1500. }
  1501. PQclear(res);
  1502. } catch (std::exception &e) {
  1503. fprintf(stderr, "ERROR: Error deleting network: %s\n", e.what());
  1504. }
  1505. // if (_rc != NULL) {
  1506. // try {
  1507. // std::string id = (*config)["id"];
  1508. // std::string controllerId = _myAddressStr.c_str();
  1509. // std::string key = "networks:{" + controllerId + "}";
  1510. // if (_rc->clusterMode) {
  1511. // _cluster->srem(key, id);
  1512. // _cluster->del("network-nodes-online:{"+controllerId+"}:"+id);
  1513. // } else {
  1514. // _redis->srem(key, id);
  1515. // _redis->del("network-nodes-online:{"+controllerId+"}:"+id);
  1516. // }
  1517. // } catch (sw::redis::Error &e) {
  1518. // fprintf(stderr, "ERROR: Error adding network to Redis: %s\n", e.what());
  1519. // }
  1520. // }
  1521. } else if (objtype == "_delete_member") {
  1522. try {
  1523. std::string memberId = (*config)["id"];
  1524. std::string networkId = (*config)["nwid"];
  1525. const char *values[2] = {
  1526. memberId.c_str(),
  1527. networkId.c_str()
  1528. };
  1529. PGresult *res = PQexecParams(conn,
  1530. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  1531. 2,
  1532. NULL,
  1533. values,
  1534. NULL,
  1535. NULL,
  1536. 0);
  1537. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1538. fprintf(stderr, "ERROR: Error deleting member: %s\n", PQresultErrorMessage(res));
  1539. }
  1540. PQclear(res);
  1541. } catch (std::exception &e) {
  1542. fprintf(stderr, "ERROR: Error deleting member: %s\n", e.what());
  1543. }
  1544. // if (_rc != NULL) {
  1545. // try {
  1546. // std::string memberId = (*config)["id"];
  1547. // std::string networkId = (*config)["nwid"];
  1548. // std::string controllerId = _myAddressStr.c_str();
  1549. // std::string key = "network-nodes-all:{" + controllerId + "}:" + networkId;
  1550. // if (_rc->clusterMode) {
  1551. // _cluster->srem(key, memberId);
  1552. // _cluster->del("member:{"+controllerId+"}:"+networkId+":"+memberId);
  1553. // } else {
  1554. // _redis->srem(key, memberId);
  1555. // _redis->del("member:{"+controllerId+"}:"+networkId+":"+memberId);
  1556. // }
  1557. // } catch (sw::redis::Error &e) {
  1558. // fprintf(stderr, "ERROR: Error deleting member from Redis: %s\n", e.what());
  1559. // }
  1560. // }
  1561. } else {
  1562. fprintf(stderr, "ERROR: unknown objtype");
  1563. }
  1564. } catch (std::exception &e) {
  1565. fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
  1566. }
  1567. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1568. }
  1569. PQfinish(conn);
  1570. if (_run == 1) {
  1571. fprintf(stderr, "ERROR: %s commitThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1572. exit(7);
  1573. }
  1574. fprintf(stderr, "commitThread finished\n");
  1575. }
  1576. void PostgreSQL::onlineNotificationThread()
  1577. {
  1578. waitForReady();
  1579. // if (_rc != NULL) {
  1580. // onlineNotification_Redis();
  1581. // } else {
  1582. onlineNotification_Postgres();
  1583. // }
  1584. }
  1585. void PostgreSQL::onlineNotification_Postgres()
  1586. {
  1587. PGconn *conn = getPgConn();
  1588. if (PQstatus(conn) == CONNECTION_BAD) {
  1589. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  1590. PQfinish(conn);
  1591. exit(1);
  1592. }
  1593. _connected = 1;
  1594. nlohmann::json jtmp1, jtmp2;
  1595. while (_run == 1) {
  1596. if (PQstatus(conn) != CONNECTION_OK) {
  1597. fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres.");
  1598. PQfinish(conn);
  1599. exit(5);
  1600. }
  1601. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1602. {
  1603. std::lock_guard<std::mutex> l(_lastOnline_l);
  1604. lastOnline.swap(_lastOnline);
  1605. }
  1606. PGresult *res = NULL;
  1607. std::stringstream memberUpdate;
  1608. memberUpdate << "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ";
  1609. bool firstRun = true;
  1610. bool memberAdded = false;
  1611. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1612. uint64_t nwid_i = i->first.first;
  1613. char nwidTmp[64];
  1614. char memTmp[64];
  1615. char ipTmp[64];
  1616. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1617. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  1618. if(!get(nwid_i, jtmp1, i->first.second, jtmp2)) {
  1619. continue; // skip non existent networks/members
  1620. }
  1621. std::string networkId(nwidTmp);
  1622. std::string memberId(memTmp);
  1623. const char *qvals[2] = {
  1624. networkId.c_str(),
  1625. memberId.c_str()
  1626. };
  1627. res = PQexecParams(conn,
  1628. "SELECT id, network_id FROM ztc_member WHERE network_id = $1 AND id = $2",
  1629. 2,
  1630. NULL,
  1631. qvals,
  1632. NULL,
  1633. NULL,
  1634. 0);
  1635. if (PQresultStatus(res) != PGRES_TUPLES_OK) {
  1636. fprintf(stderr, "Member count failed: %s", PQerrorMessage(conn));
  1637. PQclear(res);
  1638. continue;
  1639. }
  1640. int nrows = PQntuples(res);
  1641. PQclear(res);
  1642. if (nrows == 1) {
  1643. int64_t ts = i->second.first;
  1644. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1645. std::string timestamp = std::to_string(ts);
  1646. if (firstRun) {
  1647. firstRun = false;
  1648. } else {
  1649. memberUpdate << ", ";
  1650. }
  1651. memberUpdate << "('" << networkId << "', '" << memberId << "', ";
  1652. if (ipAddr.empty()) {
  1653. memberUpdate << "NULL, ";
  1654. } else {
  1655. memberUpdate << "'" << ipAddr << "', ";
  1656. }
  1657. memberUpdate << "TO_TIMESTAMP(" << timestamp << "::double precision/1000))";
  1658. memberAdded = true;
  1659. } else if (nrows > 1) {
  1660. fprintf(stderr, "nrows > 1?!?");
  1661. continue;
  1662. } else {
  1663. continue;
  1664. }
  1665. }
  1666. memberUpdate << " ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated;";
  1667. if (memberAdded) {
  1668. res = PQexec(conn, memberUpdate.str().c_str());
  1669. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1670. fprintf(stderr, "Multiple insert failed: %s", PQerrorMessage(conn));
  1671. }
  1672. PQclear(res);
  1673. }
  1674. std::this_thread::sleep_for(std::chrono::seconds(10));
  1675. }
  1676. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  1677. PQfinish(conn);
  1678. if (_run == 1) {
  1679. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1680. exit(6);
  1681. }
  1682. }
  1683. void PostgreSQL::onlineNotification_Redis()
  1684. {
  1685. _connected = 1;
  1686. char buf[11] = {0};
  1687. std::string controllerId = std::string(_myAddress.toString(buf));
  1688. while (_run == 1) {
  1689. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1690. {
  1691. std::lock_guard<std::mutex> l(_lastOnline_l);
  1692. lastOnline.swap(_lastOnline);
  1693. }
  1694. try {
  1695. if (!lastOnline.empty()) {
  1696. if (_rc->clusterMode) {
  1697. auto tx = _cluster->transaction(controllerId, true);
  1698. _doRedisUpdate(tx, controllerId, lastOnline);
  1699. } else {
  1700. auto tx = _redis->transaction(true);
  1701. _doRedisUpdate(tx, controllerId, lastOnline);
  1702. }
  1703. }
  1704. } catch (sw::redis::Error &e) {
  1705. #ifdef ZT_TRACE
  1706. fprintf(stderr, "Error in online notification thread (redis): %s\n", e.what());
  1707. #endif
  1708. }
  1709. std::this_thread::sleep_for(std::chrono::seconds(10));
  1710. }
  1711. }
  1712. void PostgreSQL::_doRedisUpdate(sw::redis::Transaction &tx, std::string &controllerId,
  1713. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > &lastOnline)
  1714. {
  1715. nlohmann::json jtmp1, jtmp2;
  1716. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1717. uint64_t nwid_i = i->first.first;
  1718. uint64_t memberid_i = i->first.second;
  1719. char nwidTmp[64];
  1720. char memTmp[64];
  1721. char ipTmp[64];
  1722. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1723. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", memberid_i);
  1724. if (!get(nwid_i, jtmp1, memberid_i, jtmp2)){
  1725. continue; // skip non existent members/networks
  1726. }
  1727. std::string networkId(nwidTmp);
  1728. std::string memberId(memTmp);
  1729. int64_t ts = i->second.first;
  1730. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1731. std::string timestamp = std::to_string(ts);
  1732. std::unordered_map<std::string, std::string> record = {
  1733. {"id", memberId},
  1734. {"address", ipAddr},
  1735. {"last_updated", std::to_string(ts)}
  1736. };
  1737. tx.zadd("nodes-online:{"+controllerId+"}", memberId, ts)
  1738. .zadd("nodes-online2:{"+controllerId+"}", networkId+"-"+memberId, ts)
  1739. .zadd("network-nodes-online:{"+controllerId+"}:"+networkId, memberId, ts)
  1740. .zadd("active-networks:{"+controllerId+"}", networkId, ts)
  1741. .sadd("network-nodes-all:{"+controllerId+"}:"+networkId, memberId)
  1742. .hmset("member:{"+controllerId+"}:"+networkId+":"+memberId, record.begin(), record.end());
  1743. }
  1744. // expire records from all-nodes and network-nodes member list
  1745. uint64_t expireOld = OSUtils::now() - 300000;
  1746. tx.zremrangebyscore("nodes-online:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1747. tx.zremrangebyscore("nodes-online2:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1748. tx.zremrangebyscore("active-networks:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1749. {
  1750. std::lock_guard<std::mutex> l(_networks_l);
  1751. for (const auto &it : _networks) {
  1752. uint64_t nwid_i = it.first;
  1753. char nwidTmp[64];
  1754. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1755. tx.zremrangebyscore("network-nodes-online:{"+controllerId+"}:"+nwidTmp,
  1756. sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1757. }
  1758. }
  1759. tx.exec();
  1760. }
  1761. PGconn *PostgreSQL::getPgConn(OverrideMode m)
  1762. {
  1763. if (m == ALLOW_PGBOUNCER_OVERRIDE) {
  1764. char *connStr = getenv("PGBOUNCER_CONNSTR");
  1765. if (connStr != NULL) {
  1766. fprintf(stderr, "PGBouncer Override\n");
  1767. std::string conn(connStr);
  1768. conn += " application_name=controller-";
  1769. conn += _myAddressStr.c_str();
  1770. return PQconnectdb(conn.c_str());
  1771. }
  1772. }
  1773. return PQconnectdb(_connString.c_str());
  1774. }
  1775. #endif //ZT_CONTROLLER_USE_LIBPQ