RethinkDB.cpp 16 KB

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