RethinkDB.cpp 18 KB

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