PostgreSQL.cpp 59 KB

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