RethinkDB.cpp 18 KB

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