RethinkDB.cpp 15 KB

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