RethinkDB.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. _heartbeatThread = std::thread([this]() {
  206. try {
  207. char tmp[1024];
  208. std::unique_ptr<R::Connection> rdb;
  209. while (_run == 1) {
  210. try {
  211. if (!rdb)
  212. rdb = R::connect(this->_host,this->_port,this->_auth);
  213. if (rdb) {
  214. OSUtils::ztsnprintf(tmp,sizeof(tmp),"{\"id\":\"%s\",\"lastAlive\":%lld}",this->_myAddressStr.c_str(),(long long)OSUtils::now());
  215. //printf("HEARTBEAT: %s" ZT_EOL_S,tmp);
  216. R::db(this->_db).table("Controller").update(R::Datum::from_json(tmp)).run(*rdb);
  217. }
  218. } catch ( ... ) {
  219. rdb.reset();
  220. }
  221. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  222. }
  223. } catch ( ... ) {}
  224. });
  225. }
  226. RethinkDB::~RethinkDB()
  227. {
  228. _run = 0;
  229. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  230. _commitQueue.stop();
  231. for(int t=0;t<ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS;++t)
  232. _commitThread[t].join();
  233. if (_membersDbWatcherConnection)
  234. ((R::Connection *)_membersDbWatcherConnection)->close();
  235. if (_networksDbWatcherConnection)
  236. ((R::Connection *)_networksDbWatcherConnection)->close();
  237. _membersDbWatcher.join();
  238. _networksDbWatcher.join();
  239. _heartbeatThread.join();
  240. }
  241. void RethinkDB::waitForReady()
  242. {
  243. while (_ready > 0) {
  244. if (!_waitNoticePrinted) {
  245. _waitNoticePrinted = true;
  246. fprintf(stderr,"NOTICE: controller RethinkDB waiting for initial data download..." ZT_EOL_S);
  247. }
  248. _readyLock.lock();
  249. _readyLock.unlock();
  250. }
  251. }
  252. void RethinkDB::save(const nlohmann::json &record)
  253. {
  254. waitForReady();
  255. _commitQueue.post(new nlohmann::json(record));
  256. }
  257. void RethinkDB::eraseNetwork(const uint64_t networkId)
  258. {
  259. char tmp2[24];
  260. waitForReady();
  261. Utils::hex(networkId,tmp2);
  262. json *tmp = new json();
  263. (*tmp)["id"] = tmp2;
  264. (*tmp)["objtype"] = "_delete_network"; // pseudo-type, tells thread to delete network
  265. _commitQueue.post(tmp);
  266. }
  267. void RethinkDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  268. {
  269. char tmp2[24];
  270. json *tmp = new json();
  271. waitForReady();
  272. Utils::hex(networkId,tmp2);
  273. (*tmp)["nwid"] = tmp2;
  274. Utils::hex10(memberId,tmp2);
  275. (*tmp)["id"] = tmp2;
  276. (*tmp)["objtype"] = "_delete_member"; // pseudo-type, tells thread to delete network
  277. _commitQueue.post(tmp);
  278. }
  279. } // namespace ZeroTier
  280. #endif // ZT_CONTROLLER_USE_RETHINKDB