RethinkDB.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. json oldConfig,newConfig;
  128. if (ov.is_object()) oldConfig = ov["config"];
  129. if (nv.is_object()) newConfig = nv["config"];
  130. if (oldConfig.is_object()||newConfig.is_object())
  131. this->_networkChanged(oldConfig,newConfig,(this->_ready <= 0));
  132. } catch ( ... ) {} // ignore bad records
  133. }
  134. }
  135. }
  136. } catch (std::exception &e) {
  137. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (network change stream): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.what());
  138. } catch (R::Error &e) {
  139. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (network change stream): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.message.c_str());
  140. } catch ( ... ) {
  141. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (network change stream): unknown exception" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  142. }
  143. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  144. }
  145. } catch ( ... ) {}
  146. });
  147. for(int t=0;t<ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS;++t) {
  148. _commitThread[t] = std::thread([this]() {
  149. try {
  150. std::unique_ptr<R::Connection> rdb;
  151. nlohmann::json *config = (nlohmann::json *)0;
  152. while ((this->_commitQueue.get(config))&&(_run == 1)) {
  153. if (!config)
  154. continue;
  155. nlohmann::json record;
  156. const char *table = (const char *)0;
  157. std::string deleteId;
  158. try {
  159. const std::string objtype = (*config)["objtype"];
  160. if (objtype == "member") {
  161. const std::string nwid = (*config)["nwid"];
  162. const std::string id = (*config)["id"];
  163. record["id"] = nwid + "-" + id;
  164. record["controllerId"] = this->_myAddressStr;
  165. record["networkId"] = nwid;
  166. record["nodeId"] = id;
  167. record["config"] = *config;
  168. table = "Member";
  169. } else if (objtype == "network") {
  170. const std::string id = (*config)["id"];
  171. record["id"] = id;
  172. record["controllerId"] = this->_myAddressStr;
  173. record["config"] = *config;
  174. table = "Network";
  175. } else if (objtype == "trace") {
  176. record = *config;
  177. table = "RemoteTrace";
  178. } else if (objtype == "_delete_network") {
  179. deleteId = (*config)["id"];
  180. table = "Network";
  181. } else if (objtype == "_delete_member") {
  182. deleteId = (*config)["nwid"];
  183. deleteId.push_back('-');
  184. const std::string tmp = (*config)["id"];
  185. deleteId.append(tmp);
  186. table = "Member";
  187. }
  188. } catch (std::exception &e) {
  189. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update record creation): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.what());
  190. table = (const char *)0;
  191. } catch (R::Error &e) {
  192. 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());
  193. table = (const char *)0;
  194. } catch ( ... ) {
  195. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update record creation): unknown exception" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  196. table = (const char *)0;
  197. }
  198. delete config;
  199. if (!table)
  200. continue;
  201. const std::string jdump(OSUtils::jsonDump(record,-1));
  202. while (_run == 1) {
  203. try {
  204. if (!rdb)
  205. rdb = R::connect(this->_host,this->_port,this->_auth);
  206. if (rdb) {
  207. if (deleteId.length() > 0) {
  208. //printf("DELETE: %s" ZT_EOL_S,deleteId.c_str());
  209. R::db(this->_db).table(table).get(deleteId).delete_().run(*rdb);
  210. } else {
  211. //printf("UPSERT: %s" ZT_EOL_S,record.dump().c_str());
  212. R::db(this->_db).table(table).insert(R::Datum::from_json(jdump),R::optargs("conflict","update","return_changes",false)).run(*rdb);
  213. }
  214. break;
  215. } else {
  216. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update): connect failed (will retry)" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  217. rdb.reset();
  218. }
  219. } catch (std::exception &e) {
  220. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update): %s [%s]" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.what(),jdump.c_str());
  221. rdb.reset();
  222. } catch (R::Error &e) {
  223. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update): %s [%s]" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.message.c_str(),jdump.c_str());
  224. rdb.reset();
  225. } catch ( ... ) {
  226. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update): unknown exception [%s]" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),jdump.c_str());
  227. rdb.reset();
  228. }
  229. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  230. }
  231. }
  232. } catch (std::exception &e) {
  233. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update outer loop): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.what());
  234. } catch (R::Error &e) {
  235. 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());
  236. } catch ( ... ) {
  237. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update outer loop): unknown exception" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  238. }
  239. });
  240. }
  241. _onlineNotificationThread = std::thread([this]() {
  242. int64_t lastUpdatedNetworkStatus = 0;
  243. std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative;
  244. try {
  245. std::unique_ptr<R::Connection> rdb;
  246. while (_run == 1) {
  247. try {
  248. if (!rdb)
  249. rdb = R::connect(this->_host,this->_port,this->_auth);
  250. if (rdb) {
  251. R::Array batch;
  252. R::Object tmpobj;
  253. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  254. {
  255. std::lock_guard<std::mutex> l(_lastOnline_l);
  256. lastOnline.swap(_lastOnline);
  257. }
  258. for(auto i=lastOnline.begin();i!=lastOnline.end();++i) {
  259. lastOnlineCumulative[i->first] = i->second.first;
  260. char tmp[64],tmp2[64];
  261. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx-%.10llx",i->first.first,i->first.second);
  262. tmpobj["id"] = tmp;
  263. tmpobj["ts"] = i->second.first;
  264. tmpobj["phy"] = i->second.second.toIpString(tmp2);
  265. batch.emplace_back(tmpobj);
  266. if (batch.size() >= 1024) {
  267. R::db(this->_db).table("MemberStatus",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
  268. batch.clear();
  269. }
  270. }
  271. if (batch.size() > 0) {
  272. R::db(this->_db).table("MemberStatus",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
  273. batch.clear();
  274. }
  275. tmpobj.clear();
  276. const int64_t now = OSUtils::now();
  277. if ((now - lastUpdatedNetworkStatus) > 10000) {
  278. lastUpdatedNetworkStatus = now;
  279. std::vector< std::pair< uint64_t,std::shared_ptr<_Network> > > networks;
  280. {
  281. std::lock_guard<std::mutex> l(_networks_l);
  282. networks.reserve(_networks.size() + 1);
  283. for(auto i=_networks.begin();i!=_networks.end();++i)
  284. networks.push_back(*i);
  285. }
  286. for(auto i=networks.begin();i!=networks.end();++i) {
  287. char tmp[64];
  288. Utils::hex(i->first,tmp);
  289. tmpobj["id"] = tmp;
  290. {
  291. std::lock_guard<std::mutex> l2(i->second->lock);
  292. tmpobj["authorizedMemberCount"] = i->second->authorizedMembers.size();
  293. tmpobj["totalMemberCount"] = i->second->members.size();
  294. unsigned long onlineMemberCount = 0;
  295. for(auto m=i->second->members.begin();m!=i->second->members.end();++m) {
  296. auto lo = lastOnlineCumulative.find(std::pair<uint64_t,uint64_t>(i->first,m->first));
  297. if (lo != lastOnlineCumulative.end()) {
  298. if ((now - lo->second) <= (ZT_NETWORK_AUTOCONF_DELAY * 2))
  299. ++onlineMemberCount;
  300. else lastOnlineCumulative.erase(lo);
  301. }
  302. }
  303. tmpobj["onlineMemberCount"] = onlineMemberCount;
  304. tmpobj["bridgeCount"] = i->second->activeBridgeMembers.size();
  305. tmpobj["ts"] = now;
  306. }
  307. batch.emplace_back(tmpobj);
  308. if (batch.size() >= 1024) {
  309. R::db(this->_db).table("NetworkStatus",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
  310. batch.clear();
  311. }
  312. }
  313. if (batch.size() > 0) {
  314. R::db(this->_db).table("NetworkStatus",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
  315. batch.clear();
  316. }
  317. }
  318. }
  319. } catch (std::exception &e) {
  320. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (node status update): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.what());
  321. rdb.reset();
  322. } catch (R::Error &e) {
  323. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (node status update): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.message.c_str());
  324. rdb.reset();
  325. } catch ( ... ) {
  326. fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (node status update): unknown exception" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  327. rdb.reset();
  328. }
  329. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  330. }
  331. } catch ( ... ) {}
  332. });
  333. _heartbeatThread = std::thread([this]() {
  334. try {
  335. R::Object controllerRecord;
  336. std::unique_ptr<R::Connection> rdb;
  337. {
  338. char publicId[1024];
  339. //char secretId[1024];
  340. char hostname[1024];
  341. this->_myId.toString(false,publicId);
  342. //this->_myId.toString(true,secretId);
  343. if (gethostname(hostname,sizeof(hostname)) != 0) {
  344. hostname[0] = (char)0;
  345. } else {
  346. for(int i=0;i<sizeof(hostname);++i) {
  347. if ((hostname[i] == '.')||(hostname[i] == 0)) {
  348. hostname[i] = (char)0;
  349. break;
  350. }
  351. }
  352. }
  353. controllerRecord["id"] = this->_myAddressStr.c_str();
  354. controllerRecord["publicIdentity"] = publicId;
  355. //controllerRecord["secretIdentity"] = secretId;
  356. if (hostname[0])
  357. controllerRecord["clusterHost"] = hostname;
  358. controllerRecord["vMajor"] = ZEROTIER_ONE_VERSION_MAJOR;
  359. controllerRecord["vMinor"] = ZEROTIER_ONE_VERSION_MINOR;
  360. controllerRecord["vRev"] = ZEROTIER_ONE_VERSION_REVISION;
  361. controllerRecord["vBuild"] = ZEROTIER_ONE_VERSION_BUILD;
  362. }
  363. while (_run == 1) {
  364. try {
  365. if (!rdb)
  366. rdb = R::connect(this->_host,this->_port,this->_auth);
  367. if (rdb) {
  368. controllerRecord["lastAlive"] = OSUtils::now();
  369. //printf("HEARTBEAT: %s" ZT_EOL_S,tmp);
  370. R::db(this->_db).table("Controller",R::optargs("read_mode","outdated")).insert(controllerRecord,R::optargs("conflict","update")).run(*rdb);
  371. }
  372. } catch ( ... ) {
  373. rdb.reset();
  374. }
  375. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  376. }
  377. } catch ( ... ) {}
  378. });
  379. }
  380. RethinkDB::~RethinkDB()
  381. {
  382. _run = 0;
  383. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  384. _commitQueue.stop();
  385. for(int t=0;t<ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS;++t)
  386. _commitThread[t].join();
  387. if (_membersDbWatcherConnection)
  388. ((R::Connection *)_membersDbWatcherConnection)->close();
  389. if (_networksDbWatcherConnection)
  390. ((R::Connection *)_networksDbWatcherConnection)->close();
  391. _membersDbWatcher.join();
  392. _networksDbWatcher.join();
  393. _heartbeatThread.join();
  394. _onlineNotificationThread.join();
  395. }
  396. bool RethinkDB::waitForReady()
  397. {
  398. while (_ready > 0) {
  399. if (!_waitNoticePrinted) {
  400. _waitNoticePrinted = true;
  401. fprintf(stderr,"[%s] NOTICE: %.10llx controller RethinkDB waiting for initial data download..." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  402. }
  403. _readyLock.lock();
  404. _readyLock.unlock();
  405. }
  406. return true;
  407. }
  408. void RethinkDB::save(nlohmann::json *orig,nlohmann::json &record)
  409. {
  410. if (!record.is_object()) // sanity check
  411. return;
  412. waitForReady();
  413. if (orig) {
  414. if (*orig != record) {
  415. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  416. _commitQueue.post(new nlohmann::json(record));
  417. }
  418. } else {
  419. record["revision"] = 1;
  420. _commitQueue.post(new nlohmann::json(record));
  421. }
  422. }
  423. void RethinkDB::eraseNetwork(const uint64_t networkId)
  424. {
  425. char tmp2[24];
  426. waitForReady();
  427. Utils::hex(networkId,tmp2);
  428. json *tmp = new json();
  429. (*tmp)["id"] = tmp2;
  430. (*tmp)["objtype"] = "_delete_network"; // pseudo-type, tells thread to delete network
  431. _commitQueue.post(tmp);
  432. }
  433. void RethinkDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  434. {
  435. char tmp2[24];
  436. json *tmp = new json();
  437. waitForReady();
  438. Utils::hex(networkId,tmp2);
  439. (*tmp)["nwid"] = tmp2;
  440. Utils::hex10(memberId,tmp2);
  441. (*tmp)["id"] = tmp2;
  442. (*tmp)["objtype"] = "_delete_member"; // pseudo-type, tells thread to delete network
  443. _commitQueue.post(tmp);
  444. }
  445. void RethinkDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
  446. {
  447. std::lock_guard<std::mutex> l(_lastOnline_l);
  448. std::pair<int64_t,InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId,memberId)];
  449. i.first = OSUtils::now();
  450. if (physicalAddress)
  451. i.second = physicalAddress;
  452. }
  453. } // namespace ZeroTier
  454. #endif // ZT_CONTROLLER_USE_RETHINKDB