PostgreSQL.cpp 40 KB

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