PostgreSQL.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  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);
  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_CONTROLLER_RETHINKDB_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_CONTROLLER_RETHINKDB_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. config["capabilities"] = json::parse(PQgetvalue(res, i, 4));
  342. try {
  343. config["creationTime"] = std::stoull(PQgetvalue(res, i, 5));
  344. } catch (std::exception &e) {
  345. config["creationTime"] = 0ULL;
  346. //fprintf(stderr, "Error upding creation time (member): %s\n", PQgetvalue(res, i, 5));
  347. }
  348. config["identity"] = PQgetvalue(res, i, 6);
  349. try {
  350. config["lastAuthorizedTime"] = std::stoull(PQgetvalue(res, i, 7));
  351. } catch(std::exception &e) {
  352. config["lastAuthorizedTime"] = 0ULL;
  353. //fprintf(stderr, "Error updating last auth time (member): %s\n", PQgetvalue(res, i, 7));
  354. }
  355. try {
  356. config["lastDeauthorizedTime"] = std::stoull(PQgetvalue(res, i, 8));
  357. } catch( std::exception &e) {
  358. config["lastDeauthorizedTime"] = 0ULL;
  359. //fprintf(stderr, "Error updating last deauth time (member): %s\n", PQgetvalue(res, i, 8));
  360. }
  361. try {
  362. config["remoteTraceLevel"] = std::stoi(PQgetvalue(res, i, 9));
  363. } catch (std::exception &e) {
  364. config["remoteTraceLevel"] = 0;
  365. }
  366. config["remoteTraceTarget"] = PQgetvalue(res, i, 10);
  367. config["tags"] = json::parse(PQgetvalue(res, i, 11));
  368. try {
  369. config["vMajor"] = std::stoi(PQgetvalue(res, i, 12));
  370. } catch(std::exception &e) {
  371. config["vMajor"] = -1;
  372. }
  373. try {
  374. config["vMinor"] = std::stoi(PQgetvalue(res, i, 13));
  375. } catch (std::exception &e) {
  376. config["vMinor"] = -1;
  377. }
  378. try {
  379. config["vRev"] = std::stoi(PQgetvalue(res, i, 14));
  380. } catch (std::exception &e) {
  381. config["vRev"] = -1;
  382. }
  383. try {
  384. config["vProto"] = std::stoi(PQgetvalue(res, i, 15));
  385. } catch (std::exception &e) {
  386. config["vProto"] = -1;
  387. }
  388. config["noAutoAssignIps"] = (strcmp(PQgetvalue(res, i, 16), "t") == 0);
  389. try {
  390. config["revision"] = std::stoull(PQgetvalue(res, i, 17));
  391. } catch (std::exception &e) {
  392. config["revision"] = 0ULL;
  393. //fprintf(stderr, "Error updating revision (member): %s\n", PQgetvalue(res, i, 17));
  394. }
  395. config["objtype"] = "member";
  396. config["ipAssignments"] = json::array();
  397. const char *p2[2] = {
  398. memberId.c_str(),
  399. networkId.c_str()
  400. };
  401. PGresult *r2 = PQexecParams(conn,
  402. "SELECT address FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  403. 2,
  404. NULL,
  405. p2,
  406. NULL,
  407. NULL,
  408. 0);
  409. if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
  410. fprintf(stderr, "Member Initialization Failed: %s", PQerrorMessage(conn));
  411. PQclear(r2);
  412. PQclear(res);
  413. exit(1);
  414. }
  415. int n = PQntuples(r2);
  416. for (int j = 0; j < n; ++j) {
  417. config["ipAssignments"].push_back(PQgetvalue(r2, j, 0));
  418. }
  419. _memberChanged(empty, config, false);
  420. }
  421. PQclear(res);
  422. if (++this->_ready == 2) {
  423. if (_waitNoticePrinted) {
  424. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  425. }
  426. _readyLock.unlock();
  427. }
  428. } catch (std::exception &e) {
  429. fprintf(stderr, "ERROR: Error initializing members: %s\n", e.what());
  430. exit(-1);
  431. }
  432. }
  433. void PostgreSQL::heartbeat()
  434. {
  435. char publicId[1024];
  436. char hostnameTmp[1024];
  437. _myId.toString(false,publicId);
  438. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  439. hostnameTmp[0] = (char)0;
  440. } else {
  441. for (int i = 0; i < sizeof(hostnameTmp); ++i) {
  442. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  443. hostnameTmp[i] = (char)0;
  444. break;
  445. }
  446. }
  447. }
  448. const char *controllerId = _myAddressStr.c_str();
  449. const char *publicIdentity = publicId;
  450. const char *hostname = hostnameTmp;
  451. PGconn *conn = PQconnectdb(_path.c_str());
  452. if (PQstatus(conn) == CONNECTION_BAD) {
  453. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  454. PQfinish(conn);
  455. exit(1);
  456. }
  457. while (_run == 1) {
  458. if(PQstatus(conn) != CONNECTION_OK) {
  459. PQfinish(conn);
  460. conn = PQconnectdb(_path.c_str());
  461. }
  462. if (conn) {
  463. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  464. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  465. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  466. std::string build = std::to_string(ZEROTIER_ONE_VERSION_BUILD);
  467. std::string now = std::to_string(OSUtils::now());
  468. const char *values[8] = {
  469. controllerId,
  470. hostname,
  471. now.c_str(),
  472. publicIdentity,
  473. major.c_str(),
  474. minor.c_str(),
  475. rev.c_str(),
  476. build.c_str()
  477. };
  478. PGresult *res = PQexecParams(conn,
  479. "INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build) "
  480. "VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8) "
  481. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  482. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  483. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev",
  484. 8, // number of parameters
  485. NULL, // oid field. ignore
  486. values, // values for substitution
  487. NULL, // lengths in bytes of each value
  488. NULL, // binary?
  489. 0);
  490. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  491. fprintf(stderr, "Heartbeat Update Failed: %s\n", PQresultErrorMessage(res));
  492. }
  493. PQclear(res);
  494. }
  495. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  496. }
  497. PQfinish(conn);
  498. conn = NULL;
  499. }
  500. void PostgreSQL::membersDbWatcher()
  501. {
  502. PGconn *conn = PQconnectdb(_path.c_str());
  503. if (PQstatus(conn) == CONNECTION_BAD) {
  504. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  505. PQfinish(conn);
  506. exit(1);
  507. }
  508. initializeMembers(conn);
  509. char buf[11] = {0};
  510. std::string cmd = "LISTEN member_" + std::string(_myAddress.toString(buf));
  511. PGresult *res = PQexec(conn, cmd.c_str());
  512. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  513. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  514. PQclear(res);
  515. PQfinish(conn);
  516. exit(1);
  517. }
  518. PQclear(res); res = NULL;
  519. while(_run == 1) {
  520. if (PQstatus(conn) != CONNECTION_OK) {
  521. fprintf(stderr, "ERROR: Member Watcher lost connection to Postgres.");
  522. exit(-1);
  523. }
  524. PGnotify *notify = NULL;
  525. PQconsumeInput(conn);
  526. while ((notify = PQnotifies(conn)) != NULL) {
  527. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  528. try {
  529. json tmp(json::parse(notify->extra));
  530. json &ov = tmp["old_val"];
  531. json &nv = tmp["new_val"];
  532. json oldConfig, newConfig;
  533. if (ov.is_object()) oldConfig = ov;
  534. if (nv.is_object()) newConfig = nv;
  535. if (oldConfig.is_object() || newConfig.is_object()) {
  536. _memberChanged(oldConfig,newConfig,(this->_ready>=2));
  537. }
  538. } catch (...) {} // ignore bad records
  539. free(notify);
  540. }
  541. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  542. }
  543. PQfinish(conn);
  544. conn = NULL;
  545. }
  546. void PostgreSQL::networksDbWatcher()
  547. {
  548. PGconn *conn = PQconnectdb(_path.c_str());
  549. if (PQstatus(conn) == CONNECTION_BAD) {
  550. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  551. PQfinish(conn);
  552. exit(1);
  553. }
  554. initializeNetworks(conn);
  555. char buf[11] = {0};
  556. std::string cmd = "LISTEN network_" + std::string(_myAddress.toString(buf));
  557. PGresult *res = PQexec(conn, cmd.c_str());
  558. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  559. fprintf(stderr, "LISTEN command failed: %s\n", PQresultErrorMessage(res));
  560. PQclear(res);
  561. PQfinish(conn);
  562. exit(1);
  563. }
  564. PQclear(res); res = NULL;
  565. while(_run == 1) {
  566. if (PQstatus(conn) != CONNECTION_OK) {
  567. fprintf(stderr, "ERROR: Network Watcher lost connection to Postgres.");
  568. exit(-1);
  569. }
  570. PGnotify *notify = NULL;
  571. PQconsumeInput(conn);
  572. while ((notify = PQnotifies(conn)) != NULL) {
  573. //fprintf(stderr, "ASYNC NOTIFY of '%s' id:%s received\n", notify->relname, notify->extra);
  574. try {
  575. json tmp(json::parse(notify->extra));
  576. json &ov = tmp["old_val"];
  577. json &nv = tmp["new_val"];
  578. json oldConfig, newConfig;
  579. if (ov.is_object()) oldConfig = ov;
  580. if (nv.is_object()) newConfig = nv;
  581. if (oldConfig.is_object()||newConfig.is_object()) {
  582. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  583. }
  584. } catch (...) {} // ignore bad records
  585. free(notify);
  586. }
  587. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  588. }
  589. PQfinish(conn);
  590. conn = NULL;
  591. }
  592. void PostgreSQL::commitThread()
  593. {
  594. PGconn *conn = PQconnectdb(_path.c_str());
  595. if (PQstatus(conn) == CONNECTION_BAD) {
  596. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  597. PQfinish(conn);
  598. exit(1);
  599. }
  600. json *config = nullptr;
  601. while(_commitQueue.get(config)&(_run == 1)) {
  602. if (!config) {
  603. continue;
  604. }
  605. if (PQstatus(conn) == CONNECTION_BAD) {
  606. fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
  607. PQfinish(conn);
  608. delete config;
  609. exit(1);
  610. }
  611. try {
  612. const std::string objtype = (*config)["objtype"];
  613. if (objtype == "member") {
  614. try {
  615. std::string memberId = (*config)["id"];
  616. std::string networkId = (*config)["nwid"];
  617. std::string identity = (*config)["identity"];
  618. std::string target = "NULL";
  619. if (!(*config)["remoteTraceTarget"].is_null()) {
  620. target = (*config)["remoteTraceTarget"];
  621. }
  622. std::string caps = OSUtils::jsonDump((*config)["capabilities"], -1);
  623. std::string lastAuthTime = std::to_string((long long)(*config)["lastAuthorizedTime"]);
  624. std::string lastDeauthTime = std::to_string((long long)(*config)["lastDeauthorizedTime"]);
  625. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  626. std::string rev = std::to_string((unsigned long long)(*config)["revision"]);
  627. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  628. std::string vmajor = std::to_string((int)(*config)["vMajor"]);
  629. std::string vminor = std::to_string((int)(*config)["vMinor"]);
  630. std::string vrev = std::to_string((int)(*config)["vRev"]);
  631. std::string vproto = std::to_string((int)(*config)["vProto"]);
  632. const char *values[19] = {
  633. memberId.c_str(),
  634. networkId.c_str(),
  635. ((*config)["activeBridge"] ? "true" : "false"),
  636. ((*config)["authorized"] ? "true" : "false"),
  637. caps.c_str(),
  638. identity.c_str(),
  639. lastAuthTime.c_str(),
  640. lastDeauthTime.c_str(),
  641. ((*config)["noAutoAssignIps"] ? "true" : "false"),
  642. rtraceLevel.c_str(),
  643. (target == "NULL") ? NULL : target.c_str(),
  644. rev.c_str(),
  645. tags.c_str(),
  646. vmajor.c_str(),
  647. vminor.c_str(),
  648. vrev.c_str(),
  649. vproto.c_str()
  650. };
  651. PGresult *res = PQexecParams(conn,
  652. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  653. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  654. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  655. "VALUES ($1, $2, $3, $4, $5, $6, "
  656. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  657. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  658. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  659. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  660. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  661. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  662. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  663. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  664. 17,
  665. NULL,
  666. values,
  667. NULL,
  668. NULL,
  669. 0);
  670. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  671. fprintf(stderr, "ERROR: Error updating member: %s\n", PQresultErrorMessage(res));
  672. fprintf(stderr, "%s", OSUtils::jsonDump(*config, 2).c_str());
  673. PQclear(res);
  674. delete config;
  675. config = nullptr;
  676. continue;
  677. }
  678. PQclear(res);
  679. res = PQexec(conn, "BEGIN");
  680. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  681. fprintf(stderr, "ERROR: Error beginning transaction: %s\n", PQresultErrorMessage(res));
  682. PQclear(res);
  683. delete config;
  684. config = nullptr;
  685. continue;
  686. }
  687. PQclear(res);
  688. const char *v2[2] = {
  689. memberId.c_str(),
  690. networkId.c_str()
  691. };
  692. res = PQexecParams(conn,
  693. "DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  694. 2,
  695. NULL,
  696. v2,
  697. NULL,
  698. NULL,
  699. 0);
  700. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  701. fprintf(stderr, "ERROR: Error updating IP address assignments: %s\n", PQresultErrorMessage(res));
  702. PQclear(res);
  703. PQclear(PQexec(conn, "ROLLBACK"));;
  704. delete config;
  705. config = nullptr;
  706. continue;
  707. }
  708. PQclear(res);
  709. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  710. std::string addr = *i;
  711. const char *v3[3] = {
  712. memberId.c_str(),
  713. networkId.c_str(),
  714. addr.c_str()
  715. };
  716. res = PQexecParams(conn,
  717. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3)",
  718. 3,
  719. NULL,
  720. v3,
  721. NULL,
  722. NULL,
  723. 0);
  724. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  725. fprintf(stderr, "ERROR: Error setting IP addresses for member: %s\n", PQresultErrorMessage(res));
  726. PQclear(res);
  727. PQclear(PQexec(conn, "ROLLBACK"));
  728. continue;
  729. }
  730. }
  731. res = PQexec(conn, "COMMIT");
  732. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  733. fprintf(stderr, "ERROR: Error committing ip address data: %s\n", PQresultErrorMessage(res));
  734. }
  735. PQclear(res);
  736. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  737. const uint64_t memberidInt = OSUtils::jsonIntHex((*config)["id"], 0ULL);
  738. if (nwidInt && memberidInt) {
  739. nlohmann::json nwOrig;
  740. nlohmann::json memOrig;
  741. nlohmann::json memNew(*config);
  742. get(nwidInt, nwOrig, memberidInt, memOrig);
  743. _memberChanged(memOrig, memNew, (this->_ready>=2));
  744. } else {
  745. fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %lu-%lu\n", nwidInt, memberidInt);
  746. }
  747. } catch (std::exception &e) {
  748. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  749. }
  750. } else if (objtype == "network") {
  751. try {
  752. std::string id = (*config)["id"];
  753. std::string controllerId = _myAddressStr.c_str();
  754. std::string name = (*config)["name"];
  755. std::string remoteTraceTarget("NULL");
  756. if (!(*config)["remoteTraceTarget"].is_null()) {
  757. remoteTraceTarget = (*config)["remoteTraceTarget"];
  758. }
  759. std::string rulesSource = (*config)["rulesSource"];
  760. std::string caps = OSUtils::jsonDump((*config)["capabilitles"], -1);
  761. std::string now = std::to_string(OSUtils::now());
  762. std::string mtu = std::to_string((int)(*config)["mtu"]);
  763. std::string mcastLimit = std::to_string((int)(*config)["multicastLimit"]);
  764. std::string rtraceLevel = std::to_string((int)(*config)["remoteTraceLevel"]);
  765. std::string rules = OSUtils::jsonDump((*config)["rules"], -1);
  766. std::string tags = OSUtils::jsonDump((*config)["tags"], -1);
  767. std::string v4mode = OSUtils::jsonDump((*config)["v4AssignMode"],-1);
  768. std::string v6mode = OSUtils::jsonDump((*config)["v6AssignMode"], -1);
  769. bool enableBroadcast = (*config)["enableBroadcast"];
  770. bool isPrivate = (*config)["private"];
  771. const char *values[16] = {
  772. id.c_str(),
  773. controllerId.c_str(),
  774. caps.c_str(),
  775. enableBroadcast ? "true" : "false",
  776. now.c_str(),
  777. mtu.c_str(),
  778. mcastLimit.c_str(),
  779. name.c_str(),
  780. isPrivate ? "true" : "false",
  781. rtraceLevel.c_str(),
  782. (remoteTraceTarget == "NULL" ? NULL : remoteTraceTarget.c_str()),
  783. rules.c_str(),
  784. rulesSource.c_str(),
  785. tags.c_str(),
  786. v4mode.c_str(),
  787. v6mode.c_str(),
  788. };
  789. PGresult *res = PQexecParams(conn,
  790. "UPDATE ztc_network SET controller_id = $2, capabilities = $3, enable_broadcast = $4, "
  791. "last_updated = $5, mtu = $6, multicast_limit = $7, name = $8, private = $9, "
  792. "remote_trace_level = $10, remote_trace_target = $11, rules = $12, rules_source = $13, "
  793. "tags = $14, v4_assign_mode = $15, v6_assign_mode = $16 "
  794. "WHERE id = $1",
  795. 16,
  796. NULL,
  797. values,
  798. NULL,
  799. NULL,
  800. 0);
  801. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  802. fprintf(stderr, "ERROR: Error updating network record: %s\n", PQresultErrorMessage(res));
  803. PQclear(res);
  804. delete config;
  805. config = nullptr;
  806. continue;
  807. }
  808. PQclear(res);
  809. res = PQexec(conn, "BEGIN");
  810. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  811. fprintf(stderr, "ERROR: Error beginnning transaction: %s\n", PQresultErrorMessage(res));
  812. PQclear(res);
  813. delete config;
  814. config = nullptr;
  815. continue;
  816. }
  817. PQclear(res);
  818. const char *params[1] = {
  819. id.c_str()
  820. };
  821. res = PQexecParams(conn,
  822. "DELETE FROM ztc_network_assignment_pool WHERE network_id = $1",
  823. 1,
  824. NULL,
  825. params,
  826. NULL,
  827. NULL,
  828. 0);
  829. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  830. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  831. PQclear(res);
  832. PQclear(PQexec(conn, "ROLLBACK"));
  833. delete config;
  834. config = nullptr;
  835. continue;
  836. }
  837. PQclear(res);
  838. auto pool = (*config)["ipAssignmentPools"];
  839. bool err = false;
  840. for (auto i = pool.begin(); i != pool.end(); ++i) {
  841. std::string start = (*i)["ipRangeStart"];
  842. std::string end = (*i)["ipRangeEnd"];
  843. const char *p[3] = {
  844. id.c_str(),
  845. start.c_str(),
  846. end.c_str()
  847. };
  848. res = PQexecParams(conn,
  849. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  850. "VALUES ($1, $2, $3)",
  851. 3,
  852. NULL,
  853. p,
  854. NULL,
  855. NULL,
  856. 0);
  857. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  858. fprintf(stderr, "ERROR: Error updating assignment pool: %s\n", PQresultErrorMessage(res));
  859. PQclear(res);
  860. err = true;
  861. break;
  862. }
  863. PQclear(res);
  864. }
  865. if (err) {
  866. PQclear(PQexec(conn, "ROLLBACK"));
  867. delete config;
  868. config = nullptr;
  869. continue;
  870. }
  871. res = PQexecParams(conn,
  872. "DELETE FROM ztc_network_route WHERE network_id = $1",
  873. 1,
  874. NULL,
  875. params,
  876. NULL,
  877. NULL,
  878. 0);
  879. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  880. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  881. PQclear(res);
  882. PQclear(PQexec(conn, "ROLLBACK"));
  883. delete config;
  884. config = nullptr;
  885. continue;
  886. }
  887. auto routes = (*config)["routes"];
  888. err = false;
  889. for (auto i = routes.begin(); i != routes.end(); ++i) {
  890. std::string t = (*i)["target"];
  891. std::vector<std::string> target;
  892. std::istringstream f(t);
  893. std::string s;
  894. while(std::getline(f, s, '/')) {
  895. target.push_back(s);
  896. }
  897. if (target.empty() || target.size() != 2) {
  898. continue;
  899. }
  900. std::string targetAddr = target[0];
  901. std::string targetBits = target[1];
  902. std::string via = "NULL";
  903. if (!(*i)["via"].is_null()) {
  904. via = (*i)["via"];
  905. }
  906. const char *p[4] = {
  907. id.c_str(),
  908. targetAddr.c_str(),
  909. targetBits.c_str(),
  910. (via == "NULL" ? NULL : via.c_str()),
  911. };
  912. res = PQexecParams(conn,
  913. "INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  914. 4,
  915. NULL,
  916. p,
  917. NULL,
  918. NULL,
  919. 0);
  920. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  921. fprintf(stderr, "ERROR: Error updating routes: %s\n", PQresultErrorMessage(res));
  922. PQclear(res);
  923. err = true;
  924. break;
  925. }
  926. PQclear(res);
  927. }
  928. if (err) {
  929. PQclear(PQexec(conn, "ROLLBACK"));
  930. delete config;
  931. config = nullptr;
  932. continue;
  933. }
  934. res = PQexec(conn, "COMMIT");
  935. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  936. fprintf(stderr, "ERROR: Error committing network update: %s\n", PQresultErrorMessage(res));
  937. }
  938. PQclear(res);
  939. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  940. if (nwidInt) {
  941. nlohmann::json nwOrig;
  942. nlohmann::json nwNew(*config);
  943. get(nwidInt, nwOrig);
  944. _networkChanged(nwOrig, nwNew, true);
  945. } else {
  946. fprintf(stderr, "Can't notify network changed: %lu\n", nwidInt);
  947. }
  948. } catch (std::exception &e) {
  949. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  950. }
  951. } else if (objtype == "trace") {
  952. fprintf(stderr, "ERROR: Trace not yet implemented");
  953. } else if (objtype == "_delete_network") {
  954. try {
  955. std::string networkId = (*config)["nwid"];
  956. const char *values[1] = {
  957. networkId.c_str()
  958. };
  959. PGresult * res = PQexecParams(conn,
  960. "UPDATE ztc_network SET deleted = true WHERE id = $1",
  961. 1,
  962. NULL,
  963. values,
  964. NULL,
  965. NULL,
  966. 0);
  967. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  968. fprintf(stderr, "ERROR: Error deleting network: %s\n", PQresultErrorMessage(res));
  969. }
  970. PQclear(res);
  971. } catch (std::exception &e) {
  972. fprintf(stderr, "ERROR: Error deleting network: %s\n", e.what());
  973. }
  974. } else if (objtype == "_delete_member") {
  975. try {
  976. std::string memberId = (*config)["id"];
  977. std::string networkId = (*config)["nwid"];
  978. const char *values[2] = {
  979. memberId.c_str(),
  980. networkId.c_str()
  981. };
  982. PGresult *res = PQexecParams(conn,
  983. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  984. 2,
  985. NULL,
  986. values,
  987. NULL,
  988. NULL,
  989. 0);
  990. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  991. fprintf(stderr, "ERROR: Error deleting member: %s\n", PQresultErrorMessage(res));
  992. }
  993. PQclear(res);
  994. } catch (std::exception &e) {
  995. fprintf(stderr, "ERROR: Error deleting member: %s\n", e.what());
  996. }
  997. } else {
  998. fprintf(stderr, "ERROR: unknown objtype");
  999. }
  1000. } catch (std::exception &e) {
  1001. fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
  1002. }
  1003. delete config;
  1004. config = nullptr;
  1005. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1006. }
  1007. PQfinish(conn);
  1008. }
  1009. void PostgreSQL::onlineNotificationThread()
  1010. {
  1011. PGconn *conn = PQconnectdb(_path.c_str());
  1012. if (PQstatus(conn) == CONNECTION_BAD) {
  1013. fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
  1014. PQfinish(conn);
  1015. exit(1);
  1016. }
  1017. _connected = 1;
  1018. int64_t lastUpdatedNetworkStatus = 0;
  1019. std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative;
  1020. while (_run == 1) {
  1021. if (PQstatus(conn) != CONNECTION_OK) {
  1022. fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres.");
  1023. exit(-1);
  1024. }
  1025. // map used to send notifications to front end
  1026. std::unordered_map<std::string, std::vector<std::string>> updateMap;
  1027. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1028. {
  1029. std::lock_guard<std::mutex> l(_lastOnline_l);
  1030. lastOnline.swap(_lastOnline);
  1031. }
  1032. PGresult *res = NULL;
  1033. int qCount = 0;
  1034. res = PQexec(conn, "BEGIN");
  1035. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1036. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1037. PQclear(res);
  1038. exit(1);
  1039. }
  1040. PQclear(res);
  1041. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1042. uint64_t nwid_i = i->first.first;
  1043. char nwidTmp[64];
  1044. char memTmp[64];
  1045. char ipTmp[64];
  1046. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1047. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  1048. auto found = _networks.find(nwid_i);
  1049. if (found == _networks.end()) {
  1050. continue; // skip members trying to join non-existant networks
  1051. }
  1052. lastOnlineCumulative[i->first] = i->second.first;
  1053. std::string networkId(nwidTmp);
  1054. std::string memberId(memTmp);
  1055. std::vector<std::string> &members = updateMap[networkId];
  1056. members.push_back(memberId);
  1057. int64_t ts = i->second.first;
  1058. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1059. std::string timestamp = std::to_string(ts);
  1060. const char *values[4] = {
  1061. networkId.c_str(),
  1062. memberId.c_str(),
  1063. (ipAddr.empty() ? NULL : ipAddr.c_str()),
  1064. timestamp.c_str(),
  1065. };
  1066. res = PQexecParams(conn,
  1067. "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ($1, $2, $3, TO_TIMESTAMP($4::double precision/1000)) "
  1068. "ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated",
  1069. 4, // number of parameters
  1070. NULL, // oid field. ignore
  1071. values, // values for substitution
  1072. NULL, // lengths in bytes of each value
  1073. NULL,
  1074. 0);
  1075. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1076. fprintf(stderr, "Error on Member Status upsert: %s\n", PQresultErrorMessage(res));
  1077. PQclear(res);
  1078. PQclear(PQexec(conn, "ROLLBACK"));
  1079. continue;
  1080. }
  1081. PQclear(res);
  1082. if ((++qCount) == 1024) {
  1083. res = PQexec(conn, "COMMIT");
  1084. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1085. fprintf(stderr, "ERROR: Error on commit (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1086. PQclear(res);
  1087. PQclear(PQexec(conn, "ROLLBACK"));
  1088. exit(1);
  1089. }
  1090. PQclear(res);
  1091. res = PQexec(conn, "BEGIN");
  1092. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1093. fprintf(stderr, "ERROR: Error on BEGIN (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1094. PQclear(res);
  1095. exit(1);
  1096. }
  1097. PQclear(res);
  1098. qCount = 0;
  1099. }
  1100. }
  1101. res = PQexec(conn, "COMMIT");
  1102. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1103. fprintf(stderr, "ERROR: Error on commit (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1104. PQclear(res);
  1105. PQclear(PQexec(conn, "ROLLBACK"));
  1106. exit(1);
  1107. }
  1108. PQclear(res);
  1109. const int64_t now = OSUtils::now();
  1110. if ((now - lastUpdatedNetworkStatus) > 10000) {
  1111. lastUpdatedNetworkStatus = now;
  1112. std::vector<std::pair<uint64_t, std::shared_ptr<_Network>>> networks;
  1113. {
  1114. std::lock_guard<std::mutex> l(_networks_l);
  1115. for (auto i = _networks.begin(); i != _networks.end(); ++i) {
  1116. networks.push_back(*i);
  1117. }
  1118. }
  1119. int nCount = 0;
  1120. res = PQexec(conn, "BEGIN");
  1121. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1122. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1123. PQclear(res);
  1124. exit(1);
  1125. }
  1126. PQclear(res);
  1127. for (auto i = networks.begin(); i != networks.end(); ++i) {
  1128. char tmp[64];
  1129. Utils::hex(i->first, tmp);
  1130. std::string networkId(tmp);
  1131. std::vector<std::string> &_notUsed = updateMap[networkId];
  1132. (void)_notUsed;
  1133. uint64_t authMemberCount = 0;
  1134. uint64_t totalMemberCount = 0;
  1135. uint64_t onlineMemberCount = 0;
  1136. uint64_t bridgeCount = 0;
  1137. uint64_t ts = now;
  1138. {
  1139. std::lock_guard<std::mutex> l2(i->second->lock);
  1140. authMemberCount = i->second->authorizedMembers.size();
  1141. totalMemberCount = i->second->members.size();
  1142. bridgeCount = i->second->activeBridgeMembers.size();
  1143. for (auto m=i->second->members.begin(); m != i->second->members.end(); ++m) {
  1144. auto lo = lastOnlineCumulative.find(std::pair<uint64_t,uint64_t>(i->first, m->first));
  1145. if (lo != lastOnlineCumulative.end()) {
  1146. if ((now - lo->second) <= (ZT_NETWORK_AUTOCONF_DELAY * 2)) {
  1147. ++onlineMemberCount;
  1148. } else {
  1149. lastOnlineCumulative.erase(lo);
  1150. }
  1151. }
  1152. }
  1153. }
  1154. std::string bc = std::to_string(bridgeCount);
  1155. std::string amc = std::to_string(authMemberCount);
  1156. std::string omc = std::to_string(onlineMemberCount);
  1157. std::string tmc = std::to_string(totalMemberCount);
  1158. std::string timestamp = std::to_string(ts);
  1159. const char *values[6] = {
  1160. networkId.c_str(),
  1161. bc.c_str(),
  1162. amc.c_str(),
  1163. omc.c_str(),
  1164. tmc.c_str(),
  1165. timestamp.c_str()
  1166. };
  1167. res = PQexecParams(conn, "INSERT INTO ztc_network_status (network_id, bridge_count, authorized_member_count, "
  1168. "online_member_count, total_member_count, last_modified) VALUES ($1, $2, $3, $4, $5, TO_TIMESTAMP($6::double precision/1000)) "
  1169. "ON CONFLICT (network_id) DO UPDATE SET bridge_count = EXCLUDED.bridge_count, "
  1170. "authorized_member_count = EXCLUDED.authorized_member_count, online_member_count = EXCLUDED.online_member_count, "
  1171. "total_member_count = EXCLUDED.total_member_count, last_modified = EXCLUDED.last_modified",
  1172. 6,
  1173. NULL,
  1174. values,
  1175. NULL,
  1176. NULL,
  1177. 0);
  1178. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1179. fprintf(stderr, "ERROR: Error on Network Status upsert (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1180. PQclear(res);
  1181. PQclear(PQexec(conn, "ROLLBACK"));
  1182. exit(1);
  1183. }
  1184. if ((++nCount) == 1024) {
  1185. res = PQexec(conn, "COMMIT");
  1186. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1187. fprintf(stderr, "ERROR: Error on COMMIT (onlineNotificationThread): %s\n" , PQresultErrorMessage(res));
  1188. PQclear(res);
  1189. PQclear(PQexec(conn, "ROLLBACK"));
  1190. exit(1);
  1191. }
  1192. res = PQexec(conn, "BEGIN");
  1193. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1194. fprintf(stderr, "ERROR: Error on BEGIN command (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1195. PQclear(res);
  1196. exit(1);
  1197. }
  1198. nCount = 0;
  1199. }
  1200. }
  1201. res = PQexec(conn, "COMMIT");
  1202. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1203. fprintf(stderr, "ERROR: Error on COMMIT (onlineNotificationThread): %s\n", PQresultErrorMessage(res));
  1204. PQclear(res);
  1205. PQclear(PQexec(conn, "ROLLBACK"));
  1206. exit(1);
  1207. }
  1208. }
  1209. for (auto it = updateMap.begin(); it != updateMap.end(); ++it) {
  1210. std::string networkId = it->first;
  1211. std::vector<std::string> members = it->second;
  1212. std::stringstream queryBuilder;
  1213. std::string membersStr = ::join(members, ",");
  1214. queryBuilder << "NOTIFY controller, '" << networkId << ":" << membersStr << "'";
  1215. std::string query = queryBuilder.str();
  1216. PGresult *res = PQexec(conn,query.c_str());
  1217. if (PQresultStatus(res) != PGRES_COMMAND_OK) {
  1218. fprintf(stderr, "ERROR: Error sending NOTIFY: %s\n", PQresultErrorMessage(res));
  1219. }
  1220. PQclear(res);
  1221. }
  1222. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  1223. }
  1224. PQfinish(conn);
  1225. }
  1226. #endif //ZT_CONTROLLER_USE_LIBPQ