RethinkDB.cpp 18 KB

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