RethinkDB.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. std::unique_ptr<nlohmann::json> config;
  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 {
  156. continue;
  157. }
  158. while (_run == 1) {
  159. try {
  160. if (!rdb)
  161. rdb = R::connect(this->_host,this->_port,this->_auth);
  162. if (rdb) {
  163. if (deleteId.length() > 0) {
  164. R::db(this->_db).table(table).get(deleteId).delete_().run(*rdb);
  165. } else {
  166. R::db(this->_db).table(table).insert(record.dump(),R::optargs("conflict","update","return_changes",false)).run(*rdb);
  167. }
  168. break;
  169. } else {
  170. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): connect failed (will retry)" ZT_EOL_S);
  171. }
  172. } catch (std::exception &e) {
  173. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): %s" ZT_EOL_S,e.what());
  174. rdb.reset();
  175. } catch (R::Error &e) {
  176. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): %s" ZT_EOL_S,e.message.c_str());
  177. rdb.reset();
  178. } catch ( ... ) {
  179. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): unknown exception" ZT_EOL_S);
  180. rdb.reset();
  181. }
  182. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  183. }
  184. }
  185. });
  186. }
  187. }
  188. RethinkDB::~RethinkDB()
  189. {
  190. // FIXME: not totally safe but will generally work, and only happens on shutdown anyway.
  191. // Would need to add some kind of 'whack it' support to librethinkdbxx to do better.
  192. _run = 0;
  193. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  194. if (_membersDbWatcherConnection)
  195. ((R::Connection *)_membersDbWatcherConnection)->close();
  196. if (_networksDbWatcherConnection)
  197. ((R::Connection *)_networksDbWatcherConnection)->close();
  198. _commitQueue.stop();
  199. for(int t=0;t<ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS;++t)
  200. _commitThread[t].join();
  201. _membersDbWatcher.join();
  202. _networksDbWatcher.join();
  203. }
  204. inline bool RethinkDB::get(const uint64_t networkId,nlohmann::json &network)
  205. {
  206. waitForReady();
  207. std::shared_ptr<_Network> nw;
  208. {
  209. std::lock_guard<std::mutex> l(_networks_l);
  210. auto nwi = _networks.find(networkId);
  211. if (nwi == _networks.end())
  212. return false;
  213. nw = nwi->second;
  214. }
  215. std::lock_guard<std::mutex> l2(nw->lock);
  216. network = nw->config;
  217. return true;
  218. }
  219. inline bool RethinkDB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member)
  220. {
  221. waitForReady();
  222. std::shared_ptr<_Network> nw;
  223. {
  224. std::lock_guard<std::mutex> l(_networks_l);
  225. auto nwi = _networks.find(networkId);
  226. if (nwi == _networks.end())
  227. return false;
  228. nw = nwi->second;
  229. }
  230. std::lock_guard<std::mutex> l2(nw->lock);
  231. auto m = nw->members.find(memberId);
  232. if (m == nw->members.end())
  233. return false;
  234. network = nw->config;
  235. member = m->second;
  236. return true;
  237. }
  238. inline bool RethinkDB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,NetworkSummaryInfo &info)
  239. {
  240. waitForReady();
  241. std::shared_ptr<_Network> nw;
  242. {
  243. std::lock_guard<std::mutex> l(_networks_l);
  244. auto nwi = _networks.find(networkId);
  245. if (nwi == _networks.end())
  246. return false;
  247. nw = nwi->second;
  248. }
  249. std::lock_guard<std::mutex> l2(nw->lock);
  250. auto m = nw->members.find(memberId);
  251. if (m == nw->members.end())
  252. return false;
  253. network = nw->config;
  254. member = m->second;
  255. _fillSummaryInfo(nw,info);
  256. return true;
  257. }
  258. inline bool RethinkDB::get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members)
  259. {
  260. waitForReady();
  261. std::shared_ptr<_Network> nw;
  262. {
  263. std::lock_guard<std::mutex> l(_networks_l);
  264. auto nwi = _networks.find(networkId);
  265. if (nwi == _networks.end())
  266. return false;
  267. nw = nwi->second;
  268. }
  269. std::lock_guard<std::mutex> l2(nw->lock);
  270. network = nw->config;
  271. for(auto m=nw->members.begin();m!=nw->members.end();++m)
  272. members.push_back(m->second);
  273. return true;
  274. }
  275. inline bool RethinkDB::summary(const uint64_t networkId,NetworkSummaryInfo &info)
  276. {
  277. waitForReady();
  278. std::shared_ptr<_Network> nw;
  279. {
  280. std::lock_guard<std::mutex> l(_networks_l);
  281. auto nwi = _networks.find(networkId);
  282. if (nwi == _networks.end())
  283. return false;
  284. nw = nwi->second;
  285. }
  286. std::lock_guard<std::mutex> l2(nw->lock);
  287. _fillSummaryInfo(nw,info);
  288. return true;
  289. }
  290. void RethinkDB::networks(std::vector<uint64_t> &networks)
  291. {
  292. waitForReady();
  293. std::lock_guard<std::mutex> l(_networks_l);
  294. networks.reserve(_networks.size() + 1);
  295. for(auto n=_networks.begin();n!=_networks.end();++n)
  296. networks.push_back(n->first);
  297. }
  298. void RethinkDB::save(const nlohmann::json &record)
  299. {
  300. waitForReady();
  301. _commitQueue.post(std::unique_ptr<nlohmann::json>(new nlohmann::json(record)));
  302. }
  303. void RethinkDB::eraseNetwork(const uint64_t networkId)
  304. {
  305. char tmp2[24];
  306. waitForReady();
  307. Utils::hex(networkId,tmp2);
  308. json tmp;
  309. tmp["id"] = tmp2;
  310. tmp["objtype"] = "delete_network"; // pseudo-type, tells thread to delete network
  311. _commitQueue.post(std::unique_ptr<nlohmann::json>(new nlohmann::json(tmp)));
  312. }
  313. void RethinkDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  314. {
  315. char tmp2[24];
  316. json tmp;
  317. waitForReady();
  318. Utils::hex(networkId,tmp2);
  319. tmp["nwid"] = tmp2;
  320. Utils::hex10(memberId,tmp2);
  321. tmp["id"] = tmp2;
  322. tmp["objtype"] = "delete_member"; // pseudo-type, tells thread to delete network
  323. _commitQueue.post(std::unique_ptr<nlohmann::json>(new nlohmann::json(tmp)));
  324. }
  325. void RethinkDB::_memberChanged(nlohmann::json &old,nlohmann::json &member)
  326. {
  327. uint64_t memberId = 0;
  328. uint64_t networkId = 0;
  329. bool isAuth = false;
  330. bool wasAuth = false;
  331. std::shared_ptr<_Network> nw;
  332. if (old.is_object()) {
  333. json &config = old["config"];
  334. if (config.is_object()) {
  335. memberId = OSUtils::jsonIntHex(config["id"],0ULL);
  336. networkId = OSUtils::jsonIntHex(config["nwid"],0ULL);
  337. if ((memberId)&&(networkId)) {
  338. {
  339. std::lock_guard<std::mutex> l(_networks_l);
  340. auto nw2 = _networks.find(networkId);
  341. if (nw2 != _networks.end())
  342. nw = nw2->second;
  343. }
  344. if (nw) {
  345. std::lock_guard<std::mutex> l(nw->lock);
  346. if (OSUtils::jsonBool(config["activeBridge"],false))
  347. nw->activeBridgeMembers.erase(memberId);
  348. wasAuth = OSUtils::jsonBool(config["authorized"],false);
  349. if (wasAuth)
  350. nw->authorizedMembers.erase(memberId);
  351. json &ips = config["ipAssignments"];
  352. if (ips.is_array()) {
  353. for(unsigned long i=0;i<ips.size();++i) {
  354. json &ipj = ips[i];
  355. if (ipj.is_string()) {
  356. const std::string ips = ipj;
  357. InetAddress ipa(ips.c_str());
  358. ipa.setPort(0);
  359. nw->allocatedIps.erase(ipa);
  360. }
  361. }
  362. }
  363. }
  364. }
  365. }
  366. }
  367. if (member.is_object()) {
  368. json &config = member["config"];
  369. if (config.is_object()) {
  370. if (!nw) {
  371. memberId = OSUtils::jsonIntHex(config["id"],0ULL);
  372. networkId = OSUtils::jsonIntHex(config["nwid"],0ULL);
  373. if ((!memberId)||(!networkId))
  374. return;
  375. std::lock_guard<std::mutex> l(_networks_l);
  376. std::shared_ptr<_Network> &nw2 = _networks[networkId];
  377. if (!nw2)
  378. nw2.reset(new _Network);
  379. nw = nw2;
  380. }
  381. {
  382. std::lock_guard<std::mutex> l(nw->lock);
  383. nw->members[memberId] = config;
  384. if (OSUtils::jsonBool(config["activeBridge"],false))
  385. nw->activeBridgeMembers.insert(memberId);
  386. isAuth = OSUtils::jsonBool(config["authorized"],false);
  387. if (isAuth)
  388. nw->authorizedMembers.insert(memberId);
  389. json &ips = config["ipAssignments"];
  390. if (ips.is_array()) {
  391. for(unsigned long i=0;i<ips.size();++i) {
  392. json &ipj = ips[i];
  393. if (ipj.is_string()) {
  394. const std::string ips = ipj;
  395. InetAddress ipa(ips.c_str());
  396. ipa.setPort(0);
  397. nw->allocatedIps.insert(ipa);
  398. }
  399. }
  400. }
  401. if (!isAuth) {
  402. const int64_t ldt = (int64_t)OSUtils::jsonInt(config["lastDeauthorizedTime"],0ULL);
  403. if (ldt > nw->mostRecentDeauthTime)
  404. nw->mostRecentDeauthTime = ldt;
  405. }
  406. }
  407. _controller->onNetworkMemberUpdate(networkId,memberId);
  408. }
  409. }
  410. if ((wasAuth)&&(!isAuth)&&(networkId)&&(memberId))
  411. _controller->onNetworkMemberDeauthorize(networkId,memberId);
  412. }
  413. void RethinkDB::_networkChanged(nlohmann::json &old,nlohmann::json &network)
  414. {
  415. if (network.is_object()) {
  416. json &config = network["config"];
  417. if (config.is_object()) {
  418. const std::string ids = config["id"];
  419. const uint64_t id = Utils::hexStrToU64(ids.c_str());
  420. if (id) {
  421. std::shared_ptr<_Network> nw;
  422. {
  423. std::lock_guard<std::mutex> l(_networks_l);
  424. std::shared_ptr<_Network> &nw2 = _networks[id];
  425. if (!nw2)
  426. nw2.reset(new _Network);
  427. nw = nw2;
  428. }
  429. {
  430. std::lock_guard<std::mutex> l2(nw->lock);
  431. nw->config = config;
  432. }
  433. _controller->onNetworkUpdate(id);
  434. }
  435. }
  436. } else if (old.is_object()) {
  437. const std::string ids = old["id"];
  438. const uint64_t id = Utils::hexStrToU64(ids.c_str());
  439. if (id) {
  440. std::lock_guard<std::mutex> l(_networks_l);
  441. _networks.erase(id);
  442. }
  443. }
  444. }
  445. } // namespace ZeroTier
  446. /*
  447. int main(int argc,char **argv)
  448. {
  449. ZeroTier::RethinkDB db(ZeroTier::Address(0x8056c2e21cULL),"10.6.6.188",28015,"ztc","");
  450. db.waitForReady();
  451. printf("ready.\n");
  452. pause();
  453. }
  454. */
  455. #endif // ZT_CONTROLLER_USE_RETHINKDB