PostgreSQL.cpp 40 KB

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