RethinkDB.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. DB(nc,myAddress,path),
  30. _ready(2), // two tables need to be synchronized before we're ready, so this is ready when it reaches 0
  31. _run(1),
  32. _waitNoticePrinted(false)
  33. {
  34. // rethinkdb:host:port:db[:auth]
  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. _membersDbWatcher = std::thread([this]() {
  45. try {
  46. while (_run == 1) {
  47. try {
  48. std::unique_ptr<R::Connection> rdb(R::connect(this->_host,this->_port,this->_auth));
  49. if (rdb) {
  50. _membersDbWatcherConnection = (void *)rdb.get();
  51. 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);
  52. while (cur.has_next()) {
  53. if (_run != 1) break;
  54. json tmp(json::parse(cur.next().as_json()));
  55. if ((tmp["type"] == "state")&&(tmp["state"] == "ready")) {
  56. if (--this->_ready == 0) {
  57. if (_waitNoticePrinted)
  58. fprintf(stderr,"NOTICE: controller RethinkDB data download complete." ZT_EOL_S);
  59. this->_readyLock.unlock();
  60. }
  61. } else {
  62. try {
  63. json &ov = tmp["old_val"];
  64. json &nv = tmp["new_val"];
  65. if (ov.is_object()||nv.is_object()) {
  66. //if (nv.is_object()) printf("MEMBER: %s" ZT_EOL_S,nv.dump().c_str());
  67. this->_memberChanged(ov,nv,(this->_ready <= 0));
  68. }
  69. } catch ( ... ) {} // ignore bad records
  70. }
  71. }
  72. }
  73. } catch (std::exception &e) {
  74. fprintf(stderr,"ERROR: controller RethinkDB (member change stream): %s" ZT_EOL_S,e.what());
  75. } catch (R::Error &e) {
  76. fprintf(stderr,"ERROR: controller RethinkDB (member change stream): %s" ZT_EOL_S,e.message.c_str());
  77. } catch ( ... ) {
  78. fprintf(stderr,"ERROR: controller RethinkDB (member change stream): unknown exception" ZT_EOL_S);
  79. }
  80. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  81. }
  82. } catch ( ... ) {}
  83. });
  84. _networksDbWatcher = std::thread([this]() {
  85. try {
  86. while (_run == 1) {
  87. try {
  88. std::unique_ptr<R::Connection> rdb(R::connect(this->_host,this->_port,this->_auth));
  89. if (rdb) {
  90. _networksDbWatcherConnection = (void *)rdb.get();
  91. 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);
  92. while (cur.has_next()) {
  93. if (_run != 1) break;
  94. json tmp(json::parse(cur.next().as_json()));
  95. if ((tmp["type"] == "state")&&(tmp["state"] == "ready")) {
  96. if (--this->_ready == 0) {
  97. if (_waitNoticePrinted)
  98. fprintf(stderr,"NOTICE: controller RethinkDB data download complete." ZT_EOL_S);
  99. this->_readyLock.unlock();
  100. }
  101. } else {
  102. try {
  103. json &ov = tmp["old_val"];
  104. json &nv = tmp["new_val"];
  105. if (ov.is_object()||nv.is_object()) {
  106. //if (nv.is_object()) printf("NETWORK: %s" ZT_EOL_S,nv.dump().c_str());
  107. this->_networkChanged(ov,nv,(this->_ready <= 0));
  108. }
  109. } catch ( ... ) {} // ignore bad records
  110. }
  111. }
  112. }
  113. } catch (std::exception &e) {
  114. fprintf(stderr,"ERROR: controller RethinkDB (network change stream): %s" ZT_EOL_S,e.what());
  115. } catch (R::Error &e) {
  116. fprintf(stderr,"ERROR: controller RethinkDB (network change stream): %s" ZT_EOL_S,e.message.c_str());
  117. } catch ( ... ) {
  118. fprintf(stderr,"ERROR: controller RethinkDB (network change stream): unknown exception" ZT_EOL_S);
  119. }
  120. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  121. }
  122. } catch ( ... ) {}
  123. });
  124. for(int t=0;t<ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS;++t) {
  125. _commitThread[t] = std::thread([this]() {
  126. try {
  127. std::unique_ptr<R::Connection> rdb;
  128. nlohmann::json *config = (nlohmann::json *)0;
  129. while ((this->_commitQueue.get(config))&&(_run == 1)) {
  130. if (!config)
  131. continue;
  132. json record;
  133. const std::string objtype = (*config)["objtype"];
  134. const char *table;
  135. std::string deleteId;
  136. try {
  137. if (objtype == "member") {
  138. const std::string nwid = (*config)["nwid"];
  139. const std::string id = (*config)["id"];
  140. record["id"] = nwid + "-" + id;
  141. record["controllerId"] = this->_myAddressStr;
  142. record["networkId"] = nwid;
  143. record["nodeId"] = id;
  144. record["config"] = *config;
  145. table = "Member";
  146. } else if (objtype == "network") {
  147. const std::string id = (*config)["id"];
  148. record["id"] = id;
  149. record["controllerId"] = this->_myAddressStr;
  150. record["config"] = *config;
  151. table = "Network";
  152. } else if (objtype == "trace") {
  153. record = *config;
  154. table = "RemoteTrace";
  155. } else if (objtype == "_delete_network") {
  156. deleteId = (*config)["id"];
  157. table = "Network";
  158. } else if (objtype == "_delete_member") {
  159. deleteId = (*config)["nwid"];
  160. deleteId.push_back('-');
  161. const std::string tmp = (*config)["id"];
  162. deleteId.append(tmp);
  163. table = "Member";
  164. } else {
  165. delete config;
  166. continue;
  167. }
  168. delete config;
  169. } catch ( ... ) {
  170. delete config;
  171. continue;
  172. }
  173. while (_run == 1) {
  174. try {
  175. if (!rdb)
  176. rdb = R::connect(this->_host,this->_port,this->_auth);
  177. if (rdb) {
  178. if (deleteId.length() > 0) {
  179. //printf("DELETE: %s" ZT_EOL_S,deleteId.c_str());
  180. R::db(this->_db).table(table).get(deleteId).delete_().run(*rdb);
  181. } else {
  182. //printf("UPSERT: %s" ZT_EOL_S,record.dump().c_str());
  183. R::db(this->_db).table(table).insert(R::Datum::from_json(record.dump()),R::optargs("conflict","update","return_changes",false)).run(*rdb);
  184. }
  185. break;
  186. } else {
  187. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): connect failed (will retry)" ZT_EOL_S);
  188. }
  189. } catch (std::exception &e) {
  190. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): %s" ZT_EOL_S,e.what());
  191. rdb.reset();
  192. } catch (R::Error &e) {
  193. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): %s" ZT_EOL_S,e.message.c_str());
  194. rdb.reset();
  195. } catch ( ... ) {
  196. fprintf(stderr,"ERROR: controller RethinkDB (insert/update): unknown exception" ZT_EOL_S);
  197. rdb.reset();
  198. }
  199. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  200. }
  201. }
  202. } catch ( ... ) {}
  203. });
  204. }
  205. _onlineNotificationThread = std::thread([this]() {
  206. try {
  207. std::unique_ptr<R::Connection> rdb;
  208. while (_run == 1) {
  209. try {
  210. if (!rdb)
  211. rdb = R::connect(this->_host,this->_port,this->_auth);
  212. if (rdb) {
  213. std::lock_guard<std::mutex> l(_lastOnline_l);
  214. R::Array batch;
  215. R::Object tmpobj;
  216. for(auto i=_lastOnline.begin();i!=_lastOnline.end();++i) {
  217. char tmp[64],tmp2[64];
  218. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx-%.10llx",i->first.first,i->first.second);
  219. tmpobj["id"] = tmp;
  220. tmpobj["ts"] = i->second.first;
  221. tmpobj["phy"] = i->second.second.toIpString(tmp2);
  222. batch.emplace_back(tmpobj);
  223. if (batch.size() >= 256) {
  224. R::db(this->_db).table("MemberLastRequest",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
  225. batch.clear();
  226. }
  227. }
  228. if (batch.size() > 0)
  229. R::db(this->_db).table("MemberLastRequest",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
  230. _lastOnline.clear();
  231. }
  232. } catch (std::exception &e) {
  233. fprintf(stderr,"ERROR: controller RethinkDB (node status update): %s" ZT_EOL_S,e.what());
  234. rdb.reset();
  235. } catch (R::Error &e) {
  236. fprintf(stderr,"ERROR: controller RethinkDB (node status update): %s" ZT_EOL_S,e.message.c_str());
  237. rdb.reset();
  238. } catch ( ... ) {
  239. fprintf(stderr,"ERROR: controller RethinkDB (node status update): unknown exception" ZT_EOL_S);
  240. rdb.reset();
  241. }
  242. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  243. }
  244. } catch ( ... ) {}
  245. });
  246. _heartbeatThread = std::thread([this]() {
  247. try {
  248. char tmp[1024];
  249. std::unique_ptr<R::Connection> rdb;
  250. while (_run == 1) {
  251. try {
  252. if (!rdb)
  253. rdb = R::connect(this->_host,this->_port,this->_auth);
  254. if (rdb) {
  255. OSUtils::ztsnprintf(tmp,sizeof(tmp),"{\"id\":\"%s\",\"lastAlive\":%lld}",this->_myAddressStr.c_str(),(long long)OSUtils::now());
  256. //printf("HEARTBEAT: %s" ZT_EOL_S,tmp);
  257. R::db(this->_db).table("Controller").update(R::Datum::from_json(tmp)).run(*rdb);
  258. }
  259. } catch ( ... ) {
  260. rdb.reset();
  261. }
  262. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  263. }
  264. } catch ( ... ) {}
  265. });
  266. }
  267. RethinkDB::~RethinkDB()
  268. {
  269. _run = 0;
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. _commitQueue.stop();
  272. for(int t=0;t<ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS;++t)
  273. _commitThread[t].join();
  274. if (_membersDbWatcherConnection)
  275. ((R::Connection *)_membersDbWatcherConnection)->close();
  276. if (_networksDbWatcherConnection)
  277. ((R::Connection *)_networksDbWatcherConnection)->close();
  278. _membersDbWatcher.join();
  279. _networksDbWatcher.join();
  280. _heartbeatThread.join();
  281. _onlineNotificationThread.join();
  282. }
  283. bool RethinkDB::waitForReady()
  284. {
  285. while (_ready > 0) {
  286. if (!_waitNoticePrinted) {
  287. _waitNoticePrinted = true;
  288. fprintf(stderr,"NOTICE: controller RethinkDB waiting for initial data download..." ZT_EOL_S);
  289. }
  290. _readyLock.lock();
  291. _readyLock.unlock();
  292. }
  293. return true;
  294. }
  295. void RethinkDB::save(nlohmann::json *orig,nlohmann::json &record)
  296. {
  297. if (!record.is_object()) // sanity check
  298. return;
  299. waitForReady();
  300. if (orig) {
  301. if (*orig != record) {
  302. nlohmann::json *q = new nlohmann::json();
  303. try {
  304. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  305. for(auto kv=record.begin();kv!=record.end();++kv) {
  306. if ((kv.key() == "id")||(kv.key() == "nwid")||(kv.key() == "objtype")||((*q)[kv.key()] != kv.value()))
  307. (*q)[kv.key()] = kv.value();
  308. }
  309. } catch ( ... ) {
  310. delete q;
  311. throw;
  312. }
  313. }
  314. } else {
  315. record["revision"] = 1;
  316. _commitQueue.post(new nlohmann::json(record));
  317. }
  318. }
  319. void RethinkDB::eraseNetwork(const uint64_t networkId)
  320. {
  321. char tmp2[24];
  322. waitForReady();
  323. Utils::hex(networkId,tmp2);
  324. json *tmp = new json();
  325. (*tmp)["id"] = tmp2;
  326. (*tmp)["objtype"] = "_delete_network"; // pseudo-type, tells thread to delete network
  327. _commitQueue.post(tmp);
  328. }
  329. void RethinkDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  330. {
  331. char tmp2[24];
  332. json *tmp = new json();
  333. waitForReady();
  334. Utils::hex(networkId,tmp2);
  335. (*tmp)["nwid"] = tmp2;
  336. Utils::hex10(memberId,tmp2);
  337. (*tmp)["id"] = tmp2;
  338. (*tmp)["objtype"] = "_delete_member"; // pseudo-type, tells thread to delete network
  339. _commitQueue.post(tmp);
  340. }
  341. void RethinkDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
  342. {
  343. std::lock_guard<std::mutex> l(_lastOnline_l);
  344. std::pair<int64_t,InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId,memberId)];
  345. i.first = OSUtils::now();
  346. if (physicalAddress)
  347. i.second = physicalAddress;
  348. }
  349. } // namespace ZeroTier
  350. #endif // ZT_CONTROLLER_USE_RETHINKDB