ReachabilityCollector.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "crypto/AddressCalc.h"
  16. #include "dht/dhtcore/ReplySerializer.h"
  17. #include "subnode/ReachabilityCollector.h"
  18. #include "util/log/Log.h"
  19. #include "util/Identity.h"
  20. #include "util/events/Timeout.h"
  21. #include "util/AddrTools.h"
  22. #include "util/events/Time.h"
  23. #include <stdbool.h>
  24. #define TIMEOUT_MILLISECONDS 10000
  25. struct PeerInfo_pvt
  26. {
  27. struct ReachabilityCollector_PeerInfo pub;
  28. // Next path to check when sending getPeers requests to our peer looking for ourselves.
  29. uint64_t pathToCheck;
  30. // For this 10 second period
  31. uint32_t sumOfLag;
  32. uint32_t lagSamples;
  33. uint32_t timeOfLastLagUpdate;
  34. uint32_t sumOfDropsLastSlot;
  35. uint32_t sumOfPacketsLastSlot;
  36. uint32_t sumOfKbLastSlot;
  37. uint32_t sumOfDrops;
  38. uint32_t sumOfPackets;
  39. uint32_t sumOfKb;
  40. // This peer is waiting for response
  41. bool waitForResponse;
  42. struct Allocator* alloc;
  43. Identity
  44. };
  45. #define ArrayList_NAME OfPeerInfo_pvt
  46. #define ArrayList_TYPE struct PeerInfo_pvt
  47. #include "util/ArrayList.h"
  48. struct ReachabilityCollector_pvt
  49. {
  50. struct ReachabilityCollector pub;
  51. struct MsgCore* msgCore;
  52. struct Allocator* alloc;
  53. struct Log* log;
  54. struct BoilerplateResponder* br;
  55. struct Address* myAddr;
  56. struct EventBase* base;
  57. struct EncodingScheme* myScheme;
  58. uint32_t resampleCycle;
  59. uint32_t linkStateSamples;
  60. struct ArrayList_OfPeerInfo_pvt* piList;
  61. Identity
  62. };
  63. static struct PeerInfo_pvt* piForLabel(struct ReachabilityCollector_pvt* rcp, uint64_t label)
  64. {
  65. for (int j = 0; j < rcp->piList->length; j++) {
  66. struct PeerInfo_pvt* pi0 = ArrayList_OfPeerInfo_pvt_get(rcp->piList, j);
  67. if (pi0->pub.addr.path == label) { return pi0; }
  68. }
  69. return NULL;
  70. }
  71. static void mkNextRequest(struct ReachabilityCollector_pvt* rcp);
  72. static void change0(struct ReachabilityCollector_pvt* rcp,
  73. struct Address* nodeAddr,
  74. struct Allocator* tempAlloc)
  75. {
  76. for (int i = 0; i < rcp->piList->length; i++) {
  77. struct PeerInfo_pvt* pi = ArrayList_OfPeerInfo_pvt_get(rcp->piList, i);
  78. if (!Address_isSameIp(nodeAddr, &pi->pub.addr)) { continue; }
  79. if (nodeAddr->path == 0) {
  80. Log_debug(rcp->log, "Peer [%s] dropped",
  81. Address_toString(&pi->pub.addr, tempAlloc)->bytes);
  82. ArrayList_OfPeerInfo_pvt_remove(rcp->piList, i);
  83. Allocator_free(pi->alloc);
  84. rcp->pub.onChange(&rcp->pub, nodeAddr->ip6.bytes, NULL);
  85. } else if (nodeAddr->path != pi->pub.addr.path) {
  86. Log_debug(rcp->log, "Peer [%s] changed path",
  87. Address_toString(&pi->pub.addr, tempAlloc)->bytes);
  88. pi->pub.pathThemToUs = -1;
  89. pi->pathToCheck = 1;
  90. pi->pub.querying = true;
  91. pi->pub.addr.path = nodeAddr->path;
  92. pi->pub.linkState.nodeId = EncodingScheme_parseDirector(rcp->myScheme, nodeAddr->path);
  93. //rcp->pub.onChange(
  94. // &rcp->pub, nodeAddr->ip6.bytes, pi->pub.pathThemToUs, nodeAddr->path);
  95. // Lets leave the peer in the list as working, our path to it changed
  96. // but it's path to us didn't necessarily change.
  97. } else {
  98. Log_debug(rcp->log, "Peer [%s] message, peer already registered",
  99. Address_toString(&pi->pub.addr, tempAlloc)->bytes);
  100. }
  101. return;
  102. }
  103. if (nodeAddr->path == 0) {
  104. Log_debug(rcp->log, "Nonexistant peer [%s] dropped",
  105. Address_toString(nodeAddr, tempAlloc)->bytes);
  106. return;
  107. }
  108. struct Allocator* piAlloc = Allocator_child(rcp->alloc);
  109. struct PeerInfo_pvt* pi = Allocator_calloc(piAlloc, sizeof(struct PeerInfo_pvt), 1);
  110. Identity_set(pi);
  111. Bits_memcpy(&pi->pub.addr, nodeAddr, Address_SIZE);
  112. pi->alloc = piAlloc;
  113. pi->pub.querying = true;
  114. pi->pathToCheck = 1;
  115. pi->pub.pathThemToUs = -1;
  116. pi->waitForResponse = false;
  117. pi->pub.linkState.nodeId = EncodingScheme_parseDirector(rcp->myScheme, nodeAddr->path);
  118. ArrayList_OfPeerInfo_pvt_add(rcp->piList, pi);
  119. Log_debug(rcp->log, "Peer [%s] added", Address_toString(&pi->pub.addr, tempAlloc)->bytes);
  120. mkNextRequest(rcp);
  121. }
  122. void ReachabilityCollector_change(struct ReachabilityCollector* rc, struct Address* nodeAddr)
  123. {
  124. struct ReachabilityCollector_pvt* rcp = Identity_check((struct ReachabilityCollector_pvt*) rc);
  125. struct Allocator* tempAlloc = Allocator_child(rcp->alloc);
  126. change0(rcp, nodeAddr, tempAlloc);
  127. Allocator_free(tempAlloc);
  128. }
  129. struct Query {
  130. struct ReachabilityCollector_pvt* rcp;
  131. String* addr;
  132. uint8_t targetPath[20];
  133. };
  134. static void onReplyTimeout(struct MsgCore_Promise* prom)
  135. {
  136. struct Query* q = (struct Query*) prom->userData;
  137. struct ReachabilityCollector_pvt* rcp =
  138. Identity_check((struct ReachabilityCollector_pvt*) q->rcp);
  139. struct PeerInfo_pvt* pi = NULL;
  140. for (int j = 0; j < rcp->piList->length; j++) {
  141. pi = ArrayList_OfPeerInfo_pvt_get(rcp->piList, j);
  142. if (Address_isSameIp(&pi->pub.addr, prom->target)) {
  143. pi->waitForResponse = false;
  144. return;
  145. }
  146. }
  147. }
  148. static void latencyUpdate(
  149. struct ReachabilityCollector_pvt* rcp,
  150. struct PeerInfo_pvt* pip,
  151. uint32_t lag)
  152. {
  153. Log_debug(rcp->log, "Latency update for [%" PRIx64 "] [%u]ms", pip->pub.addr.path, lag);
  154. pip->sumOfLag += lag;
  155. pip->lagSamples++;
  156. pip->timeOfLastLagUpdate = Time_currentTimeMilliseconds(rcp->base);
  157. }
  158. static void onReply(Dict* msg, struct Address* src, struct MsgCore_Promise* prom)
  159. {
  160. struct Query* q = (struct Query*) prom->userData;
  161. struct ReachabilityCollector_pvt* rcp =
  162. Identity_check((struct ReachabilityCollector_pvt*) q->rcp);
  163. if (!src) {
  164. onReplyTimeout(prom);
  165. mkNextRequest(rcp);
  166. return;
  167. }
  168. struct PeerInfo_pvt* pi = NULL;
  169. for (int j = 0; j < rcp->piList->length; j++) {
  170. struct PeerInfo_pvt* pi0 = ArrayList_OfPeerInfo_pvt_get(rcp->piList, j);
  171. if (Address_isSameIp(&pi0->pub.addr, src)) {
  172. pi = pi0;
  173. break;
  174. }
  175. }
  176. if (!pi) {
  177. Log_debug(rcp->log, "Got message from peer which is gone from list");
  178. return;
  179. }
  180. latencyUpdate(rcp, pi, prom->lag);
  181. pi->waitForResponse = false;
  182. struct Address_List* results = ReplySerializer_parse(src, msg, rcp->log, false, prom->alloc);
  183. uint64_t path = 1;
  184. if (!results) {
  185. Log_debug(rcp->log, "Got invalid getPeers reply from [%s]",
  186. Address_toString(src, prom->alloc)->bytes);
  187. return;
  188. }
  189. for (int i = results->length - 1; i >= 0; i--) {
  190. path = results->elems[i].path;
  191. Log_debug(rcp->log, "getPeers result [%s] [%s][%s]",
  192. Address_toString(&results->elems[i], prom->alloc)->bytes,
  193. q->addr->bytes, q->targetPath);
  194. if (Bits_memcmp(results->elems[i].ip6.bytes, rcp->myAddr->ip6.bytes, 16)) { continue; }
  195. if (pi->pub.pathThemToUs != path) {
  196. Log_debug(rcp->log, "Found back-route for [%s]",
  197. Address_toString(src, prom->alloc)->bytes);
  198. pi->pub.pathThemToUs = path;
  199. rcp->pub.onChange(&rcp->pub, src->ip6.bytes, &pi->pub);
  200. }
  201. pi->pub.querying = false;
  202. mkNextRequest(rcp);
  203. return;
  204. }
  205. if (results->length < 8) {
  206. // Peer's gp response does not include my addr, meaning the peer might not know us yet.
  207. // should wait peer sendPing (see InterfaceControl.c).
  208. pi->pathToCheck = 1;
  209. return;
  210. } else {
  211. pi->pathToCheck = path;
  212. }
  213. mkNextRequest(rcp);
  214. }
  215. static void queryPeer(struct ReachabilityCollector_pvt* rcp, struct PeerInfo_pvt* pi)
  216. {
  217. struct MsgCore_Promise* query =
  218. MsgCore_createQuery(rcp->msgCore, TIMEOUT_MILLISECONDS, rcp->alloc);
  219. struct Query* q = Allocator_calloc(query->alloc, sizeof(struct Query), 1);
  220. q->rcp = rcp;
  221. q->addr = Address_toString(&pi->pub.addr, query->alloc);
  222. query->userData = q;
  223. query->cb = onReply;
  224. Assert_true(AddressCalc_validAddress(pi->pub.addr.ip6.bytes));
  225. query->target = Address_clone(&pi->pub.addr, query->alloc);
  226. Assert_true(pi->pub.addr.path);
  227. Dict* d = query->msg = Dict_new(query->alloc);
  228. Dict_putStringCC(d, "q", "gp", query->alloc);
  229. uint64_t label_be = Endian_hostToBigEndian64(pi->pathToCheck);
  230. uint8_t nearbyLabelBytes[8];
  231. Bits_memcpy(nearbyLabelBytes, &label_be, 8);
  232. AddrTools_printPath(q->targetPath, pi->pathToCheck);
  233. Log_debug(rcp->log, "Getting peers for peer [%s] tar [%s]", q->addr->bytes, q->targetPath);
  234. Dict_putStringC(d, "tar",
  235. String_newBinary(nearbyLabelBytes, 8, query->alloc), query->alloc);
  236. BoilerplateResponder_addBoilerplate(rcp->br, d, &pi->pub.addr, query->alloc);
  237. pi->waitForResponse = true;
  238. }
  239. static void mkNextRequest(struct ReachabilityCollector_pvt* rcp)
  240. {
  241. struct PeerInfo_pvt* pi = NULL;
  242. for (int i = 0; i < rcp->piList->length; i++) {
  243. pi = ArrayList_OfPeerInfo_pvt_get(rcp->piList, i);
  244. if (pi->pub.querying && !pi->waitForResponse) { break; }
  245. }
  246. if (!pi || !pi->pub.querying) {
  247. Log_debug(rcp->log, "All [%u] peers have been queried", rcp->piList->length);
  248. return;
  249. }
  250. if (pi->waitForResponse) {
  251. Log_debug(rcp->log, "Peer is waiting for response.");
  252. return;
  253. }
  254. queryPeer(rcp, pi);
  255. }
  256. static void cycle(void* vrc)
  257. {
  258. struct ReachabilityCollector_pvt* rcp = Identity_check((struct ReachabilityCollector_pvt*) vrc);
  259. mkNextRequest(rcp);
  260. // 10 second window is cut into 5 intervals
  261. // second 0, 2, 4, 6, 8
  262. // number 1, 2, 3, 4, 5
  263. // in number 4, we will ping any peer who has not received one yet to get latency
  264. // in number 5, we will collect everything back
  265. rcp->resampleCycle++;
  266. if (rcp->resampleCycle < 4) { return; }
  267. for (int j = 0; j < rcp->piList->length; j++) {
  268. struct PeerInfo_pvt* pi = ArrayList_OfPeerInfo_pvt_get(rcp->piList, j);
  269. Log_debug(rcp->log, "Visiting peer [%" PRIx64 "] samples [%u]",
  270. pi->pub.addr.path, pi->lagSamples);
  271. if (pi->lagSamples == 0) {
  272. Log_debug(rcp->log, "Triggering a ping to peer [%" PRIx64 "]", pi->pub.addr.path);
  273. queryPeer(rcp, pi);
  274. }
  275. if (rcp->resampleCycle < 5) { continue; }
  276. int sampleNum = rcp->linkStateSamples % LinkState_SLOTS;
  277. uint64_t drops = pi->sumOfDrops - pi->sumOfDropsLastSlot;
  278. uint64_t packets = pi->sumOfPackets - pi->sumOfPacketsLastSlot;
  279. uint64_t dropRateShl18 = packets ? (drops << 18) / packets : 0;
  280. pi->pub.linkState.dropSlots[sampleNum] = dropRateShl18 > 0xfffe ? 0xfffe : dropRateShl18;
  281. pi->sumOfDropsLastSlot = pi->sumOfDrops;
  282. pi->pub.linkState.kbRecvSlots[sampleNum] = pi->sumOfKb - pi->sumOfKbLastSlot;
  283. pi->sumOfKbLastSlot = pi->sumOfKb;
  284. pi->pub.linkState.lagSlots[sampleNum] = pi->lagSamples ? pi->sumOfLag / pi->lagSamples : 0;
  285. pi->sumOfLag = 0;
  286. pi->lagSamples = 0;
  287. pi->pub.linkState.samples = rcp->linkStateSamples + 1;
  288. }
  289. if (rcp->resampleCycle >= 5) {
  290. rcp->resampleCycle = 0;
  291. rcp->linkStateSamples++;
  292. }
  293. }
  294. struct ReachabilityCollector_PeerInfo*
  295. ReachabilityCollector_getPeerInfo(struct ReachabilityCollector* rc, int peerNum)
  296. {
  297. struct ReachabilityCollector_pvt* rcp = Identity_check((struct ReachabilityCollector_pvt*) rc);
  298. struct PeerInfo_pvt* pi = ArrayList_OfPeerInfo_pvt_get(rcp->piList, peerNum);
  299. return pi ? &pi->pub : NULL;
  300. }
  301. void ReachabilityCollector_lagSample(
  302. struct ReachabilityCollector* rc, uint64_t label, uint32_t milliseconds)
  303. {
  304. struct ReachabilityCollector_pvt* rcp = Identity_check((struct ReachabilityCollector_pvt*) rc);
  305. struct PeerInfo_pvt* pi = piForLabel(rcp, label);
  306. if (!pi) { return; }
  307. latencyUpdate(rcp, pi, milliseconds);
  308. }
  309. void ReachabilityCollector_updateBandwidthAndDrops(
  310. struct ReachabilityCollector* rc,
  311. uint64_t label,
  312. uint32_t sumOfPackets,
  313. uint32_t sumOfDrops,
  314. uint32_t sumOfKb)
  315. {
  316. struct ReachabilityCollector_pvt* rcp = Identity_check((struct ReachabilityCollector_pvt*) rc);
  317. struct PeerInfo_pvt* pi = piForLabel(rcp, label);
  318. if (!pi) { return; }
  319. pi->sumOfPackets = sumOfPackets;
  320. pi->sumOfDrops = sumOfDrops;
  321. pi->sumOfKb = sumOfKb;
  322. }
  323. static void dummyOnChange(
  324. struct ReachabilityCollector* rc,
  325. uint8_t nodeIpv6[16],
  326. struct ReachabilityCollector_PeerInfo* pi)
  327. {
  328. struct ReachabilityCollector_pvt* rcp = Identity_check((struct ReachabilityCollector_pvt*) rc);
  329. Log_debug(rcp->log, "dummyOnChange called, onChange unassigned");
  330. }
  331. struct ReachabilityCollector* ReachabilityCollector_new(struct Allocator* allocator,
  332. struct MsgCore* msgCore,
  333. struct Log* log,
  334. struct EventBase* base,
  335. struct BoilerplateResponder* br,
  336. struct Address* myAddr,
  337. struct EncodingScheme* myScheme)
  338. {
  339. struct Allocator* alloc = Allocator_child(allocator);
  340. struct ReachabilityCollector_pvt* rcp =
  341. Allocator_calloc(alloc, sizeof(struct ReachabilityCollector_pvt), 1);
  342. rcp->myAddr = myAddr;
  343. rcp->msgCore = msgCore;
  344. rcp->alloc = alloc;
  345. rcp->piList = ArrayList_OfPeerInfo_pvt_new(alloc);
  346. rcp->log = log;
  347. rcp->br = br;
  348. rcp->base = base;
  349. rcp->pub.onChange = dummyOnChange;
  350. rcp->myScheme = myScheme;
  351. Identity_set(rcp);
  352. Timeout_setInterval(cycle, rcp, 2000, base, alloc);
  353. return &rcp->pub;
  354. }