LFDB.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
  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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include "LFDB.hpp"
  27. #include <thread>
  28. #include <chrono>
  29. #include <iostream>
  30. #include <sstream>
  31. #include "../osdep/OSUtils.hpp"
  32. #include "../ext/cpp-httplib/httplib.h"
  33. namespace ZeroTier
  34. {
  35. LFDB::LFDB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path,const char *lfOwnerPrivate,const char *lfOwnerPublic,const char *lfNodeHost,int lfNodePort,bool storeOnlineState) :
  36. DB(nc,myId,path),
  37. _nc(nc),
  38. _myId(myId),
  39. _lfOwnerPrivate(lfOwnerPrivate),
  40. _lfOwnerPublic(lfOwnerPublic),
  41. _lfNodeHost(lfNodeHost),
  42. _lfNodePort(lfNodePort),
  43. _running(true),
  44. _ready(false),
  45. _storeOnlineState(storeOnlineState)
  46. {
  47. _syncThread = std::thread([this]() {
  48. char controllerAddress[24];
  49. _myId.address().toString(controllerAddress);
  50. httplib::Client htcli(_lfNodeHost.c_str(),_lfNodePort,600);
  51. std::ostringstream query;
  52. int64_t timeRangeStart = 0;
  53. while (_running) {
  54. query.clear();
  55. query
  56. << '{'
  57. << "\"Ranges\":[{"
  58. << "\"Name\": \"com.zerotier.controller.lfdb:" << controllerAddress << "/network\","
  59. << "\"Range\": [ 0,18446744073709551615 ]"
  60. << "}],"
  61. << "\"TimeRange\": [ " << timeRangeStart << ",18446744073709551615 ],"
  62. << "\"MaskingKey\":\"" << controllerAddress << "\","
  63. << "\"Owners\":[\"" << _lfOwnerPublic << "\"]"
  64. << '}';
  65. auto resp = htcli.Post("/query",query.str(),"application/json");
  66. if (resp->status == 200) {
  67. nlohmann::json results(OSUtils::jsonParse(resp->body));
  68. if ((results.is_array())&&(results.size() > 0)) {
  69. for(std::size_t ri=0;ri<results.size();++ri) {
  70. nlohmann::json &rset = results[ri];
  71. if ((rset.is_array())&&(rset.size() > 0)) {
  72. nlohmann::json &result = rset[0];
  73. if (result.is_object()) {
  74. nlohmann::json &record = result["Record"];
  75. if (record.is_object()) {
  76. int64_t ts = record["Timestamp"];
  77. std::string value = result["Value"];
  78. nlohmann::json network(OSUtils::jsonParse(value));
  79. if (network.is_object()) {
  80. std::string idstr = network["id"];
  81. }
  82. }
  83. }
  84. }
  85. }
  86. }
  87. } else {
  88. fprintf(stderr,"ERROR: LFDB: %d from node: %s" ZT_EOL_S,resp->status,resp->body.c_str());
  89. }
  90. query.clear();
  91. query
  92. << '{'
  93. << "\"Ranges\":[{"
  94. << "\"Name\": \"com.zerotier.controller.lfdb:" << controllerAddress << "/network\","
  95. << "\"Range\": [ 0,18446744073709551615 ]"
  96. << "},{"
  97. << "\"Name\": \"com.zerotier.controller.lfdb:" << controllerAddress << "/network/member\","
  98. << "\"Range\": [ 0,18446744073709551615 ]"
  99. << "}],"
  100. << "\"TimeRange\": [ " << timeRangeStart << ",18446744073709551615 ],"
  101. << "\"MaskingKey\":\"" << controllerAddress << "\","
  102. << "\"Owners\":[\"" << _lfOwnerPublic << "\"]"
  103. << '}';
  104. resp = htcli.Post("/query",query.str(),"application/json");
  105. if (resp->status == 200) {
  106. nlohmann::json results(OSUtils::jsonParse(resp->body));
  107. if ((results.is_array())&&(results.size() > 0)) {
  108. for(std::size_t ri=0;ri<results.size();++ri) {
  109. nlohmann::json &rset = results[ri];
  110. if ((rset.is_array())&&(rset.size() > 0)) {
  111. nlohmann::json &result = rset[0];
  112. if (result.is_object()) {
  113. nlohmann::json &record = result["Record"];
  114. if (record.is_object()) {
  115. int64_t ts = record["Timestamp"];
  116. std::string value = result["Value"];
  117. nlohmann::json member(OSUtils::jsonParse(value));
  118. if (member.is_object()) {
  119. std::string nwidstr = member["nwid"];
  120. std::string idstr = member["id"];
  121. }
  122. }
  123. }
  124. }
  125. }
  126. }
  127. } else {
  128. fprintf(stderr,"ERROR: LFDB: %d from node: %s" ZT_EOL_S,resp->status,resp->body.c_str());
  129. }
  130. timeRangeStart = time(nullptr) - 120; // start next query 2m before now to avoid losing updates
  131. _ready = true;
  132. // Delay 2s between queries, checking running flag every 100ms
  133. for(int k=0;k<20;++k) {
  134. if (!_running)
  135. return;
  136. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  137. }
  138. }
  139. });
  140. }
  141. LFDB::~LFDB()
  142. {
  143. _running = false;
  144. _syncThread.join();
  145. }
  146. bool LFDB::waitForReady()
  147. {
  148. while (!_ready) {
  149. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  150. }
  151. return true;
  152. }
  153. bool LFDB::isReady()
  154. {
  155. return (_ready);
  156. }
  157. void LFDB::save(nlohmann::json *orig,nlohmann::json &record)
  158. {
  159. if (orig) {
  160. if (*orig != record) {
  161. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  162. }
  163. } else {
  164. record["revision"] = 1;
  165. }
  166. const std::string objtype = record["objtype"];
  167. if (objtype == "network") {
  168. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  169. if (nwid) {
  170. nlohmann::json old;
  171. get(nwid,old);
  172. if ((!old.is_object())||(old != record)) {
  173. }
  174. }
  175. } else if (objtype == "member") {
  176. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  177. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  178. if ((id)&&(nwid)) {
  179. nlohmann::json network,old;
  180. get(nwid,network,id,old);
  181. if ((!old.is_object())||(old != record)) {
  182. }
  183. }
  184. }
  185. }
  186. void LFDB::eraseNetwork(const uint64_t networkId)
  187. {
  188. // TODO
  189. }
  190. void LFDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  191. {
  192. // TODO
  193. }
  194. void LFDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
  195. {
  196. std::lock_guard<std::mutex> l(_state_l);
  197. auto nw = _state.find(networkId);
  198. if (nw != _state.end()) {
  199. auto m = nw->second.members.find(memberId);
  200. if (m != nw->second.members.end()) {
  201. m->second.lastOnlineTime = OSUtils::now();
  202. if (physicalAddress)
  203. m->second.lastOnlineAddress = physicalAddress;
  204. m->second.lastOnlineDirty = true;
  205. }
  206. }
  207. }
  208. #if 0
  209. FileDB::FileDB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path) :
  210. DB(nc,myId,path),
  211. _networksPath(_path + ZT_PATH_SEPARATOR_S + "network"),
  212. _tracePath(_path + ZT_PATH_SEPARATOR_S + "trace"),
  213. _onlineChanged(false),
  214. _running(true)
  215. {
  216. OSUtils::mkdir(_path.c_str());
  217. OSUtils::lockDownFile(_path.c_str(),true);
  218. OSUtils::mkdir(_networksPath.c_str());
  219. OSUtils::mkdir(_tracePath.c_str());
  220. std::vector<std::string> networks(OSUtils::listDirectory(_networksPath.c_str(),false));
  221. std::string buf;
  222. for(auto n=networks.begin();n!=networks.end();++n) {
  223. buf.clear();
  224. if ((n->length() == 21)&&(OSUtils::readFile((_networksPath + ZT_PATH_SEPARATOR_S + *n).c_str(),buf))) {
  225. try {
  226. nlohmann::json network(OSUtils::jsonParse(buf));
  227. const std::string nwids = network["id"];
  228. if (nwids.length() == 16) {
  229. nlohmann::json nullJson;
  230. _networkChanged(nullJson,network,false);
  231. std::string membersPath(_networksPath + ZT_PATH_SEPARATOR_S + nwids + ZT_PATH_SEPARATOR_S "member");
  232. std::vector<std::string> members(OSUtils::listDirectory(membersPath.c_str(),false));
  233. for(auto m=members.begin();m!=members.end();++m) {
  234. buf.clear();
  235. if ((m->length() == 15)&&(OSUtils::readFile((membersPath + ZT_PATH_SEPARATOR_S + *m).c_str(),buf))) {
  236. try {
  237. nlohmann::json member(OSUtils::jsonParse(buf));
  238. const std::string addrs = member["id"];
  239. if (addrs.length() == 10) {
  240. nlohmann::json nullJson2;
  241. _memberChanged(nullJson2,member,false);
  242. }
  243. } catch ( ... ) {}
  244. }
  245. }
  246. }
  247. } catch ( ... ) {}
  248. }
  249. }
  250. _onlineUpdateThread = std::thread([this]() {
  251. unsigned int cnt = 0;
  252. while (this->_running) {
  253. std::this_thread::sleep_for(std::chrono::microseconds(100));
  254. if ((++cnt % 20) == 0) { // 5 seconds
  255. std::lock_guard<std::mutex> l(this->_online_l);
  256. if (!this->_running) return;
  257. if (this->_onlineChanged) {
  258. char p[4096],atmp[64];
  259. for(auto nw=this->_online.begin();nw!=this->_online.end();++nw) {
  260. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx-online.json",_networksPath.c_str(),(unsigned long long)nw->first);
  261. FILE *f = fopen(p,"wb");
  262. if (f) {
  263. fprintf(f,"{");
  264. const char *memberPrefix = "";
  265. for(auto m=nw->second.begin();m!=nw->second.end();++m) {
  266. fprintf(f,"%s\"%.10llx\":{" ZT_EOL_S,memberPrefix,(unsigned long long)m->first);
  267. memberPrefix = ",";
  268. InetAddress lastAddr;
  269. const char *timestampPrefix = " ";
  270. int cnt = 0;
  271. for(auto ts=m->second.rbegin();ts!=m->second.rend();) {
  272. if (cnt < 25) {
  273. if (lastAddr != ts->second) {
  274. lastAddr = ts->second;
  275. fprintf(f,"%s\"%lld\":\"%s\"" ZT_EOL_S,timestampPrefix,(long long)ts->first,ts->second.toString(atmp));
  276. timestampPrefix = ",";
  277. ++cnt;
  278. ++ts;
  279. } else {
  280. ts = std::map<int64_t,InetAddress>::reverse_iterator(m->second.erase(std::next(ts).base()));
  281. }
  282. } else {
  283. ts = std::map<int64_t,InetAddress>::reverse_iterator(m->second.erase(std::next(ts).base()));
  284. }
  285. }
  286. fprintf(f,"}");
  287. }
  288. fprintf(f,"}" ZT_EOL_S);
  289. fclose(f);
  290. }
  291. }
  292. this->_onlineChanged = false;
  293. }
  294. }
  295. }
  296. });
  297. }
  298. FileDB::~FileDB()
  299. {
  300. try {
  301. _online_l.lock();
  302. _running = false;
  303. _online_l.unlock();
  304. _onlineUpdateThread.join();
  305. } catch ( ... ) {}
  306. }
  307. bool FileDB::waitForReady() { return true; }
  308. bool FileDB::isReady() { return true; }
  309. void FileDB::save(nlohmann::json *orig,nlohmann::json &record)
  310. {
  311. char p1[4096],p2[4096],pb[4096];
  312. try {
  313. if (orig) {
  314. if (*orig != record) {
  315. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  316. }
  317. } else {
  318. record["revision"] = 1;
  319. }
  320. const std::string objtype = record["objtype"];
  321. if (objtype == "network") {
  322. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  323. if (nwid) {
  324. nlohmann::json old;
  325. get(nwid,old);
  326. if ((!old.is_object())||(old != record)) {
  327. OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json",_networksPath.c_str(),nwid);
  328. if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1)))
  329. fprintf(stderr,"WARNING: controller unable to write to path: %s" ZT_EOL_S,p1);
  330. _networkChanged(old,record,true);
  331. }
  332. }
  333. } else if (objtype == "member") {
  334. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  335. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  336. if ((id)&&(nwid)) {
  337. nlohmann::json network,old;
  338. get(nwid,network,id,old);
  339. if ((!old.is_object())||(old != record)) {
  340. OSUtils::ztsnprintf(pb,sizeof(pb),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member",_networksPath.c_str(),(unsigned long long)nwid);
  341. OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%.10llx.json",pb,(unsigned long long)id);
  342. if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1))) {
  343. OSUtils::ztsnprintf(p2,sizeof(p2),"%s" ZT_PATH_SEPARATOR_S "%.16llx",_networksPath.c_str(),(unsigned long long)nwid);
  344. OSUtils::mkdir(p2);
  345. OSUtils::mkdir(pb);
  346. if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1)))
  347. fprintf(stderr,"WARNING: controller unable to write to path: %s" ZT_EOL_S,p1);
  348. }
  349. _memberChanged(old,record,true);
  350. }
  351. }
  352. } else if (objtype == "trace") {
  353. const std::string id = record["id"];
  354. if (id.length() > 0) {
  355. OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%s.json",_tracePath.c_str(),id.c_str());
  356. OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1));
  357. }
  358. }
  359. } catch ( ... ) {} // drop invalid records missing fields
  360. }
  361. void FileDB::eraseNetwork(const uint64_t networkId)
  362. {
  363. nlohmann::json network,nullJson;
  364. get(networkId,network);
  365. char p[16384];
  366. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json",_networksPath.c_str(),networkId);
  367. OSUtils::rm(p);
  368. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx-online.json",_networksPath.c_str(),networkId);
  369. OSUtils::rm(p);
  370. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member",_networksPath.c_str(),(unsigned long long)networkId);
  371. OSUtils::rmDashRf(p);
  372. _networkChanged(network,nullJson,true);
  373. std::lock_guard<std::mutex> l(this->_online_l);
  374. this->_online.erase(networkId);
  375. this->_onlineChanged = true;
  376. }
  377. void FileDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  378. {
  379. nlohmann::json network,member,nullJson;
  380. get(networkId,network);
  381. get(memberId,member);
  382. char p[4096];
  383. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member" ZT_PATH_SEPARATOR_S "%.10llx.json",_networksPath.c_str(),networkId,memberId);
  384. OSUtils::rm(p);
  385. _memberChanged(member,nullJson,true);
  386. std::lock_guard<std::mutex> l(this->_online_l);
  387. this->_online[networkId].erase(memberId);
  388. this->_onlineChanged = true;
  389. }
  390. void FileDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
  391. {
  392. char mid[32],atmp[64];
  393. OSUtils::ztsnprintf(mid,sizeof(mid),"%.10llx",(unsigned long long)memberId);
  394. physicalAddress.toString(atmp);
  395. std::lock_guard<std::mutex> l(this->_online_l);
  396. this->_online[networkId][memberId][OSUtils::now()] = physicalAddress;
  397. this->_onlineChanged = true;
  398. }
  399. #endif
  400. } // namespace ZeroTier