RethinkDB.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 "../version.h"
  22. #include <chrono>
  23. #include <algorithm>
  24. #include <stdexcept>
  25. #include "../ext/librethinkdbxx/build/include/rethinkdb.h"
  26. namespace R = RethinkDB;
  27. using json = nlohmann::json;
  28. namespace ZeroTier {
  29. RethinkDB::RethinkDB(EmbeddedNetworkController *const nc,const Address &myAddress,const char *path) :
  30. DB(nc,myAddress,path),
  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. // rethinkdb:host:port:db[:auth]
  36. std::vector<std::string> ps(OSUtils::split(path,":","",""));
  37. if ((ps.size() < 4)||(ps[0] != "rethinkdb"))
  38. throw std::runtime_error("invalid rethinkdb database url");
  39. _host = ps[1];
  40. _port = Utils::strToInt(ps[2].c_str());
  41. _db = ps[3];
  42. if (ps.size() > 4)
  43. _auth = ps[4];
  44. _readyLock.lock();
  45. _membersDbWatcher = std::thread([this]() {
  46. try {
  47. while (_run == 1) {
  48. try {
  49. std::unique_ptr<R::Connection> rdb(R::connect(this->_host,this->_port,this->_auth));
  50. if (rdb) {
  51. _membersDbWatcherConnection = (void *)rdb.get();
  52. 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);
  53. while (cur.has_next()) {
  54. if (_run != 1) break;
  55. json tmp(json::parse(cur.next().as_json()));
  56. if ((tmp["type"] == "state")&&(tmp["state"] == "ready")) {
  57. if (--this->_ready == 0) {
  58. if (_waitNoticePrinted)
  59. fprintf(stderr,"NOTICE: controller RethinkDB data download complete." ZT_EOL_S);
  60. this->_readyLock.unlock();
  61. }
  62. } else {
  63. try {
  64. json &ov = tmp["old_val"];
  65. json &nv = tmp["new_val"];
  66. if (ov.is_object()||nv.is_object()) {
  67. //if (nv.is_object()) printf("MEMBER: %s" ZT_EOL_S,nv.dump().c_str());
  68. this->_memberChanged(ov,nv,(this->_ready <= 0));
  69. }
  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. } catch ( ... ) {}
  84. });
  85. _networksDbWatcher = std::thread([this]() {
  86. try {
  87. while (_run == 1) {
  88. try {
  89. std::unique_ptr<R::Connection> rdb(R::connect(this->_host,this->_port,this->_auth));
  90. if (rdb) {
  91. _networksDbWatcherConnection = (void *)rdb.get();
  92. 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);
  93. while (cur.has_next()) {
  94. if (_run != 1) break;
  95. json tmp(json::parse(cur.next().as_json()));
  96. if ((tmp["type"] == "state")&&(tmp["state"] == "ready")) {
  97. if (--this->_ready == 0) {
  98. if (_waitNoticePrinted)
  99. fprintf(stderr,"NOTICE: controller RethinkDB data download complete." ZT_EOL_S);
  100. this->_readyLock.unlock();
  101. }
  102. } else {
  103. try {
  104. json &ov = tmp["old_val"];
  105. json &nv = tmp["new_val"];
  106. if (ov.is_object()||nv.is_object()) {
  107. //if (nv.is_object()) printf("NETWORK: %s" ZT_EOL_S,nv.dump().c_str());
  108. this->_networkChanged(ov,nv,(this->_ready <= 0));
  109. }
  110. } catch ( ... ) {} // ignore bad records
  111. }
  112. }
  113. }
  114. } catch (std::exception &e) {
  115. fprintf(stderr,"ERROR: controller RethinkDB (network change stream): %s" ZT_EOL_S,e.what());
  116. } catch (R::Error &e) {
  117. fprintf(stderr,"ERROR: controller RethinkDB (network change stream): %s" ZT_EOL_S,e.message.c_str());
  118. } catch ( ... ) {
  119. fprintf(stderr,"ERROR: controller RethinkDB (network change stream): unknown exception" ZT_EOL_S);
  120. }
  121. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  122. }
  123. } catch ( ... ) {}
  124. });
  125. for(int t=0;t<ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS;++t) {
  126. _commitThread[t] = std::thread([this]() {
  127. try {
  128. std::unique_ptr<R::Connection> rdb;
  129. nlohmann::json *config = (nlohmann::json *)0;
  130. while ((this->_commitQueue.get(config))&&(_run == 1)) {
  131. if (!config)
  132. continue;
  133. json record;
  134. const std::string objtype = (*config)["objtype"];
  135. const char *table;
  136. std::string deleteId;
  137. try {
  138. if (objtype == "member") {
  139. const std::string nwid = (*config)["nwid"];
  140. const std::string id = (*config)["id"];
  141. record["id"] = nwid + "-" + id;
  142. record["controllerId"] = this->_myAddressStr;
  143. record["networkId"] = nwid;
  144. record["nodeId"] = id;
  145. record["config"] = *config;
  146. table = "Member";
  147. } else if (objtype == "network") {
  148. const std::string id = (*config)["id"];
  149. record["id"] = id;
  150. record["controllerId"] = this->_myAddressStr;
  151. record["config"] = *config;
  152. table = "Network";
  153. } else if (objtype == "trace") {
  154. record = *config;
  155. table = "RemoteTrace";
  156. } else if (objtype == "_delete_network") {
  157. deleteId = (*config)["id"];
  158. table = "Network";
  159. } else if (objtype == "_delete_member") {
  160. deleteId = (*config)["nwid"];
  161. deleteId.push_back('-');
  162. const std::string tmp = (*config)["id"];
  163. deleteId.append(tmp);
  164. table = "Member";
  165. } else {
  166. delete config;
  167. continue;
  168. }
  169. delete config;
  170. } catch ( ... ) {
  171. delete config;
  172. continue;
  173. }
  174. while (_run == 1) {
  175. try {
  176. if (!rdb)
  177. rdb = R::connect(this->_host,this->_port,this->_auth);
  178. if (rdb) {
  179. if (deleteId.length() > 0) {
  180. //printf("DELETE: %s" ZT_EOL_S,deleteId.c_str());
  181. R::db(this->_db).table(table).get(deleteId).delete_().run(*rdb);
  182. } else {
  183. //printf("UPSERT: %s" ZT_EOL_S,record.dump().c_str());
  184. R::db(this->_db).table(table).insert(R::Datum::from_json(record.dump()),R::optargs("conflict","update","return_changes",false)).run(*rdb);
  185. }
  186. break;
  187. } else {
  188. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): connect failed (will retry)" ZT_EOL_S);
  189. }
  190. } catch (std::exception &e) {
  191. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): %s" ZT_EOL_S,e.what());
  192. rdb.reset();
  193. } catch (R::Error &e) {
  194. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): %s" ZT_EOL_S,e.message.c_str());
  195. rdb.reset();
  196. } catch ( ... ) {
  197. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): unknown exception" ZT_EOL_S);
  198. rdb.reset();
  199. }
  200. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  201. }
  202. }
  203. } catch ( ... ) {}
  204. });
  205. }
  206. _onlineNotificationThread = std::thread([this]() {
  207. int64_t lastUpdatedNetworkStatus = 0;
  208. std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative;
  209. try {
  210. std::unique_ptr<R::Connection> rdb;
  211. while (_run == 1) {
  212. try {
  213. if (!rdb)
  214. rdb = R::connect(this->_host,this->_port,this->_auth);
  215. if (rdb) {
  216. R::Array batch;
  217. R::Object tmpobj;
  218. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  219. {
  220. std::lock_guard<std::mutex> l(_lastOnline_l);
  221. lastOnline.swap(_lastOnline);
  222. }
  223. for(auto i=lastOnline.begin();i!=lastOnline.end();++i) {
  224. lastOnlineCumulative[i->first] = i->second.first;
  225. char tmp[64],tmp2[64];
  226. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx-%.10llx",i->first.first,i->first.second);
  227. tmpobj["id"] = tmp;
  228. tmpobj["ts"] = i->second.first;
  229. tmpobj["phy"] = i->second.second.toIpString(tmp2);
  230. batch.emplace_back(tmpobj);
  231. if (batch.size() >= 1024) {
  232. R::db(this->_db).table("MemberStatus",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
  233. batch.clear();
  234. }
  235. }
  236. if (batch.size() > 0) {
  237. R::db(this->_db).table("MemberStatus",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
  238. batch.clear();
  239. }
  240. tmpobj.clear();
  241. const int64_t now = OSUtils::now();
  242. if ((now - lastUpdatedNetworkStatus) > 10000) {
  243. lastUpdatedNetworkStatus = now;
  244. std::vector< std::pair< uint64_t,std::shared_ptr<_Network> > > networks;
  245. {
  246. std::lock_guard<std::mutex> l(_networks_l);
  247. networks.reserve(_networks.size() + 1);
  248. for(auto i=_networks.begin();i!=_networks.end();++i)
  249. networks.push_back(*i);
  250. }
  251. for(auto i=networks.begin();i!=networks.end();++i) {
  252. char tmp[64];
  253. Utils::hex(i->first,tmp);
  254. tmpobj["id"] = tmp;
  255. {
  256. std::lock_guard<std::mutex> l2(i->second->lock);
  257. tmpobj["authorizedMemberCount"] = i->second->authorizedMembers.size();
  258. tmpobj["totalMemberCount"] = i->second->members.size();
  259. unsigned long activeMemberCount = 0;
  260. for(auto m=i->second->members.begin();m!=i->second->members.end();++m) {
  261. auto lo = lastOnlineCumulative.find(std::pair<uint64_t,uint64_t>(i->first,m->first));
  262. if (lo != lastOnlineCumulative.end()) {
  263. if ((now - lo->second) <= (ZT_NETWORK_AUTOCONF_DELAY * 2))
  264. ++activeMemberCount;
  265. else lastOnlineCumulative.erase(lo);
  266. }
  267. }
  268. tmpobj["activeMemberCount"] = activeMemberCount;
  269. tmpobj["bridgeCount"] = i->second->activeBridgeMembers.size();
  270. }
  271. batch.emplace_back(tmpobj);
  272. if (batch.size() >= 1024) {
  273. R::db(this->_db).table("NetworkStatus",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
  274. batch.clear();
  275. }
  276. }
  277. if (batch.size() > 0) {
  278. R::db(this->_db).table("NetworkStatus",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
  279. batch.clear();
  280. }
  281. }
  282. }
  283. } catch (std::exception &e) {
  284. fprintf(stderr,"ERROR: controller RethinkDB (node status update): %s" ZT_EOL_S,e.what());
  285. rdb.reset();
  286. } catch (R::Error &e) {
  287. fprintf(stderr,"ERROR: controller RethinkDB (node status update): %s" ZT_EOL_S,e.message.c_str());
  288. rdb.reset();
  289. } catch ( ... ) {
  290. fprintf(stderr,"ERROR: controller RethinkDB (node status update): unknown exception" ZT_EOL_S);
  291. rdb.reset();
  292. }
  293. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  294. }
  295. } catch ( ... ) {}
  296. });
  297. _heartbeatThread = std::thread([this]() {
  298. try {
  299. char tmp[1024];
  300. std::unique_ptr<R::Connection> rdb;
  301. while (_run == 1) {
  302. try {
  303. if (!rdb)
  304. rdb = R::connect(this->_host,this->_port,this->_auth);
  305. if (rdb) {
  306. OSUtils::ztsnprintf(tmp,sizeof(tmp),"{\"id\":\"%s\",\"lastAlive\":%lld,\"version\":\"%d.%d.%d\"}",this->_myAddressStr.c_str(),(long long)OSUtils::now(),ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  307. //printf("HEARTBEAT: %s" ZT_EOL_S,tmp);
  308. R::db(this->_db).table("Controller").update(R::Datum::from_json(tmp)).run(*rdb);
  309. }
  310. } catch ( ... ) {
  311. rdb.reset();
  312. }
  313. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  314. }
  315. } catch ( ... ) {}
  316. });
  317. }
  318. RethinkDB::~RethinkDB()
  319. {
  320. _run = 0;
  321. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  322. _commitQueue.stop();
  323. for(int t=0;t<ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS;++t)
  324. _commitThread[t].join();
  325. if (_membersDbWatcherConnection)
  326. ((R::Connection *)_membersDbWatcherConnection)->close();
  327. if (_networksDbWatcherConnection)
  328. ((R::Connection *)_networksDbWatcherConnection)->close();
  329. _membersDbWatcher.join();
  330. _networksDbWatcher.join();
  331. _heartbeatThread.join();
  332. _onlineNotificationThread.join();
  333. }
  334. bool RethinkDB::waitForReady()
  335. {
  336. while (_ready > 0) {
  337. if (!_waitNoticePrinted) {
  338. _waitNoticePrinted = true;
  339. fprintf(stderr,"NOTICE: controller RethinkDB waiting for initial data download..." ZT_EOL_S);
  340. }
  341. _readyLock.lock();
  342. _readyLock.unlock();
  343. }
  344. return true;
  345. }
  346. void RethinkDB::save(nlohmann::json *orig,nlohmann::json &record)
  347. {
  348. if (!record.is_object()) // sanity check
  349. return;
  350. waitForReady();
  351. if (orig) {
  352. if (*orig != record) {
  353. nlohmann::json *q = new nlohmann::json();
  354. try {
  355. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  356. for(auto kv=record.begin();kv!=record.end();++kv) {
  357. if ((kv.key() == "id")||(kv.key() == "nwid")||(kv.key() == "objtype")||((*q)[kv.key()] != kv.value()))
  358. (*q)[kv.key()] = kv.value();
  359. }
  360. } catch ( ... ) {
  361. delete q;
  362. throw;
  363. }
  364. }
  365. } else {
  366. record["revision"] = 1;
  367. _commitQueue.post(new nlohmann::json(record));
  368. }
  369. }
  370. void RethinkDB::eraseNetwork(const uint64_t networkId)
  371. {
  372. char tmp2[24];
  373. waitForReady();
  374. Utils::hex(networkId,tmp2);
  375. json *tmp = new json();
  376. (*tmp)["id"] = tmp2;
  377. (*tmp)["objtype"] = "_delete_network"; // pseudo-type, tells thread to delete network
  378. _commitQueue.post(tmp);
  379. }
  380. void RethinkDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  381. {
  382. char tmp2[24];
  383. json *tmp = new json();
  384. waitForReady();
  385. Utils::hex(networkId,tmp2);
  386. (*tmp)["nwid"] = tmp2;
  387. Utils::hex10(memberId,tmp2);
  388. (*tmp)["id"] = tmp2;
  389. (*tmp)["objtype"] = "_delete_member"; // pseudo-type, tells thread to delete network
  390. _commitQueue.post(tmp);
  391. }
  392. void RethinkDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
  393. {
  394. std::lock_guard<std::mutex> l(_lastOnline_l);
  395. std::pair<int64_t,InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId,memberId)];
  396. i.first = OSUtils::now();
  397. if (physicalAddress)
  398. i.second = physicalAddress;
  399. }
  400. } // namespace ZeroTier
  401. #endif // ZT_CONTROLLER_USE_RETHINKDB