RethinkDB.cpp 18 KB

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