PostgreSQL.cpp 39 KB

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