RethinkDB.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 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_RETHINKDB
  19. #include "RethinkDB.hpp"
  20. #include "EmbeddedNetworkController.hpp"
  21. #include <chrono>
  22. #include <algorithm>
  23. #include <stdexcept>
  24. #include "../ext/librethinkdbxx/build/include/rethinkdb.h"
  25. namespace R = RethinkDB;
  26. using json = nlohmann::json;
  27. namespace ZeroTier {
  28. RethinkDB::RethinkDB(EmbeddedNetworkController *const nc,const Address &myAddress,const char *path) :
  29. _controller(nc),
  30. _myAddress(myAddress),
  31. _ready(2), // two tables need to be synchronized before we're ready, so this is ready when it reaches 0
  32. _run(1),
  33. _waitNoticePrinted(false)
  34. {
  35. std::vector<std::string> ps(OSUtils::split(path,":","",""));
  36. if ((ps.size() < 4)||(ps[0] != "rethinkdb"))
  37. throw std::runtime_error("invalid rethinkdb database url");
  38. _host = ps[1];
  39. _port = Utils::strToInt(ps[2].c_str());
  40. _db = ps[3];
  41. if (ps.size() > 4)
  42. _auth = ps[4];
  43. _readyLock.lock();
  44. {
  45. char tmp[32];
  46. _myAddress.toString(tmp);
  47. _myAddressStr = tmp;
  48. }
  49. _membersDbWatcher = std::thread([this]() {
  50. try {
  51. while (_run == 1) {
  52. try {
  53. std::unique_ptr<R::Connection> rdb(R::connect(this->_host,this->_port,this->_auth));
  54. if (rdb) {
  55. _membersDbWatcherConnection = (void *)rdb.get();
  56. auto cur = R::db(this->_db).table("Member",R::optargs("read_mode","outdated")).get_all(this->_myAddressStr,R::optargs("index","controllerId")).changes(R::optargs("squash",0.05,"include_initial",true,"include_types",true,"include_states",true)).run(*rdb);
  57. while (cur.has_next()) {
  58. if (_run != 1) break;
  59. json tmp(json::parse(cur.next().as_json()));
  60. if ((tmp["type"] == "state")&&(tmp["state"] == "ready")) {
  61. if (--this->_ready == 0) {
  62. if (_waitNoticePrinted)
  63. fprintf(stderr,"NOTICE: controller RethinkDB data download complete." ZT_EOL_S);
  64. this->_readyLock.unlock();
  65. }
  66. } else {
  67. try {
  68. json &ov = tmp["old_val"];
  69. json &nv = tmp["new_val"];
  70. if (ov.is_object()||nv.is_object()) {
  71. //if (nv.is_object()) printf("MEMBER: %s" ZT_EOL_S,nv.dump().c_str());
  72. this->_memberChanged(ov,nv);
  73. }
  74. } catch ( ... ) {} // ignore bad records
  75. }
  76. }
  77. }
  78. } catch (std::exception &e) {
  79. fprintf(stderr,"ERROR: controller RethinkDB (member change stream): %s" ZT_EOL_S,e.what());
  80. } catch (R::Error &e) {
  81. fprintf(stderr,"ERROR: controller RethinkDB (member change stream): %s" ZT_EOL_S,e.message.c_str());
  82. } catch ( ... ) {
  83. fprintf(stderr,"ERROR: controller RethinkDB (member change stream): unknown exception" ZT_EOL_S);
  84. }
  85. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  86. }
  87. } catch ( ... ) {}
  88. });
  89. _networksDbWatcher = std::thread([this]() {
  90. try {
  91. while (_run == 1) {
  92. try {
  93. std::unique_ptr<R::Connection> rdb(R::connect(this->_host,this->_port,this->_auth));
  94. if (rdb) {
  95. _networksDbWatcherConnection = (void *)rdb.get();
  96. auto cur = R::db(this->_db).table("Network",R::optargs("read_mode","outdated")).get_all(this->_myAddressStr,R::optargs("index","controllerId")).changes(R::optargs("squash",0.05,"include_initial",true,"include_types",true,"include_states",true)).run(*rdb);
  97. while (cur.has_next()) {
  98. if (_run != 1) break;
  99. json tmp(json::parse(cur.next().as_json()));
  100. if ((tmp["type"] == "state")&&(tmp["state"] == "ready")) {
  101. if (--this->_ready == 0) {
  102. if (_waitNoticePrinted)
  103. fprintf(stderr,"NOTICE: controller RethinkDB data download complete." ZT_EOL_S);
  104. this->_readyLock.unlock();
  105. }
  106. } else {
  107. try {
  108. json &ov = tmp["old_val"];
  109. json &nv = tmp["new_val"];
  110. if (ov.is_object()||nv.is_object()) {
  111. //if (nv.is_object()) printf("NETWORK: %s" ZT_EOL_S,nv.dump().c_str());
  112. this->_networkChanged(ov,nv);
  113. }
  114. } catch ( ... ) {} // ignore bad records
  115. }
  116. }
  117. }
  118. } catch (std::exception &e) {
  119. fprintf(stderr,"ERROR: controller RethinkDB (network change stream): %s" ZT_EOL_S,e.what());
  120. } catch (R::Error &e) {
  121. fprintf(stderr,"ERROR: controller RethinkDB (network change stream): %s" ZT_EOL_S,e.message.c_str());
  122. } catch ( ... ) {
  123. fprintf(stderr,"ERROR: controller RethinkDB (network change stream): unknown exception" ZT_EOL_S);
  124. }
  125. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  126. }
  127. } catch ( ... ) {}
  128. });
  129. for(int t=0;t<ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS;++t) {
  130. _commitThread[t] = std::thread([this]() {
  131. try {
  132. std::unique_ptr<R::Connection> rdb;
  133. nlohmann::json *config = (nlohmann::json *)0;
  134. while ((this->_commitQueue.get(config))&&(_run == 1)) {
  135. if (!config)
  136. continue;
  137. json record;
  138. const std::string objtype = (*config)["objtype"];
  139. const char *table;
  140. std::string deleteId;
  141. try {
  142. if (objtype == "member") {
  143. const std::string nwid = (*config)["nwid"];
  144. const std::string id = (*config)["id"];
  145. record["id"] = nwid + "-" + id;
  146. record["controllerId"] = this->_myAddressStr;
  147. record["networkId"] = nwid;
  148. record["nodeId"] = id;
  149. record["config"] = *config;
  150. table = "Member";
  151. } else if (objtype == "network") {
  152. const std::string id = (*config)["id"];
  153. record["id"] = id;
  154. record["controllerId"] = this->_myAddressStr;
  155. record["config"] = *config;
  156. table = "Network";
  157. } else if (objtype == "delete_network") {
  158. deleteId = (*config)["id"];
  159. table = "Network";
  160. } else if (objtype == "delete_member") {
  161. deleteId = (*config)["nwid"];
  162. deleteId.push_back('-');
  163. const std::string tmp = (*config)["id"];
  164. deleteId.append(tmp);
  165. table = "Member";
  166. } else if (objtype == "trace") {
  167. record = *config;
  168. table = "RemoteTrace";
  169. } else {
  170. delete config;
  171. continue;
  172. }
  173. delete config;
  174. } catch ( ... ) {
  175. delete config;
  176. continue;
  177. }
  178. while (_run == 1) {
  179. try {
  180. if (!rdb)
  181. rdb = R::connect(this->_host,this->_port,this->_auth);
  182. if (rdb) {
  183. if (deleteId.length() > 0) {
  184. //printf("DELETE: %s" ZT_EOL_S,deleteId.c_str());
  185. R::db(this->_db).table(table).get(deleteId).delete_().run(*rdb);
  186. } else {
  187. //printf("UPSERT: %s" ZT_EOL_S,record.dump().c_str());
  188. R::db(this->_db).table(table).insert(R::Datum::from_json(record.dump()),R::optargs("conflict","update","return_changes",false)).run(*rdb);
  189. }
  190. break;
  191. } else {
  192. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): connect failed (will retry)" ZT_EOL_S);
  193. }
  194. } catch (std::exception &e) {
  195. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): %s" ZT_EOL_S,e.what());
  196. rdb.reset();
  197. } catch (R::Error &e) {
  198. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): %s" ZT_EOL_S,e.message.c_str());
  199. rdb.reset();
  200. } catch ( ... ) {
  201. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): unknown exception" ZT_EOL_S);
  202. rdb.reset();
  203. }
  204. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  205. }
  206. }
  207. } catch ( ... ) {}
  208. });
  209. }
  210. _heartbeatThread = std::thread([this]() {
  211. try {
  212. char tmp[1024];
  213. std::unique_ptr<R::Connection> rdb;
  214. while (_run == 1) {
  215. try {
  216. if (!rdb)
  217. rdb = R::connect(this->_host,this->_port,this->_auth);
  218. if (rdb) {
  219. OSUtils::ztsnprintf(tmp,sizeof(tmp),"{\"id\":\"%s\",\"lastAlive\":%lld}",this->_myAddressStr.c_str(),(long long)OSUtils::now());
  220. //printf("HEARTBEAT: %s" ZT_EOL_S,tmp);
  221. R::db(this->_db).table("Controller").update(R::Datum::from_json(tmp)).run(*rdb);
  222. }
  223. } catch ( ... ) {
  224. rdb.reset();
  225. }
  226. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  227. }
  228. } catch ( ... ) {}
  229. });
  230. }
  231. RethinkDB::~RethinkDB()
  232. {
  233. _run = 0;
  234. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  235. _commitQueue.stop();
  236. for(int t=0;t<ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS;++t)
  237. _commitThread[t].join();
  238. if (_membersDbWatcherConnection)
  239. ((R::Connection *)_membersDbWatcherConnection)->close();
  240. if (_networksDbWatcherConnection)
  241. ((R::Connection *)_networksDbWatcherConnection)->close();
  242. _membersDbWatcher.join();
  243. _networksDbWatcher.join();
  244. _heartbeatThread.join();
  245. }
  246. bool RethinkDB::get(const uint64_t networkId,nlohmann::json &network)
  247. {
  248. waitForReady();
  249. std::shared_ptr<_Network> nw;
  250. {
  251. std::lock_guard<std::mutex> l(_networks_l);
  252. auto nwi = _networks.find(networkId);
  253. if (nwi == _networks.end())
  254. return false;
  255. nw = nwi->second;
  256. }
  257. {
  258. std::lock_guard<std::mutex> l2(nw->lock);
  259. network = nw->config;
  260. }
  261. return true;
  262. }
  263. bool RethinkDB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member)
  264. {
  265. waitForReady();
  266. std::shared_ptr<_Network> nw;
  267. {
  268. std::lock_guard<std::mutex> l(_networks_l);
  269. auto nwi = _networks.find(networkId);
  270. if (nwi == _networks.end())
  271. return false;
  272. nw = nwi->second;
  273. }
  274. {
  275. std::lock_guard<std::mutex> l2(nw->lock);
  276. network = nw->config;
  277. auto m = nw->members.find(memberId);
  278. if (m == nw->members.end())
  279. return false;
  280. member = m->second;
  281. }
  282. return true;
  283. }
  284. bool RethinkDB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,NetworkSummaryInfo &info)
  285. {
  286. waitForReady();
  287. std::shared_ptr<_Network> nw;
  288. {
  289. std::lock_guard<std::mutex> l(_networks_l);
  290. auto nwi = _networks.find(networkId);
  291. if (nwi == _networks.end())
  292. return false;
  293. nw = nwi->second;
  294. }
  295. {
  296. std::lock_guard<std::mutex> l2(nw->lock);
  297. network = nw->config;
  298. _fillSummaryInfo(nw,info);
  299. auto m = nw->members.find(memberId);
  300. if (m == nw->members.end())
  301. return false;
  302. member = m->second;
  303. }
  304. return true;
  305. }
  306. bool RethinkDB::get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members)
  307. {
  308. waitForReady();
  309. std::shared_ptr<_Network> nw;
  310. {
  311. std::lock_guard<std::mutex> l(_networks_l);
  312. auto nwi = _networks.find(networkId);
  313. if (nwi == _networks.end())
  314. return false;
  315. nw = nwi->second;
  316. }
  317. {
  318. std::lock_guard<std::mutex> l2(nw->lock);
  319. network = nw->config;
  320. for(auto m=nw->members.begin();m!=nw->members.end();++m)
  321. members.push_back(m->second);
  322. }
  323. return true;
  324. }
  325. bool RethinkDB::summary(const uint64_t networkId,NetworkSummaryInfo &info)
  326. {
  327. waitForReady();
  328. std::shared_ptr<_Network> nw;
  329. {
  330. std::lock_guard<std::mutex> l(_networks_l);
  331. auto nwi = _networks.find(networkId);
  332. if (nwi == _networks.end())
  333. return false;
  334. nw = nwi->second;
  335. }
  336. {
  337. std::lock_guard<std::mutex> l2(nw->lock);
  338. _fillSummaryInfo(nw,info);
  339. }
  340. return true;
  341. }
  342. void RethinkDB::networks(std::vector<uint64_t> &networks)
  343. {
  344. waitForReady();
  345. std::lock_guard<std::mutex> l(_networks_l);
  346. networks.reserve(_networks.size() + 1);
  347. for(auto n=_networks.begin();n!=_networks.end();++n)
  348. networks.push_back(n->first);
  349. }
  350. void RethinkDB::save(const nlohmann::json &record)
  351. {
  352. waitForReady();
  353. _commitQueue.post(new nlohmann::json(record));
  354. }
  355. void RethinkDB::eraseNetwork(const uint64_t networkId)
  356. {
  357. char tmp2[24];
  358. waitForReady();
  359. Utils::hex(networkId,tmp2);
  360. json *tmp = new json();
  361. (*tmp)["id"] = tmp2;
  362. (*tmp)["objtype"] = "delete_network"; // pseudo-type, tells thread to delete network
  363. _commitQueue.post(tmp);
  364. }
  365. void RethinkDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  366. {
  367. char tmp2[24];
  368. json *tmp = new json();
  369. waitForReady();
  370. Utils::hex(networkId,tmp2);
  371. (*tmp)["nwid"] = tmp2;
  372. Utils::hex10(memberId,tmp2);
  373. (*tmp)["id"] = tmp2;
  374. (*tmp)["objtype"] = "delete_member"; // pseudo-type, tells thread to delete network
  375. _commitQueue.post(tmp);
  376. }
  377. void RethinkDB::_memberChanged(nlohmann::json &old,nlohmann::json &member)
  378. {
  379. uint64_t memberId = 0;
  380. uint64_t networkId = 0;
  381. bool isAuth = false;
  382. bool wasAuth = false;
  383. std::shared_ptr<_Network> nw;
  384. if (old.is_object()) {
  385. json &config = old["config"];
  386. if (config.is_object()) {
  387. memberId = OSUtils::jsonIntHex(config["id"],0ULL);
  388. networkId = OSUtils::jsonIntHex(config["nwid"],0ULL);
  389. if ((memberId)&&(networkId)) {
  390. {
  391. std::lock_guard<std::mutex> l(_networks_l);
  392. auto nw2 = _networks.find(networkId);
  393. if (nw2 != _networks.end())
  394. nw = nw2->second;
  395. }
  396. if (nw) {
  397. std::lock_guard<std::mutex> l(nw->lock);
  398. if (OSUtils::jsonBool(config["activeBridge"],false))
  399. nw->activeBridgeMembers.erase(memberId);
  400. wasAuth = OSUtils::jsonBool(config["authorized"],false);
  401. if (wasAuth)
  402. nw->authorizedMembers.erase(memberId);
  403. json &ips = config["ipAssignments"];
  404. if (ips.is_array()) {
  405. for(unsigned long i=0;i<ips.size();++i) {
  406. json &ipj = ips[i];
  407. if (ipj.is_string()) {
  408. const std::string ips = ipj;
  409. InetAddress ipa(ips.c_str());
  410. ipa.setPort(0);
  411. nw->allocatedIps.erase(ipa);
  412. }
  413. }
  414. }
  415. }
  416. }
  417. }
  418. }
  419. if (member.is_object()) {
  420. json &config = member["config"];
  421. if (config.is_object()) {
  422. if (!nw) {
  423. memberId = OSUtils::jsonIntHex(config["id"],0ULL);
  424. networkId = OSUtils::jsonIntHex(config["nwid"],0ULL);
  425. if ((!memberId)||(!networkId))
  426. return;
  427. std::lock_guard<std::mutex> l(_networks_l);
  428. std::shared_ptr<_Network> &nw2 = _networks[networkId];
  429. if (!nw2)
  430. nw2.reset(new _Network);
  431. nw = nw2;
  432. }
  433. {
  434. std::lock_guard<std::mutex> l(nw->lock);
  435. nw->members[memberId] = config;
  436. if (OSUtils::jsonBool(config["activeBridge"],false))
  437. nw->activeBridgeMembers.insert(memberId);
  438. isAuth = OSUtils::jsonBool(config["authorized"],false);
  439. if (isAuth)
  440. nw->authorizedMembers.insert(memberId);
  441. json &ips = config["ipAssignments"];
  442. if (ips.is_array()) {
  443. for(unsigned long i=0;i<ips.size();++i) {
  444. json &ipj = ips[i];
  445. if (ipj.is_string()) {
  446. const std::string ips = ipj;
  447. InetAddress ipa(ips.c_str());
  448. ipa.setPort(0);
  449. nw->allocatedIps.insert(ipa);
  450. }
  451. }
  452. }
  453. if (!isAuth) {
  454. const int64_t ldt = (int64_t)OSUtils::jsonInt(config["lastDeauthorizedTime"],0ULL);
  455. if (ldt > nw->mostRecentDeauthTime)
  456. nw->mostRecentDeauthTime = ldt;
  457. }
  458. }
  459. _controller->onNetworkMemberUpdate(networkId,memberId);
  460. }
  461. } else if (memberId) {
  462. if (nw) {
  463. std::lock_guard<std::mutex> l(nw->lock);
  464. nw->members.erase(memberId);
  465. }
  466. if (networkId) {
  467. std::lock_guard<std::mutex> l(_networks_l);
  468. auto er = _networkByMember.equal_range(memberId);
  469. for(auto i=er.first;i!=er.second;++i) {
  470. if (i->second == networkId) {
  471. _networkByMember.erase(i);
  472. break;
  473. }
  474. }
  475. }
  476. }
  477. if ((wasAuth)&&(!isAuth)&&(networkId)&&(memberId))
  478. _controller->onNetworkMemberDeauthorize(networkId,memberId);
  479. }
  480. void RethinkDB::_networkChanged(nlohmann::json &old,nlohmann::json &network)
  481. {
  482. if (network.is_object()) {
  483. json &config = network["config"];
  484. if (config.is_object()) {
  485. const std::string ids = config["id"];
  486. const uint64_t id = Utils::hexStrToU64(ids.c_str());
  487. if (id) {
  488. std::shared_ptr<_Network> nw;
  489. {
  490. std::lock_guard<std::mutex> l(_networks_l);
  491. std::shared_ptr<_Network> &nw2 = _networks[id];
  492. if (!nw2)
  493. nw2.reset(new _Network);
  494. nw = nw2;
  495. }
  496. {
  497. std::lock_guard<std::mutex> l2(nw->lock);
  498. nw->config = config;
  499. }
  500. _controller->onNetworkUpdate(id);
  501. }
  502. }
  503. } else if (old.is_object()) {
  504. const std::string ids = old["id"];
  505. const uint64_t id = Utils::hexStrToU64(ids.c_str());
  506. if (id) {
  507. std::lock_guard<std::mutex> l(_networks_l);
  508. _networks.erase(id);
  509. }
  510. }
  511. }
  512. } // namespace ZeroTier
  513. #endif // ZT_CONTROLLER_USE_RETHINKDB