LFDB.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. auto 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. }
  152. bool LFDB::isReady()
  153. {
  154. return (_ready);
  155. }
  156. void LFDB::save(nlohmann::json *orig,nlohmann::json &record)
  157. {
  158. if (orig) {
  159. if (*orig != record) {
  160. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  161. }
  162. } else {
  163. record["revision"] = 1;
  164. }
  165. const std::string objtype = record["objtype"];
  166. if (objtype == "network") {
  167. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  168. if (nwid) {
  169. nlohmann::json old;
  170. get(nwid,old);
  171. if ((!old.is_object())||(old != record)) {
  172. }
  173. }
  174. } else if (objtype == "member") {
  175. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  176. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  177. if ((id)&&(nwid)) {
  178. nlohmann::json network,old;
  179. get(nwid,network,id,old);
  180. if ((!old.is_object())||(old != record)) {
  181. }
  182. }
  183. }
  184. }
  185. void LFDB::eraseNetwork(const uint64_t networkId)
  186. {
  187. // TODO
  188. }
  189. void LFDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  190. {
  191. // TODO
  192. }
  193. void LFDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
  194. {
  195. std::lock_guard<std::mutex> l(_state_l);
  196. auto nw = _state.find(networkId);
  197. if (nw != _state.end()) {
  198. auto m = nw->second.members.find(memberId);
  199. if (m != nw->second.members.end()) {
  200. m->second.lastOnlineTime = OSUtils::now();
  201. if (physicalAddress)
  202. m->second.lastOnlineAddress = physicalAddress;
  203. m->second.lastOnlineDirty = true;
  204. }
  205. }
  206. }
  207. #if 0
  208. FileDB::FileDB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path) :
  209. DB(nc,myId,path),
  210. _networksPath(_path + ZT_PATH_SEPARATOR_S + "network"),
  211. _tracePath(_path + ZT_PATH_SEPARATOR_S + "trace"),
  212. _onlineChanged(false),
  213. _running(true)
  214. {
  215. OSUtils::mkdir(_path.c_str());
  216. OSUtils::lockDownFile(_path.c_str(),true);
  217. OSUtils::mkdir(_networksPath.c_str());
  218. OSUtils::mkdir(_tracePath.c_str());
  219. std::vector<std::string> networks(OSUtils::listDirectory(_networksPath.c_str(),false));
  220. std::string buf;
  221. for(auto n=networks.begin();n!=networks.end();++n) {
  222. buf.clear();
  223. if ((n->length() == 21)&&(OSUtils::readFile((_networksPath + ZT_PATH_SEPARATOR_S + *n).c_str(),buf))) {
  224. try {
  225. nlohmann::json network(OSUtils::jsonParse(buf));
  226. const std::string nwids = network["id"];
  227. if (nwids.length() == 16) {
  228. nlohmann::json nullJson;
  229. _networkChanged(nullJson,network,false);
  230. std::string membersPath(_networksPath + ZT_PATH_SEPARATOR_S + nwids + ZT_PATH_SEPARATOR_S "member");
  231. std::vector<std::string> members(OSUtils::listDirectory(membersPath.c_str(),false));
  232. for(auto m=members.begin();m!=members.end();++m) {
  233. buf.clear();
  234. if ((m->length() == 15)&&(OSUtils::readFile((membersPath + ZT_PATH_SEPARATOR_S + *m).c_str(),buf))) {
  235. try {
  236. nlohmann::json member(OSUtils::jsonParse(buf));
  237. const std::string addrs = member["id"];
  238. if (addrs.length() == 10) {
  239. nlohmann::json nullJson2;
  240. _memberChanged(nullJson2,member,false);
  241. }
  242. } catch ( ... ) {}
  243. }
  244. }
  245. }
  246. } catch ( ... ) {}
  247. }
  248. }
  249. _onlineUpdateThread = std::thread([this]() {
  250. unsigned int cnt = 0;
  251. while (this->_running) {
  252. std::this_thread::sleep_for(std::chrono::microseconds(100));
  253. if ((++cnt % 20) == 0) { // 5 seconds
  254. std::lock_guard<std::mutex> l(this->_online_l);
  255. if (!this->_running) return;
  256. if (this->_onlineChanged) {
  257. char p[4096],atmp[64];
  258. for(auto nw=this->_online.begin();nw!=this->_online.end();++nw) {
  259. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx-online.json",_networksPath.c_str(),(unsigned long long)nw->first);
  260. FILE *f = fopen(p,"wb");
  261. if (f) {
  262. fprintf(f,"{");
  263. const char *memberPrefix = "";
  264. for(auto m=nw->second.begin();m!=nw->second.end();++m) {
  265. fprintf(f,"%s\"%.10llx\":{" ZT_EOL_S,memberPrefix,(unsigned long long)m->first);
  266. memberPrefix = ",";
  267. InetAddress lastAddr;
  268. const char *timestampPrefix = " ";
  269. int cnt = 0;
  270. for(auto ts=m->second.rbegin();ts!=m->second.rend();) {
  271. if (cnt < 25) {
  272. if (lastAddr != ts->second) {
  273. lastAddr = ts->second;
  274. fprintf(f,"%s\"%lld\":\"%s\"" ZT_EOL_S,timestampPrefix,(long long)ts->first,ts->second.toString(atmp));
  275. timestampPrefix = ",";
  276. ++cnt;
  277. ++ts;
  278. } else {
  279. ts = std::map<int64_t,InetAddress>::reverse_iterator(m->second.erase(std::next(ts).base()));
  280. }
  281. } else {
  282. ts = std::map<int64_t,InetAddress>::reverse_iterator(m->second.erase(std::next(ts).base()));
  283. }
  284. }
  285. fprintf(f,"}");
  286. }
  287. fprintf(f,"}" ZT_EOL_S);
  288. fclose(f);
  289. }
  290. }
  291. this->_onlineChanged = false;
  292. }
  293. }
  294. }
  295. });
  296. }
  297. FileDB::~FileDB()
  298. {
  299. try {
  300. _online_l.lock();
  301. _running = false;
  302. _online_l.unlock();
  303. _onlineUpdateThread.join();
  304. } catch ( ... ) {}
  305. }
  306. bool FileDB::waitForReady() { return true; }
  307. bool FileDB::isReady() { return true; }
  308. void FileDB::save(nlohmann::json *orig,nlohmann::json &record)
  309. {
  310. char p1[4096],p2[4096],pb[4096];
  311. try {
  312. if (orig) {
  313. if (*orig != record) {
  314. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  315. }
  316. } else {
  317. record["revision"] = 1;
  318. }
  319. const std::string objtype = record["objtype"];
  320. if (objtype == "network") {
  321. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  322. if (nwid) {
  323. nlohmann::json old;
  324. get(nwid,old);
  325. if ((!old.is_object())||(old != record)) {
  326. OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json",_networksPath.c_str(),nwid);
  327. if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1)))
  328. fprintf(stderr,"WARNING: controller unable to write to path: %s" ZT_EOL_S,p1);
  329. _networkChanged(old,record,true);
  330. }
  331. }
  332. } else if (objtype == "member") {
  333. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  334. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  335. if ((id)&&(nwid)) {
  336. nlohmann::json network,old;
  337. get(nwid,network,id,old);
  338. if ((!old.is_object())||(old != record)) {
  339. OSUtils::ztsnprintf(pb,sizeof(pb),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member",_networksPath.c_str(),(unsigned long long)nwid);
  340. OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%.10llx.json",pb,(unsigned long long)id);
  341. if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1))) {
  342. OSUtils::ztsnprintf(p2,sizeof(p2),"%s" ZT_PATH_SEPARATOR_S "%.16llx",_networksPath.c_str(),(unsigned long long)nwid);
  343. OSUtils::mkdir(p2);
  344. OSUtils::mkdir(pb);
  345. if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1)))
  346. fprintf(stderr,"WARNING: controller unable to write to path: %s" ZT_EOL_S,p1);
  347. }
  348. _memberChanged(old,record,true);
  349. }
  350. }
  351. } else if (objtype == "trace") {
  352. const std::string id = record["id"];
  353. if (id.length() > 0) {
  354. OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%s.json",_tracePath.c_str(),id.c_str());
  355. OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1));
  356. }
  357. }
  358. } catch ( ... ) {} // drop invalid records missing fields
  359. }
  360. void FileDB::eraseNetwork(const uint64_t networkId)
  361. {
  362. nlohmann::json network,nullJson;
  363. get(networkId,network);
  364. char p[16384];
  365. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json",_networksPath.c_str(),networkId);
  366. OSUtils::rm(p);
  367. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx-online.json",_networksPath.c_str(),networkId);
  368. OSUtils::rm(p);
  369. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member",_networksPath.c_str(),(unsigned long long)networkId);
  370. OSUtils::rmDashRf(p);
  371. _networkChanged(network,nullJson,true);
  372. std::lock_guard<std::mutex> l(this->_online_l);
  373. this->_online.erase(networkId);
  374. this->_onlineChanged = true;
  375. }
  376. void FileDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  377. {
  378. nlohmann::json network,member,nullJson;
  379. get(networkId,network);
  380. get(memberId,member);
  381. char p[4096];
  382. 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);
  383. OSUtils::rm(p);
  384. _memberChanged(member,nullJson,true);
  385. std::lock_guard<std::mutex> l(this->_online_l);
  386. this->_online[networkId].erase(memberId);
  387. this->_onlineChanged = true;
  388. }
  389. void FileDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
  390. {
  391. char mid[32],atmp[64];
  392. OSUtils::ztsnprintf(mid,sizeof(mid),"%.10llx",(unsigned long long)memberId);
  393. physicalAddress.toString(atmp);
  394. std::lock_guard<std::mutex> l(this->_online_l);
  395. this->_online[networkId][memberId][OSUtils::now()] = physicalAddress;
  396. this->_onlineChanged = true;
  397. }
  398. #endif
  399. } // namespace ZeroTier