PostgreSQL.cpp 43 KB

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