Bond.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <cmath>
  14. #include "Peer.hpp"
  15. #include "Bond.hpp"
  16. #include "Switch.hpp"
  17. #include "Flow.hpp"
  18. #include "Path.hpp"
  19. namespace ZeroTier {
  20. Bond::Bond(const RuntimeEnvironment *renv, int policy, const SharedPtr<Peer>& peer) :
  21. RR(renv),
  22. _peer(peer)
  23. {
  24. // TODO: Remove for production
  25. _header=false;
  26. _lastLogTS = RR->node->now();
  27. _lastPrintTS = RR->node->now();
  28. setReasonableDefaults(policy, SharedPtr<Bond>(), false);
  29. _policyAlias = BondController::getPolicyStrByCode(policy);
  30. }
  31. Bond::Bond(const RuntimeEnvironment *renv, std::string& basePolicy, std::string& policyAlias, const SharedPtr<Peer>& peer) :
  32. RR(renv),
  33. _policyAlias(policyAlias),
  34. _peer(peer)
  35. {
  36. setReasonableDefaults(BondController::getPolicyCodeByStr(basePolicy), SharedPtr<Bond>(), false);
  37. }
  38. Bond::Bond(const RuntimeEnvironment *renv, SharedPtr<Bond> originalBond, const SharedPtr<Peer>& peer) :
  39. RR(renv),
  40. _peer(peer)
  41. {
  42. // TODO: Remove for production
  43. _header=false;
  44. _lastLogTS = RR->node->now();
  45. _lastPrintTS = RR->node->now();
  46. setReasonableDefaults(originalBond->_bondingPolicy, originalBond, true);
  47. }
  48. void Bond::nominatePath(const SharedPtr<Path>& path, int64_t now)
  49. {
  50. char pathStr[128];path->address().toString(pathStr);fprintf(stderr, "nominatePath: %s %s\n", getLink(path)->ifname().c_str(), pathStr);
  51. Mutex::Lock _l(_paths_m);
  52. if (!RR->bc->linkAllowed(_policyAlias, getLink(path))) {
  53. return;
  54. }
  55. bool alreadyPresent = false;
  56. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  57. if (path.ptr() == _paths[i].ptr()) {
  58. fprintf(stderr, "previously encountered path, not notifying bond (%s)\n", pathStr);
  59. alreadyPresent = true;
  60. break;
  61. }
  62. }
  63. if (!alreadyPresent) {
  64. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  65. if (!_paths[i]) {
  66. fprintf(stderr, "notifyOfNewPath(): Setting path %s to idx=%d\n", pathStr, i);
  67. _paths[i] = path;
  68. //_paths[i]->link = RR->bc->getLinkBySocket(_policyAlias, path->localSocket());
  69. _paths[i]->startTrial(now);
  70. break;
  71. }
  72. }
  73. }
  74. curateBond(now, true);
  75. estimatePathQuality(now);
  76. }
  77. SharedPtr<Path> Bond::getAppropriatePath(int64_t now, int32_t flowId)
  78. {
  79. Mutex::Lock _l(_paths_m);
  80. /**
  81. * active-backup
  82. */
  83. if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  84. if (_abPath) {
  85. return _abPath;
  86. }
  87. }
  88. /**
  89. * broadcast
  90. */
  91. if (_bondingPolicy == ZT_BONDING_POLICY_BROADCAST) {
  92. return SharedPtr<Path>(); // Handled in Switch::_trySend()
  93. }
  94. if (!_numBondedPaths) {
  95. return SharedPtr<Path>(); // No paths assigned to bond yet, cannot balance traffic
  96. }
  97. /**
  98. * balance-rr
  99. */
  100. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR) {
  101. if (!_allowFlowHashing) {
  102. //fprintf(stderr, "_rrPacketsSentOnCurrLink=%d, _numBondedPaths=%d, _rrIdx=%d\n", _rrPacketsSentOnCurrLink, _numBondedPaths, _rrIdx);
  103. if (_packetsPerLink == 0) {
  104. // Randomly select a path
  105. return _paths[_bondedIdx[_freeRandomByte % _numBondedPaths]]; // TODO: Optimize
  106. }
  107. if (_rrPacketsSentOnCurrLink < _packetsPerLink) {
  108. // Continue to use this link
  109. ++_rrPacketsSentOnCurrLink;
  110. return _paths[_bondedIdx[_rrIdx]];
  111. }
  112. // Reset striping counter
  113. _rrPacketsSentOnCurrLink = 0;
  114. if (_numBondedPaths == 1) {
  115. _rrIdx = 0;
  116. }
  117. else {
  118. int _tempIdx = _rrIdx;
  119. for (int searchCount = 0; searchCount < (_numBondedPaths-1); searchCount++) {
  120. _tempIdx = (_tempIdx == (_numBondedPaths-1)) ? 0 : _tempIdx+1;
  121. if (_bondedIdx[_tempIdx] != ZT_MAX_PEER_NETWORK_PATHS) {
  122. if (_paths[_bondedIdx[_tempIdx]] && _paths[_bondedIdx[_tempIdx]]->eligible(now,_ackSendInterval)) {
  123. _rrIdx = _tempIdx;
  124. break;
  125. }
  126. }
  127. }
  128. }
  129. if (_paths[_bondedIdx[_rrIdx]]) {
  130. return _paths[_bondedIdx[_rrIdx]];
  131. }
  132. }
  133. }
  134. /**
  135. * balance-xor
  136. */
  137. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  138. if (!_allowFlowHashing || flowId == -1) {
  139. // No specific path required for unclassified traffic, send on anything
  140. return _paths[_bondedIdx[_freeRandomByte % _numBondedPaths]]; // TODO: Optimize
  141. }
  142. else if (_allowFlowHashing) {
  143. // TODO: Optimize
  144. Mutex::Lock _l(_flows_m);
  145. SharedPtr<Flow> flow;
  146. if (_flows.count(flowId)) {
  147. flow = _flows[flowId];
  148. flow->updateActivity(now);
  149. }
  150. else {
  151. unsigned char entropy;
  152. Utils::getSecureRandom(&entropy, 1);
  153. flow = createFlow(SharedPtr<Path>(), flowId, entropy, now);
  154. }
  155. if (flow) {
  156. return flow->assignedPath();
  157. }
  158. }
  159. }
  160. return SharedPtr<Path>();
  161. }
  162. void Bond::recordIncomingInvalidPacket(const SharedPtr<Path>& path)
  163. {
  164. // char pathStr[128];path->address().toString(pathStr);fprintf(stderr, "recordIncomingInvalidPacket() %s %s\n", getLink(path)->ifname().c_str(), pathStr);
  165. Mutex::Lock _l(_paths_m);
  166. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  167. if (_paths[i] == path) {
  168. _paths[i]->packetValiditySamples.push(false);
  169. }
  170. }
  171. }
  172. void Bond::recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  173. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  174. {
  175. // char pathStr[128];path->address().toString(pathStr);fprintf(stderr, "recordOutgoingPacket() %s %s, packetId=%llx, payloadLength=%d, verb=%x, flowId=%lx\n", getLink(path)->ifname().c_str(), pathStr, packetId, payloadLength, verb, flowId);
  176. _freeRandomByte += (unsigned char)(packetId >> 8); // Grab entropy to use in path selection logic
  177. if (!_shouldCollectPathStatistics) {
  178. return;
  179. }
  180. bool isFrame = (verb == Packet::VERB_FRAME || verb == Packet::VERB_EXT_FRAME);
  181. bool shouldRecord = (packetId & (ZT_QOS_ACK_DIVISOR - 1)
  182. && (verb != Packet::VERB_ACK)
  183. && (verb != Packet::VERB_QOS_MEASUREMENT));
  184. if (isFrame || shouldRecord) {
  185. Mutex::Lock _l(_paths_m);
  186. if (isFrame) {
  187. ++(path->_packetsOut);
  188. _lastFrame=now;
  189. }
  190. if (shouldRecord) {
  191. path->_unackedBytes += payloadLength;
  192. // Take note that we're expecting a VERB_ACK on this path as of a specific time
  193. if (path->qosStatsOut.size() < ZT_QOS_MAX_OUTSTANDING_RECORDS) {
  194. path->qosStatsOut[packetId] = now;
  195. }
  196. }
  197. }
  198. if (_allowFlowHashing) {
  199. if (_allowFlowHashing && (flowId != ZT_QOS_NO_FLOW)) {
  200. Mutex::Lock _l(_flows_m);
  201. if (_flows.count(flowId)) {
  202. _flows[flowId]->recordOutgoingBytes(payloadLength);
  203. }
  204. }
  205. }
  206. }
  207. void Bond::recordIncomingPacket(const SharedPtr<Path>& path, uint64_t packetId, uint16_t payloadLength,
  208. Packet::Verb verb, int32_t flowId, int64_t now)
  209. {
  210. //char pathStr[128];path->address().toString(pathStr);fprintf(stderr, "recordIncomingPacket() %s %s, packetId=%llx, payloadLength=%d, verb=%x, flowId=%lx\n", getLink(path)->ifname().c_str(), pathStr, packetId, payloadLength, verb, flowId);
  211. bool isFrame = (verb == Packet::VERB_FRAME || verb == Packet::VERB_EXT_FRAME);
  212. bool shouldRecord = (packetId & (ZT_QOS_ACK_DIVISOR - 1)
  213. && (verb != Packet::VERB_ACK)
  214. && (verb != Packet::VERB_QOS_MEASUREMENT));
  215. if (isFrame || shouldRecord) {
  216. Mutex::Lock _l(_paths_m);
  217. if (isFrame) {
  218. ++(path->_packetsIn);
  219. _lastFrame=now;
  220. }
  221. if (shouldRecord) {
  222. path->ackStatsIn[packetId] = payloadLength;
  223. ++(path->_packetsReceivedSinceLastAck);
  224. path->qosStatsIn[packetId] = now;
  225. ++(path->_packetsReceivedSinceLastQoS);
  226. path->packetValiditySamples.push(true);
  227. }
  228. }
  229. /**
  230. * Learn new flows and pro-actively create entries for them in the bond so
  231. * that the next time we send a packet out that is part of a flow we know
  232. * which path to use.
  233. */
  234. if ((flowId != ZT_QOS_NO_FLOW)
  235. && (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR
  236. || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR
  237. || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE)) {
  238. Mutex::Lock _l(_flows_m);
  239. SharedPtr<Flow> flow;
  240. if (!_flows.count(flowId)) {
  241. flow = createFlow(path, flowId, 0, now);
  242. } else {
  243. flow = _flows[flowId];
  244. }
  245. if (flow) {
  246. flow->recordIncomingBytes(payloadLength);
  247. }
  248. }
  249. }
  250. void Bond::receivedQoS(const SharedPtr<Path>& path, int64_t now, int count, uint64_t *rx_id, uint16_t *rx_ts)
  251. {
  252. //char pathStr[128];path->address().toString(pathStr);fprintf(stderr, "receivedQoS() %s %s\n", getLink(path)->ifname().c_str(), pathStr);
  253. Mutex::Lock _l(_paths_m);
  254. // Look up egress times and compute latency values for each record
  255. std::map<uint64_t,uint64_t>::iterator it;
  256. for (int j=0; j<count; j++) {
  257. it = path->qosStatsOut.find(rx_id[j]);
  258. if (it != path->qosStatsOut.end()) {
  259. path->latencySamples.push(((uint16_t)(now - it->second) - rx_ts[j]) / 2);
  260. path->qosStatsOut.erase(it);
  261. }
  262. }
  263. path->qosRecordSize.push(count);
  264. //char pathStr[128];path->address().toString(pathStr);fprintf(stderr, "receivedQoS() on path %s %s, count=%d, successful=%d, qosStatsOut.size()=%d\n", getLink(path)->ifname().c_str(), pathStr, count, path->aknowledgedQoSRecordCountSinceLastCheck, path->qosStatsOut.size());
  265. }
  266. void Bond::receivedAck(const SharedPtr<Path>& path, int64_t now, int32_t ackedBytes)
  267. {
  268. Mutex::Lock _l(_paths_m);
  269. //char pathStr[128];path->address().toString(pathStr);fprintf(stderr, "receivedAck() %s %s, (ackedBytes=%d, lastAckReceived=%lld, ackAge=%lld)\n", getLink(path)->ifname().c_str(), pathStr, ackedBytes, path->lastAckReceived, path->ackAge(now));
  270. path->_lastAckReceived = now;
  271. path->_unackedBytes = (ackedBytes > path->_unackedBytes) ? 0 : path->_unackedBytes - ackedBytes;
  272. int64_t timeSinceThroughputEstimate = (now - path->_lastThroughputEstimation);
  273. if (timeSinceThroughputEstimate >= throughputMeasurementInterval) {
  274. // TODO: See if this floating point math can be reduced
  275. uint64_t throughput = (uint64_t)((float)(path->_bytesAckedSinceLastThroughputEstimation) / ((float)timeSinceThroughputEstimate / (float)1000));
  276. throughput /= 1000;
  277. if (throughput > 0.0) {
  278. path->throughputSamples.push(throughput);
  279. path->_throughputMax = throughput > path->_throughputMax ? throughput : path->_throughputMax;
  280. }
  281. path->_lastThroughputEstimation = now;
  282. path->_bytesAckedSinceLastThroughputEstimation = 0;
  283. } else {
  284. path->_bytesAckedSinceLastThroughputEstimation += ackedBytes;
  285. }
  286. }
  287. int32_t Bond::generateQoSPacket(const SharedPtr<Path>& path, int64_t now, char *qosBuffer)
  288. {
  289. //char pathStr[128];path->address().toString(pathStr);fprintf(stderr, "generateQoSPacket() %s %s\n", getLink(path)->ifname().c_str(), pathStr);
  290. int32_t len = 0;
  291. std::map<uint64_t,uint64_t>::iterator it = path->qosStatsIn.begin();
  292. int i=0;
  293. int numRecords = std::min(path->_packetsReceivedSinceLastQoS,ZT_QOS_TABLE_SIZE);
  294. while (i<numRecords && it != path->qosStatsIn.end()) {
  295. uint64_t id = it->first;
  296. memcpy(qosBuffer, &id, sizeof(uint64_t));
  297. qosBuffer+=sizeof(uint64_t);
  298. uint16_t holdingTime = (uint16_t)(now - it->second);
  299. memcpy(qosBuffer, &holdingTime, sizeof(uint16_t));
  300. qosBuffer+=sizeof(uint16_t);
  301. len+=sizeof(uint64_t)+sizeof(uint16_t);
  302. path->qosStatsIn.erase(it++);
  303. ++i;
  304. }
  305. return len;
  306. }
  307. bool Bond::assignFlowToBondedPath(SharedPtr<Flow> &flow, int64_t now)
  308. {
  309. //fprintf(stderr, "assignFlowToBondedPath\n");
  310. char curPathStr[128];
  311. unsigned int idx = ZT_MAX_PEER_NETWORK_PATHS;
  312. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR) {
  313. idx = abs((int)(flow->id() % (_numBondedPaths)));
  314. //fprintf(stderr, "flow->id()=%d, %x, _numBondedPaths=%d, idx=%d\n", flow->id(), flow->id(), _numBondedPaths, idx);
  315. flow->assignPath(_paths[_bondedIdx[idx]],now);
  316. ++(_paths[_bondedIdx[idx]]->_assignedFlowCount);
  317. }
  318. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  319. unsigned char entropy;
  320. Utils::getSecureRandom(&entropy, 1);
  321. if (_totalBondUnderload) {
  322. entropy %= _totalBondUnderload;
  323. }
  324. if (!_numBondedPaths) {
  325. fprintf(stderr, "no bonded paths for flow assignment\n");
  326. return false;
  327. }
  328. /* Since there may be scenarios where a path is removed before we can re-estimate
  329. relative qualities (and thus allocations) we need to down-modulate the entropy
  330. value that we use to randomly assign among the surviving paths, otherwise we risk
  331. not being able to find a path to assign this flow to. */
  332. int totalIncompleteAllocation = 0;
  333. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  334. if (_paths[i] && _paths[i]->bonded()) {
  335. totalIncompleteAllocation += _paths[i]->_allocation;
  336. }
  337. }
  338. //fprintf(stderr, "entropy = %d, totalIncompleteAllocation=%d\n", entropy, totalIncompleteAllocation);
  339. entropy %= totalIncompleteAllocation;
  340. //fprintf(stderr, "new entropy = %d\n", entropy);
  341. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  342. if (_paths[i] && _paths[i]->bonded()) {
  343. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  344. _paths[i]->address().toString(curPathStr);
  345. uint8_t probabilitySegment = (_totalBondUnderload > 0) ? _paths[i]->_affinity : _paths[i]->_allocation;
  346. //fprintf(stderr, "i=%2d, entropy=%3d, alloc=%3d, byteload=%4d, segment=%3d, _totalBondUnderload=%3d, ifname=%s, path=%20s\n", i, entropy, _paths[i]->_allocation, _paths[i]->_relativeByteLoad, probabilitySegment, _totalBondUnderload, link->ifname().c_str(), curPathStr);
  347. if (entropy <= probabilitySegment) {
  348. idx = i;
  349. //fprintf(stderr, "\t is best path\n");
  350. break;
  351. }
  352. entropy -= probabilitySegment;
  353. }
  354. }
  355. if (idx < ZT_MAX_PEER_NETWORK_PATHS) {
  356. if (flow->_assignedPath) {
  357. flow->_previouslyAssignedPath = flow->_assignedPath;
  358. }
  359. flow->assignPath(_paths[idx],now);
  360. ++(_paths[idx]->_assignedFlowCount);
  361. }
  362. else {
  363. fprintf(stderr, "could not assign flow?\n"); exit(0); // TODO: Remove for production
  364. return false;
  365. }
  366. }
  367. flow->assignedPath()->address().toString(curPathStr);
  368. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, flow->assignedPath()->localSocket());
  369. fprintf(stderr, "assigned (tx) flow %x with peer %llx to path %s on %s (idx=%d)\n", flow->id(), _peer->_id.address().toInt(), curPathStr, link->ifname().c_str(), idx);
  370. return true;
  371. }
  372. SharedPtr<Flow> Bond::createFlow(const SharedPtr<Path> &path, int32_t flowId, unsigned char entropy, int64_t now)
  373. {
  374. //fprintf(stderr, "createFlow\n");
  375. char curPathStr[128];
  376. // ---
  377. if (!_numBondedPaths) {
  378. fprintf(stderr, "there are no bonded paths, cannot assign flow\n");
  379. return SharedPtr<Flow>();
  380. }
  381. if (_flows.size() >= ZT_FLOW_MAX_COUNT) {
  382. fprintf(stderr, "max number of flows reached (%d), forcibly forgetting oldest flow\n", ZT_FLOW_MAX_COUNT);
  383. forgetFlowsWhenNecessary(0,true,now);
  384. }
  385. SharedPtr<Flow> flow = new Flow(flowId, now);
  386. _flows[flowId] = flow;
  387. fprintf(stderr, "new flow %x detected with peer %llx, %lu active flow(s)\n", flowId, _peer->_id.address().toInt(), (_flows.size()));
  388. /**
  389. * Add a flow with a given Path already provided. This is the case when a packet
  390. * is received on a path but no flow exists, in this case we simply assign the path
  391. * that the remote peer chose for us.
  392. */
  393. if (path) {
  394. flow->assignPath(path,now);
  395. path->address().toString(curPathStr);
  396. path->_assignedFlowCount++;
  397. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, flow->assignedPath()->localSocket());
  398. fprintf(stderr, "assigned (rx) flow %x with peer %llx to path %s on %s\n", flow->id(), _peer->_id.address().toInt(), curPathStr, link->ifname().c_str());
  399. }
  400. /**
  401. * Add a flow when no path was provided. This means that it is an outgoing packet
  402. * and that it is up to the local peer to decide how to load-balance its transmission.
  403. */
  404. else if (!path) {
  405. assignFlowToBondedPath(flow, now);
  406. }
  407. return flow;
  408. }
  409. void Bond::forgetFlowsWhenNecessary(uint64_t age, bool oldest, int64_t now)
  410. {
  411. //fprintf(stderr, "forgetFlowsWhenNecessary\n");
  412. std::map<int32_t,SharedPtr<Flow> >::iterator it = _flows.begin();
  413. std::map<int32_t,SharedPtr<Flow> >::iterator oldestFlow = _flows.end();
  414. SharedPtr<Flow> expiredFlow;
  415. if (age) { // Remove by specific age
  416. while (it != _flows.end()) {
  417. if (it->second->age(now) > age) {
  418. fprintf(stderr, "forgetting flow %x between this node and %llx, %lu active flow(s)\n", it->first, _peer->_id.address().toInt(), (_flows.size()-1));
  419. it->second->assignedPath()->_assignedFlowCount--;
  420. it = _flows.erase(it);
  421. } else {
  422. ++it;
  423. }
  424. }
  425. }
  426. else if (oldest) { // Remove single oldest by natural expiration
  427. uint64_t maxAge = 0;
  428. while (it != _flows.end()) {
  429. if (it->second->age(now) > maxAge) {
  430. maxAge = (now - it->second->age(now));
  431. oldestFlow = it;
  432. }
  433. ++it;
  434. }
  435. if (oldestFlow != _flows.end()) {
  436. fprintf(stderr, "forgetting oldest flow %x (of age %llu) between this node and %llx, %lu active flow(s)\n", oldestFlow->first, oldestFlow->second->age(now), _peer->_id.address().toInt(), (_flows.size()-1));
  437. oldestFlow->second->assignedPath()->_assignedFlowCount--;
  438. _flows.erase(oldestFlow);
  439. }
  440. }
  441. }
  442. void Bond::processIncomingPathNegotiationRequest(uint64_t now, SharedPtr<Path> &path, int16_t remoteUtility)
  443. {
  444. //fprintf(stderr, "processIncomingPathNegotiationRequest\n");
  445. if (_abLinkSelectMethod != ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE) {
  446. return;
  447. }
  448. Mutex::Lock _l(_paths_m);
  449. char pathStr[128];
  450. path->address().toString(pathStr);
  451. if (!_lastPathNegotiationCheck) {
  452. return;
  453. }
  454. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, path->localSocket());
  455. if (remoteUtility > _localUtility) {
  456. fprintf(stderr, "peer suggests path, its utility (%d) is greater than ours (%d), we will switch to %s on %s (ls=%llx)\n", remoteUtility, _localUtility, pathStr, link->ifname().c_str(), path->localSocket());
  457. negotiatedPath = path;
  458. }
  459. if (remoteUtility < _localUtility) {
  460. fprintf(stderr, "peer suggests path, its utility (%d) is less than ours (%d), we will NOT switch to %s on %s (ls=%llx)\n", remoteUtility, _localUtility, pathStr, link->ifname().c_str(), path->localSocket());
  461. }
  462. if (remoteUtility == _localUtility) {
  463. fprintf(stderr, "peer suggest path, but utility is equal, picking choice made by peer with greater identity.\n");
  464. if (_peer->_id.address().toInt() > RR->node->identity().address().toInt()) {
  465. fprintf(stderr, "peer identity was greater, going with their choice of %s on %s (ls=%llx)\n", pathStr, link->ifname().c_str(), path->localSocket());
  466. negotiatedPath = path;
  467. } else {
  468. fprintf(stderr, "our identity was greater, no change\n");
  469. }
  470. }
  471. }
  472. void Bond::pathNegotiationCheck(void *tPtr, const int64_t now)
  473. {
  474. //fprintf(stderr, "pathNegotiationCheck\n");
  475. char pathStr[128];
  476. int maxInPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  477. int maxOutPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  478. uint64_t maxInCount = 0;
  479. uint64_t maxOutCount = 0;
  480. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  481. if (!_paths[i]) {
  482. continue;
  483. }
  484. if (_paths[i]->_packetsIn > maxInCount) {
  485. maxInCount = _paths[i]->_packetsIn;
  486. maxInPathIdx = i;
  487. }
  488. if (_paths[i]->_packetsOut > maxOutCount) {
  489. maxOutCount = _paths[i]->_packetsOut;
  490. maxOutPathIdx = i;
  491. }
  492. _paths[i]->resetPacketCounts();
  493. }
  494. bool _peerLinksSynchronized = ((maxInPathIdx != ZT_MAX_PEER_NETWORK_PATHS)
  495. && (maxOutPathIdx != ZT_MAX_PEER_NETWORK_PATHS)
  496. && (maxInPathIdx != maxOutPathIdx)) ? false : true;
  497. /**
  498. * Determine utility and attempt to petition remote peer to switch to our chosen path
  499. */
  500. if (!_peerLinksSynchronized) {
  501. _localUtility = _paths[maxOutPathIdx]->_failoverScore - _paths[maxInPathIdx]->_failoverScore;
  502. if (_paths[maxOutPathIdx]->_negotiated) {
  503. _localUtility -= ZT_MULTIPATH_FAILOVER_HANDICAP_NEGOTIATED;
  504. }
  505. if ((now - _lastSentPathNegotiationRequest) > ZT_PATH_NEGOTIATION_CUTOFF_TIME) {
  506. fprintf(stderr, "BT: (sync) it's been long enough, sending more requests.\n");
  507. _numSentPathNegotiationRequests = 0;
  508. }
  509. if (_numSentPathNegotiationRequests < ZT_PATH_NEGOTIATION_TRY_COUNT) {
  510. if (_localUtility >= 0) {
  511. fprintf(stderr, "BT: (sync) paths appear to be out of sync (utility=%d)\n", _localUtility);
  512. sendPATH_NEGOTIATION_REQUEST(tPtr, _paths[maxOutPathIdx]);
  513. ++_numSentPathNegotiationRequests;
  514. _lastSentPathNegotiationRequest = now;
  515. _paths[maxOutPathIdx]->address().toString(pathStr);
  516. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[maxOutPathIdx]->localSocket());
  517. fprintf(stderr, "sending request to use %s on %s, ls=%llx, utility=%d\n", pathStr, link->ifname().c_str(), _paths[maxOutPathIdx]->localSocket(), _localUtility);
  518. }
  519. }
  520. /**
  521. * Give up negotiating and consider switching
  522. */
  523. else if ((now - _lastSentPathNegotiationRequest) > (2 * ZT_PATH_NEGOTIATION_CHECK_INTERVAL)) {
  524. if (_localUtility == 0) {
  525. // There's no loss to us, just switch without sending a another request
  526. fprintf(stderr, "BT: (sync) giving up, switching to remote peer's path.\n");
  527. negotiatedPath = _paths[maxInPathIdx];
  528. }
  529. }
  530. }
  531. }
  532. void Bond::sendPATH_NEGOTIATION_REQUEST(void *tPtr, const SharedPtr<Path> &path)
  533. {
  534. //char pathStr[128];path->address().toString(pathStr);fprintf(stderr, "sendPATH_NEGOTIATION_REQUEST() %s %s\n", getLink(path)->ifname().c_str(), pathStr);
  535. if (_abLinkSelectMethod != ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE) {
  536. return;
  537. }
  538. Packet outp(_peer->_id.address(),RR->identity.address(),Packet::VERB_PATH_NEGOTIATION_REQUEST);
  539. outp.append<int16_t>(_localUtility);
  540. if (path->address()) {
  541. outp.armor(_peer->key(),false);
  542. RR->node->putPacket(tPtr,path->localSocket(),path->address(),outp.data(),outp.size());
  543. }
  544. }
  545. void Bond::sendACK(void *tPtr,const SharedPtr<Path> &path,const int64_t localSocket,
  546. const InetAddress &atAddress,int64_t now)
  547. {
  548. //char pathStr[128];path->address().toString(pathStr);fprintf(stderr, "sendACK() %s %s\n", getLink(path)->ifname().c_str(), pathStr);
  549. Packet outp(_peer->_id.address(),RR->identity.address(),Packet::VERB_ACK);
  550. int32_t bytesToAck = 0;
  551. std::map<uint64_t,uint16_t>::iterator it = path->ackStatsIn.begin();
  552. while (it != path->ackStatsIn.end()) {
  553. bytesToAck += it->second;
  554. ++it;
  555. }
  556. outp.append<uint32_t>(bytesToAck);
  557. if (atAddress) {
  558. outp.armor(_peer->key(),false);
  559. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  560. } else {
  561. RR->sw->send(tPtr,outp,false);
  562. }
  563. path->ackStatsIn.clear();
  564. path->_packetsReceivedSinceLastAck = 0;
  565. path->_lastAckSent = now;
  566. }
  567. void Bond::sendQOS_MEASUREMENT(void *tPtr,const SharedPtr<Path> &path,const int64_t localSocket,
  568. const InetAddress &atAddress,int64_t now)
  569. {
  570. //char pathStr[128];path->address().toString(pathStr);fprintf(stderr, "sendQOS() %s %s\n", getLink(path)->ifname().c_str(), pathStr);
  571. const int64_t _now = RR->node->now();
  572. Packet outp(_peer->_id.address(),RR->identity.address(),Packet::VERB_QOS_MEASUREMENT);
  573. char qosData[ZT_QOS_MAX_PACKET_SIZE];
  574. int16_t len = generateQoSPacket(path, _now,qosData);
  575. outp.append(qosData,len);
  576. if (atAddress) {
  577. outp.armor(_peer->key(),false);
  578. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  579. } else {
  580. RR->sw->send(tPtr,outp,false);
  581. }
  582. // Account for the fact that a VERB_QOS_MEASUREMENT was just sent. Reset timers.
  583. path->_packetsReceivedSinceLastQoS = 0;
  584. path->_lastQoSMeasurement = now;
  585. }
  586. void Bond::processBackgroundTasks(void *tPtr, const int64_t now)
  587. {
  588. Mutex::Lock _l(_paths_m);
  589. if (!_peer->_canUseMultipath || (now - _lastBackgroundTaskCheck) < ZT_BOND_BACKGROUND_TASK_MIN_INTERVAL) {
  590. return;
  591. }
  592. _lastBackgroundTaskCheck = now;
  593. // Compute dynamic path monitor timer interval
  594. if (_linkMonitorStrategy == ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC) {
  595. int suggestedMonitorInterval = (now - _lastFrame) / 100;
  596. _dynamicPathMonitorInterval = std::min(ZT_PATH_HEARTBEAT_PERIOD, ((suggestedMonitorInterval > _bondMonitorInterval) ? suggestedMonitorInterval : _bondMonitorInterval));
  597. //fprintf(stderr, "_lastFrame=%llu, suggestedMonitorInterval=%d, _dynamicPathMonitorInterval=%d\n",
  598. // (now-_lastFrame), suggestedMonitorInterval, _dynamicPathMonitorInterval);
  599. }
  600. // TODO: Clarify and generalize this logic
  601. if (_linkMonitorStrategy == ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC) {
  602. _shouldCollectPathStatistics = true;
  603. }
  604. // Memoize oft-used properties in the packet ingress/egress logic path
  605. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  606. // Required for real-time balancing
  607. _shouldCollectPathStatistics = true;
  608. }
  609. if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  610. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_BETTER) {
  611. // Required for judging suitability of primary link after recovery
  612. _shouldCollectPathStatistics = true;
  613. }
  614. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE) {
  615. // Required for judging suitability of new candidate primary
  616. _shouldCollectPathStatistics = true;
  617. }
  618. }
  619. if ((now - _lastCheckUserPreferences) > 1000) {
  620. _lastCheckUserPreferences = now;
  621. applyUserPrefs();
  622. }
  623. curateBond(now,false);
  624. if ((now - _lastQualityEstimation) > _qualityEstimationInterval) {
  625. _lastQualityEstimation = now;
  626. estimatePathQuality(now);
  627. }
  628. dumpInfo(now);
  629. // Send QOS/ACK packets as needed
  630. if (_shouldCollectPathStatistics) {
  631. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  632. if (_paths[i] && _paths[i]->allowed()) {
  633. if (_paths[i]->needsToSendQoS(now,_qosSendInterval)) {
  634. sendQOS_MEASUREMENT(tPtr, _paths[i], _paths[i]->localSocket(), _paths[i]->address(), now);
  635. }
  636. if (_paths[i]->needsToSendAck(now,_ackSendInterval)) {
  637. sendACK(tPtr, _paths[i], _paths[i]->localSocket(), _paths[i]->address(), now);
  638. }
  639. }
  640. }
  641. }
  642. // Perform periodic background tasks unique to each bonding policy
  643. switch (_bondingPolicy)
  644. {
  645. case ZT_BONDING_POLICY_ACTIVE_BACKUP:
  646. processActiveBackupTasks(now);
  647. break;
  648. case ZT_BONDING_POLICY_BROADCAST:
  649. break;
  650. case ZT_BONDING_POLICY_BALANCE_RR:
  651. case ZT_BONDING_POLICY_BALANCE_XOR:
  652. case ZT_BONDING_POLICY_BALANCE_AWARE:
  653. processBalanceTasks(now);
  654. break;
  655. default:
  656. break;
  657. }
  658. // Check whether or not a path negotiation needs to be performed
  659. if (((now - _lastPathNegotiationCheck) > ZT_PATH_NEGOTIATION_CHECK_INTERVAL) && _allowPathNegotiation) {
  660. _lastPathNegotiationCheck = now;
  661. pathNegotiationCheck(tPtr, now);
  662. }
  663. }
  664. void Bond::applyUserPrefs()
  665. {
  666. //fprintf(stderr, "applyUserPrefs, _minReqPathMonitorInterval=%d\n", RR->bc->minReqPathMonitorInterval());
  667. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  668. if (!_paths[i]) {
  669. continue;
  670. }
  671. SharedPtr<Link> sl = getLink(_paths[i]);
  672. if (sl) {
  673. if (sl->monitorInterval() == 0) { // If no interval was specified for this link, use more generic bond-wide interval
  674. sl->setMonitorInterval(_bondMonitorInterval);
  675. }
  676. RR->bc->setMinReqPathMonitorInterval((sl->monitorInterval() < RR->bc->minReqPathMonitorInterval()) ? sl->monitorInterval() : RR->bc->minReqPathMonitorInterval());
  677. bool bFoundCommonLink = false;
  678. SharedPtr<Link> commonLink =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  679. for(unsigned int j=0;j<ZT_MAX_PEER_NETWORK_PATHS;++j) {
  680. if (_paths[j] && _paths[j].ptr() != _paths[i].ptr()) {
  681. if (RR->bc->getLinkBySocket(_policyAlias, _paths[j]->localSocket()) == commonLink) {
  682. bFoundCommonLink = true;
  683. }
  684. }
  685. }
  686. _paths[i]->_monitorInterval = sl->monitorInterval();
  687. _paths[i]->_upDelay = sl->upDelay() ? sl->upDelay() : _upDelay;
  688. _paths[i]->_downDelay = sl->downDelay() ? sl->downDelay() : _downDelay;
  689. _paths[i]->_ipvPref = sl->ipvPref();
  690. _paths[i]->_mode = sl->mode();
  691. _paths[i]->_enabled = sl->enabled();
  692. _paths[i]->_onlyPathOnLink = !bFoundCommonLink;
  693. }
  694. }
  695. if (_peer) {
  696. _peer->_shouldCollectPathStatistics = _shouldCollectPathStatistics;
  697. _peer->_bondingPolicy = _bondingPolicy;
  698. }
  699. }
  700. void Bond::curateBond(const int64_t now, bool rebuildBond)
  701. {
  702. //fprintf(stderr, "%lu curateBond (rebuildBond=%d), _numBondedPaths=%d\n", ((now - RR->bc->getBondStartTime())), rebuildBond, _numBondedPaths);
  703. char pathStr[128];
  704. /**
  705. * Update path states
  706. */
  707. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  708. if (!_paths[i]) {
  709. continue;
  710. }
  711. bool currEligibility = _paths[i]->eligible(now,_ackSendInterval);
  712. //_paths[i]->address().toString(pathStr);
  713. //fprintf(stderr, "\n\n%ld path eligibility (for %s, %s):\n", (RR->node->now() - RR->bc->getBondStartTime()), getLink(_paths[i])->ifname().c_str(), pathStr);
  714. //_paths[i]->printEligible(now,_ackSendInterval);
  715. if (currEligibility != _paths[i]->_lastEligibilityState) {
  716. _paths[i]->address().toString(pathStr);
  717. //fprintf(stderr, "\n\n%ld path eligibility (for %s, %s) has changed (from %d to %d)\n", (RR->node->now() - RR->bc->getBondStartTime()), getLink(_paths[i])->ifname().c_str(), pathStr, _paths[i]->lastCheckedEligibility, _paths[i]->eligible(now,_ackSendInterval));
  718. if (currEligibility) {
  719. rebuildBond = true;
  720. }
  721. if (!currEligibility) {
  722. _paths[i]->adjustRefractoryPeriod(now, _defaultPathRefractoryPeriod, !currEligibility);
  723. if (_paths[i]->bonded()) {
  724. //fprintf(stderr, "the path was bonded, reallocation of its flows will occur soon\n");
  725. rebuildBond = true;
  726. _paths[i]->_shouldReallocateFlows = _paths[i]->bonded();
  727. _paths[i]->setBonded(false);
  728. } else {
  729. //fprintf(stderr, "the path was not bonded, no consequences\n");
  730. }
  731. }
  732. }
  733. if (currEligibility) {
  734. _paths[i]->adjustRefractoryPeriod(now, _defaultPathRefractoryPeriod, false);
  735. }
  736. _paths[i]->_lastEligibilityState = currEligibility;
  737. }
  738. /**
  739. * Curate the set of paths that are part of the bond proper. Selects a single path
  740. * per logical link according to eligibility and user-specified constraints.
  741. */
  742. if ((_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR)
  743. || (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR)
  744. || (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE)) {
  745. if (!_numBondedPaths) {
  746. rebuildBond = true;
  747. }
  748. // TODO: Optimize
  749. if (rebuildBond) {
  750. int updatedBondedPathCount = 0;
  751. std::map<SharedPtr<Link>,int> linkMap;
  752. for (int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  753. if (_paths[i] && _paths[i]->allowed() && (_paths[i]->eligible(now,_ackSendInterval) || !_numBondedPaths)) {
  754. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  755. if (!linkMap.count(link)) {
  756. linkMap[link] = i;
  757. }
  758. else {
  759. bool overriden = false;
  760. _paths[i]->address().toString(pathStr);
  761. //fprintf(stderr, " link representative path already exists! (%s %s)\n", getLink(_paths[i])->ifname().c_str(), pathStr);
  762. if (_paths[i]->preferred() && !_paths[linkMap[link]]->preferred()) {
  763. // Override previous choice if preferred
  764. //fprintf(stderr, "overriding since its preferred!\n");
  765. if (_paths[linkMap[link]]->_assignedFlowCount) {
  766. _paths[linkMap[link]]->_deprecated = true;
  767. }
  768. else {
  769. _paths[linkMap[link]]->_deprecated = true;
  770. _paths[linkMap[link]]->setBonded(false);
  771. }
  772. linkMap[link] = i;
  773. overriden = true;
  774. }
  775. if ((_paths[i]->preferred() && _paths[linkMap[link]]->preferred())
  776. || (!_paths[i]->preferred() && !_paths[linkMap[link]]->preferred())) {
  777. if (_paths[i]->preferenceRank() > _paths[linkMap[link]]->preferenceRank()) {
  778. // Override if higher preference
  779. //fprintf(stderr, "overriding according to preference preferenceRank!\n");
  780. if (_paths[linkMap[link]]->_assignedFlowCount) {
  781. _paths[linkMap[link]]->_deprecated = true;
  782. }
  783. else {
  784. _paths[linkMap[link]]->_deprecated = true;
  785. _paths[linkMap[link]]->setBonded(false);
  786. }
  787. linkMap[link] = i;
  788. }
  789. }
  790. }
  791. }
  792. }
  793. std::map<SharedPtr<Link>,int>::iterator it = linkMap.begin();
  794. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  795. if (!_paths[i]) {
  796. continue;
  797. }
  798. _bondedIdx[i] = ZT_MAX_PEER_NETWORK_PATHS;
  799. if (it != linkMap.end()) {
  800. _bondedIdx[i] = it->second;
  801. _paths[_bondedIdx[i]]->setBonded(true);
  802. ++it;
  803. ++updatedBondedPathCount;
  804. _paths[_bondedIdx[i]]->address().toString(pathStr);
  805. //fprintf(stderr, "setting i=%d, _bondedIdx[%d]=%d to bonded (%s %s)\n", i, i, _bondedIdx[i], getLink(_paths[_bondedIdx[i]])->ifname().c_str(), pathStr);
  806. }
  807. }
  808. _numBondedPaths = updatedBondedPathCount;
  809. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR) {
  810. // Cause a RR reset since the currently used index might no longer be valid
  811. _rrPacketsSentOnCurrLink = _packetsPerLink;
  812. }
  813. }
  814. }
  815. }
  816. void Bond::estimatePathQuality(const int64_t now)
  817. {
  818. char pathStr[128];
  819. uint32_t totUserSpecifiedLinkSpeed = 0;
  820. if (_numBondedPaths) { // Compute relative user-specified speeds of links
  821. for(unsigned int i=0;i<_numBondedPaths;++i) {
  822. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  823. if (_paths[i] && _paths[i]->allowed()) {
  824. totUserSpecifiedLinkSpeed += link->speed();
  825. }
  826. }
  827. for(unsigned int i=0;i<_numBondedPaths;++i) {
  828. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  829. if (_paths[i] && _paths[i]->allowed()) {
  830. link->setRelativeSpeed(round( ((float)link->speed() / (float)totUserSpecifiedLinkSpeed) * 255));
  831. }
  832. }
  833. }
  834. float lat[ZT_MAX_PEER_NETWORK_PATHS];
  835. float pdv[ZT_MAX_PEER_NETWORK_PATHS];
  836. float plr[ZT_MAX_PEER_NETWORK_PATHS];
  837. float per[ZT_MAX_PEER_NETWORK_PATHS];
  838. float maxLAT = 0;
  839. float maxPDV = 0;
  840. float maxPLR = 0;
  841. float maxPER = 0;
  842. float quality[ZT_MAX_PEER_NETWORK_PATHS];
  843. uint8_t alloc[ZT_MAX_PEER_NETWORK_PATHS];
  844. float totQuality = 0.0f;
  845. memset(&lat, 0, sizeof(lat));
  846. memset(&pdv, 0, sizeof(pdv));
  847. memset(&plr, 0, sizeof(plr));
  848. memset(&per, 0, sizeof(per));
  849. memset(&quality, 0, sizeof(quality));
  850. memset(&alloc, 0, sizeof(alloc));
  851. // Compute initial summary statistics
  852. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  853. if (!_paths[i] || !_paths[i]->allowed()) {
  854. continue;
  855. }
  856. // Compute/Smooth average of real-world observations
  857. _paths[i]->_latencyMean = _paths[i]->latencySamples.mean();
  858. _paths[i]->_latencyVariance = _paths[i]->latencySamples.stddev();
  859. _paths[i]->_packetErrorRatio = 1.0 - (_paths[i]->packetValiditySamples.count() ? _paths[i]->packetValiditySamples.mean() : 1.0);
  860. if (userHasSpecifiedLinkSpeeds()) {
  861. // Use user-reported metrics
  862. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  863. if (link) {
  864. _paths[i]->_throughputMean = link->speed();
  865. _paths[i]->_throughputVariance = 0;
  866. }
  867. }
  868. // Drain unacknowledged QoS records
  869. std::map<uint64_t,uint64_t>::iterator it = _paths[i]->qosStatsOut.begin();
  870. uint64_t currentLostRecords = 0;
  871. while (it != _paths[i]->qosStatsOut.end()) {
  872. int qosRecordTimeout = 5000; //_paths[i]->monitorInterval() * ZT_MULTIPATH_QOS_ACK_INTERVAL_MULTIPLIER * 8;
  873. if ((now - it->second) >= qosRecordTimeout) {
  874. //fprintf(stderr, "packetId=%llx was lost\n", it->first);
  875. it = _paths[i]->qosStatsOut.erase(it);
  876. ++currentLostRecords;
  877. } else { ++it; }
  878. }
  879. quality[i]=0;
  880. totQuality=0;
  881. // Normalize raw observations according to sane limits and/or user specified values
  882. lat[i] = 1.0 / expf(4*Utils::normalize(_paths[i]->_latencyMean, 0, _maxAcceptableLatency, 0, 1));
  883. pdv[i] = 1.0 / expf(4*Utils::normalize(_paths[i]->_latencyVariance, 0, _maxAcceptablePacketDelayVariance, 0, 1));
  884. plr[i] = 1.0 / expf(4*Utils::normalize(_paths[i]->_packetLossRatio, 0, _maxAcceptablePacketLossRatio, 0, 1));
  885. per[i] = 1.0 / expf(4*Utils::normalize(_paths[i]->_packetErrorRatio, 0, _maxAcceptablePacketErrorRatio, 0, 1));
  886. //scp[i] = _paths[i]->ipvPref != 0 ? 1.0 : Utils::normalize(_paths[i]->ipScope(), InetAddress::IP_SCOPE_NONE, InetAddress::IP_SCOPE_PRIVATE, 0, 1);
  887. // Record bond-wide maximums to determine relative values
  888. maxLAT = lat[i] > maxLAT ? lat[i] : maxLAT;
  889. maxPDV = pdv[i] > maxPDV ? pdv[i] : maxPDV;
  890. maxPLR = plr[i] > maxPLR ? plr[i] : maxPLR;
  891. maxPER = per[i] > maxPER ? per[i] : maxPER;
  892. //fprintf(stdout, "EH %d: lat=%8.3f, ltm=%8.3f, pdv=%8.3f, plr=%5.3f, per=%5.3f, thr=%8f, thm=%5.3f, thv=%5.3f, avl=%5.3f, age=%8.2f, scp=%4d, q=%5.3f, qtot=%5.3f, ac=%d if=%s, path=%s\n",
  893. // i, lat[i], ltm[i], pdv[i], plr[i], per[i], thr[i], thm[i], thv[i], avl[i], age[i], scp[i], quality[i], totQuality, alloc[i], getLink(_paths[i])->ifname().c_str(), pathStr);
  894. }
  895. // Convert metrics to relative quantities and apply contribution weights
  896. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  897. if (_paths[i] && _paths[i]->bonded()) {
  898. quality[i] += ((maxLAT > 0.0f ? lat[i] / maxLAT : 0.0f) * _qualityWeights[ZT_QOS_LAT_IDX]);
  899. quality[i] += ((maxPDV > 0.0f ? pdv[i] / maxPDV : 0.0f) * _qualityWeights[ZT_QOS_PDV_IDX]);
  900. quality[i] += ((maxPLR > 0.0f ? plr[i] / maxPLR : 0.0f) * _qualityWeights[ZT_QOS_PLR_IDX]);
  901. quality[i] += ((maxPER > 0.0f ? per[i] / maxPER : 0.0f) * _qualityWeights[ZT_QOS_PER_IDX]);
  902. //quality[i] += (scp[i] * _qualityWeights[ZT_QOS_SCP_IDX]);
  903. totQuality += quality[i];
  904. }
  905. }
  906. //
  907. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  908. if (_paths[i] && _paths[i]->bonded()) {
  909. alloc[i] = std::ceil((quality[i] / totQuality) * (float)255);
  910. _paths[i]->_allocation = alloc[i];
  911. }
  912. }
  913. if ((now - _lastLogTS) > 500) {
  914. if (!relevant()) {return;}
  915. //fprintf(stderr, "\n");
  916. _lastLogTS = now;
  917. int numPlottablePaths=0;
  918. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  919. if (_paths[i]) {
  920. ++numPlottablePaths;
  921. _paths[i]->address().toString(pathStr);
  922. //fprintf(stderr, "%lu FIN [%d/%d]: pmi=%5d, lat=%4.3f, ltm=%4.3f, pdv=%4.3f, plr=%4.3f, per=%4.3f, thr=%4.3f, thm=%4.3f, thv=%4.3f, age=%4.3f, scp=%4d, q=%4.3f, qtot=%4.3f, ac=%4d, asf=%3d, if=%s, path=%20s, bond=%d, qosout=%d, plrraw=%d\n",
  923. // ((now - RR->bc->getBondStartTime())), i, _numBondedPaths, _paths[i]->monitorInterval,
  924. // lat[i], ltm[i], pdv[i], plr[i], per[i], thr[i], thm[i], thv[i], age[i], scp[i],
  925. // quality[i], totQuality, alloc[i], _paths[i]->assignedFlowCount, getLink(_paths[i])->ifname().c_str(), pathStr, _paths[i]->bonded(), _paths[i]->qosStatsOut.size(), _paths[i]->packetLossRatio);
  926. }
  927. }
  928. if (numPlottablePaths < 2) {
  929. return;
  930. }
  931. if (!_header) {
  932. fprintf(stdout, "now, bonded, relativeUnderload, flows, ");
  933. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  934. if (_paths[i]) {
  935. _paths[i]->address().toString(pathStr);
  936. std::string label = std::string((pathStr)) + " " + getLink(_paths[i])->ifname();
  937. for (int i=0; i<19; ++i) {
  938. fprintf(stdout, "%s, ", label.c_str());
  939. }
  940. }
  941. }
  942. _header=true;
  943. }
  944. /*
  945. fprintf(stdout, "%ld, %d, %d, %d, ",((now - RR->bc->getBondStartTime())),_numBondedPaths,_totalBondUnderload, _flows.size());
  946. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  947. if (_paths[i]) {
  948. _paths[i]->address().toString(pathStr);
  949. fprintf(stdout, "%s, %s, %8.3f, %8.3f, %8.3f, %5.3f, %5.3f, %5.3f, %8f, %5.3f, %5.3f, %d, %5.3f, %d, %d, %d, %d, %d, %d, ",
  950. getLink(_paths[i])->ifname().c_str(), pathStr, _paths[i]->_latencyMean, lat[i],pdv[i], _paths[i]->_packetLossRatio, plr[i],per[i],thr[i],thm[i],thv[i],(now - _paths[i]->lastIn()),quality[i],alloc[i],
  951. _paths[i]->_relativeByteLoad, _paths[i]->_assignedFlowCount, _paths[i]->alive(now, true), _paths[i]->eligible(now,_ackSendInterval), _paths[i]->qosStatsOut.size());
  952. }
  953. }*/
  954. //fprintf(stdout, "\n");
  955. }
  956. }
  957. void Bond::processBalanceTasks(const int64_t now)
  958. {
  959. char curPathStr[128];
  960. // TODO: Generalize
  961. int totalAllocation = 0;
  962. for (int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  963. if (!_paths[i]) {
  964. continue;
  965. }
  966. if (_paths[i] && _paths[i]->bonded() && _paths[i]->eligible(now,_ackSendInterval)) {
  967. totalAllocation+=_paths[i]->_allocation;
  968. }
  969. }
  970. unsigned char minimumAllocationValue = 0.33 * ((float)totalAllocation / (float)_numBondedPaths);
  971. if (_allowFlowHashing) {
  972. /**
  973. * Clean up and reset flows if necessary
  974. */
  975. if ((now - _lastFlowExpirationCheck) > ZT_MULTIPATH_FLOW_CHECK_INTERVAL) {
  976. Mutex::Lock _l(_flows_m);
  977. forgetFlowsWhenNecessary(ZT_MULTIPATH_FLOW_EXPIRATION_INTERVAL,false,now);
  978. _lastFlowExpirationCheck = now;
  979. }
  980. if ((now - _lastFlowStatReset) > ZT_FLOW_STATS_RESET_INTERVAL) {
  981. Mutex::Lock _l(_flows_m);
  982. _lastFlowStatReset = now;
  983. std::map<int32_t,SharedPtr<Flow> >::iterator it = _flows.begin();
  984. while (it != _flows.end()) {
  985. it->second->resetByteCounts();
  986. ++it;
  987. }
  988. }
  989. /**
  990. * Re-allocate flows from dead paths
  991. */
  992. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  993. Mutex::Lock _l(_flows_m);
  994. for (int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  995. if (!_paths[i]) {
  996. continue;
  997. }
  998. if (!_paths[i]->eligible(now,_ackSendInterval) && _paths[i]->_shouldReallocateFlows) {
  999. _paths[i]->address().toString(curPathStr);
  1000. fprintf(stderr, "%d reallocating flows from dead path %s on %s\n", (RR->node->now() - RR->bc->getBondStartTime()), curPathStr, getLink(_paths[i])->ifname().c_str());
  1001. std::map<int32_t,SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1002. while (flow_it != _flows.end()) {
  1003. if (flow_it->second->assignedPath() == _paths[i]) {
  1004. if(assignFlowToBondedPath(flow_it->second, now)) {
  1005. _paths[i]->_assignedFlowCount--;
  1006. }
  1007. }
  1008. ++flow_it;
  1009. }
  1010. _paths[i]->_shouldReallocateFlows = false;
  1011. }
  1012. }
  1013. }
  1014. /**
  1015. * Re-allocate flows from under-performing
  1016. * NOTE: This could be part of the above block but was kept separate for clarity.
  1017. */
  1018. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  1019. Mutex::Lock _l(_flows_m);
  1020. for (int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  1021. if (!_paths[i]) {
  1022. continue;
  1023. }
  1024. if (_paths[i] && _paths[i]->bonded() && _paths[i]->eligible(now,_ackSendInterval) && (_paths[i]->_allocation < minimumAllocationValue) && _paths[i]->_assignedFlowCount) {
  1025. _paths[i]->address().toString(curPathStr);
  1026. fprintf(stderr, "%d reallocating flows from under-performing path %s on %s\n", (RR->node->now() - RR->bc->getBondStartTime()), curPathStr, getLink(_paths[i])->ifname().c_str());
  1027. std::map<int32_t,SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1028. while (flow_it != _flows.end()) {
  1029. if (flow_it->second->assignedPath() == _paths[i]) {
  1030. if(assignFlowToBondedPath(flow_it->second, now)) {
  1031. _paths[i]->_assignedFlowCount--;
  1032. }
  1033. }
  1034. ++flow_it;
  1035. }
  1036. _paths[i]->_shouldReallocateFlows = false;
  1037. }
  1038. }
  1039. }
  1040. }
  1041. /**
  1042. * Tasks specific to (Balance Round Robin)
  1043. */
  1044. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR) {
  1045. if (_allowFlowHashing) {
  1046. // TODO: Should ideally failover from (idx) to a random link, this is so that (idx+1) isn't overloaded
  1047. }
  1048. else if (!_allowFlowHashing) {
  1049. // Nothing
  1050. }
  1051. }
  1052. /**
  1053. * Tasks specific to (Balance XOR)
  1054. */
  1055. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR) {
  1056. // Nothing specific for XOR
  1057. }
  1058. /**
  1059. * Tasks specific to (Balance Aware)
  1060. */
  1061. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  1062. if (_allowFlowHashing) {
  1063. Mutex::Lock _l(_flows_m);
  1064. if (_flowRebalanceStrategy == ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_PASSIVE) {
  1065. // Do nothing here, this is taken care of in the more general case above.
  1066. }
  1067. if (_flowRebalanceStrategy == ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_OPPORTUNISTIC) {
  1068. // If the flow is temporarily inactive we should take this opportunity to re-assign the flow if needed.
  1069. }
  1070. if (_flowRebalanceStrategy == ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_AGGRESSIVE) {
  1071. /**
  1072. * Return flows to the original path if it has once again become available
  1073. */
  1074. if ((now - _lastFlowRebalance) > ZT_FLOW_REBALANCE_INTERVAL) {
  1075. std::map<int32_t,SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1076. while (flow_it != _flows.end()) {
  1077. if (flow_it->second->_previouslyAssignedPath && flow_it->second->_previouslyAssignedPath->eligible(now, _ackSendInterval)
  1078. && (flow_it->second->_previouslyAssignedPath->_allocation >= (minimumAllocationValue * 2))) {
  1079. fprintf(stderr, "moving flow back onto its previous path assignment (based on eligibility)\n");
  1080. (flow_it->second->_assignedPath->_assignedFlowCount)--;
  1081. flow_it->second->assignPath(flow_it->second->_previouslyAssignedPath,now);
  1082. (flow_it->second->_previouslyAssignedPath->_assignedFlowCount)++;
  1083. }
  1084. ++flow_it;
  1085. }
  1086. _lastFlowRebalance = now;
  1087. }
  1088. /**
  1089. * Return flows to the original path if it has once again become (performant)
  1090. */
  1091. if ((now - _lastFlowRebalance) > ZT_FLOW_REBALANCE_INTERVAL) {
  1092. std::map<int32_t,SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1093. while (flow_it != _flows.end()) {
  1094. if (flow_it->second->_previouslyAssignedPath && flow_it->second->_previouslyAssignedPath->eligible(now, _ackSendInterval)
  1095. && (flow_it->second->_previouslyAssignedPath->_allocation >= (minimumAllocationValue * 2))) {
  1096. fprintf(stderr, "moving flow back onto its previous path assignment (based on performance)\n");
  1097. (flow_it->second->_assignedPath->_assignedFlowCount)--;
  1098. flow_it->second->assignPath(flow_it->second->_previouslyAssignedPath,now);
  1099. (flow_it->second->_previouslyAssignedPath->_assignedFlowCount)++;
  1100. }
  1101. ++flow_it;
  1102. }
  1103. _lastFlowRebalance = now;
  1104. }
  1105. }
  1106. }
  1107. else if (!_allowFlowHashing) {
  1108. // Nothing
  1109. }
  1110. }
  1111. }
  1112. void Bond::dequeueNextActiveBackupPath(const uint64_t now)
  1113. {
  1114. //fprintf(stderr, "dequeueNextActiveBackupPath\n");
  1115. if (_abFailoverQueue.empty()) {
  1116. return;
  1117. }
  1118. _abPath = _abFailoverQueue.front();
  1119. _abFailoverQueue.pop_front();
  1120. _lastActiveBackupPathChange = now;
  1121. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1122. if (_paths[i]) {
  1123. _paths[i]->resetPacketCounts();
  1124. }
  1125. }
  1126. }
  1127. void Bond::processActiveBackupTasks(const int64_t now)
  1128. {
  1129. //fprintf(stderr, "%llu processActiveBackupTasks\n", (now - RR->bc->getBondStartTime()));
  1130. char pathStr[128]; char prevPathStr[128]; char curPathStr[128];
  1131. SharedPtr<Path> prevActiveBackupPath = _abPath;
  1132. SharedPtr<Path> nonPreferredPath;
  1133. bool bFoundPrimaryLink = false;
  1134. /**
  1135. * Select initial "active" active-backup link
  1136. */
  1137. if (!_abPath) {
  1138. fprintf(stderr, "%llu no active backup path yet...\n", ((now - RR->bc->getBondStartTime())));
  1139. /**
  1140. * [Automatic mode]
  1141. * The user has not explicitly specified links or their failover schedule,
  1142. * the bonding policy will now select the first eligible path and set it as
  1143. * its active backup path, if a substantially better path is detected the bonding
  1144. * policy will assign it as the new active backup path. If the path fails it will
  1145. * simply find the next eligible path.
  1146. */
  1147. if (!userHasSpecifiedLinks()) {
  1148. fprintf(stderr, "%llu AB: (auto) user did not specify any links. waiting until we know more\n", ((now - RR->bc->getBondStartTime())));
  1149. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1150. if (_paths[i] && _paths[i]->eligible(now,_ackSendInterval)) {
  1151. _paths[i]->address().toString(curPathStr);
  1152. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1153. if (link) {
  1154. fprintf(stderr, "%llu AB: (initial) [%d] found eligible path %s on: %s\n", ((now - RR->bc->getBondStartTime())), i, curPathStr, link->ifname().c_str());
  1155. }
  1156. _abPath = _paths[i];
  1157. break;
  1158. }
  1159. }
  1160. }
  1161. /**
  1162. * [Manual mode]
  1163. * The user has specified links or failover rules that the bonding policy should adhere to.
  1164. */
  1165. else if (userHasSpecifiedLinks()) {
  1166. fprintf(stderr, "%llu AB: (manual) no active backup link, checking local.conf\n", ((now - RR->bc->getBondStartTime())));
  1167. if (userHasSpecifiedPrimaryLink()) {
  1168. fprintf(stderr, "%llu AB: (manual) user has specified primary link, looking for it.\n", ((now - RR->bc->getBondStartTime())));
  1169. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1170. if (!_paths[i]) {
  1171. continue;
  1172. }
  1173. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1174. if (_paths[i]->eligible(now,_ackSendInterval) && link->primary()) {
  1175. if (!_paths[i]->preferred()) {
  1176. _paths[i]->address().toString(curPathStr);
  1177. fprintf(stderr, "%llu AB: (initial) [%d] found path on primary link, taking note in case we don't find a preferred path\n", ((now - RR->bc->getBondStartTime())), i);
  1178. nonPreferredPath = _paths[i];
  1179. bFoundPrimaryLink = true;
  1180. }
  1181. if (_paths[i]->preferred()) {
  1182. _abPath = _paths[i];
  1183. _abPath->address().toString(curPathStr);
  1184. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1185. if (link) {
  1186. fprintf(stderr, "%llu AB: (initial) [%d] found preferred path %s on primary link: %s\n", ((now - RR->bc->getBondStartTime())), i, curPathStr, link->ifname().c_str());
  1187. }
  1188. bFoundPrimaryLink = true;
  1189. break;
  1190. }
  1191. }
  1192. }
  1193. if (_abPath) {
  1194. _abPath->address().toString(curPathStr);
  1195. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _abPath->localSocket());
  1196. if (link) {
  1197. fprintf(stderr, "%llu AB: (initial) found preferred primary path: %s on %s\n", ((now - RR->bc->getBondStartTime())), curPathStr, link->ifname().c_str());
  1198. }
  1199. }
  1200. else {
  1201. if (bFoundPrimaryLink && nonPreferredPath) {
  1202. fprintf(stderr, "%llu AB: (initial) found a non-preferred primary path\n", ((now - RR->bc->getBondStartTime())));
  1203. _abPath = nonPreferredPath;
  1204. }
  1205. }
  1206. if (!_abPath) {
  1207. fprintf(stderr, "%llu AB: (initial) designated primary link is not yet ready\n", ((now - RR->bc->getBondStartTime())));
  1208. // TODO: Should fail-over to specified backup or just wait?
  1209. }
  1210. }
  1211. else if (!userHasSpecifiedPrimaryLink()) {
  1212. int _abIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1213. fprintf(stderr, "%llu AB: (initial) user did not specify primary link, just picking something\n", ((now - RR->bc->getBondStartTime())));
  1214. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1215. if (_paths[i] && _paths[i]->eligible(now,_ackSendInterval)) {
  1216. _abIdx = i;
  1217. break;
  1218. }
  1219. }
  1220. if (_abIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1221. fprintf(stderr, "%llu AB: (initial) unable to find a candidate next-best, no change\n", ((now - RR->bc->getBondStartTime())));
  1222. }
  1223. else {
  1224. _abPath = _paths[_abIdx];
  1225. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _abPath->localSocket());
  1226. if (link) {
  1227. fprintf(stderr, "%llu AB: (initial) selected non-primary link idx=%d, %s on %s\n", ((now - RR->bc->getBondStartTime())), _abIdx, pathStr, link->ifname().c_str());
  1228. }
  1229. }
  1230. }
  1231. }
  1232. }
  1233. /**
  1234. * Update and maintain the active-backup failover queue
  1235. */
  1236. if (_abPath) {
  1237. // Don't worry about the failover queue until we have an active link
  1238. // Remove ineligible paths from the failover link queue
  1239. for (std::list<SharedPtr<Path> >::iterator it(_abFailoverQueue.begin()); it!=_abFailoverQueue.end();) {
  1240. if ((*it) && !(*it)->eligible(now,_ackSendInterval)) {
  1241. (*it)->address().toString(curPathStr);
  1242. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, (*it)->localSocket());
  1243. if (link) {
  1244. fprintf(stderr, "%llu AB: (fq) %s on %s is now ineligible, removing from failover queue\n", ((now - RR->bc->getBondStartTime())), curPathStr, link->ifname().c_str());
  1245. }
  1246. it = _abFailoverQueue.erase(it);
  1247. } else {
  1248. ++it;
  1249. }
  1250. }
  1251. /**
  1252. * Failover instructions were provided by user, build queue according those as well as IPv
  1253. * preference, disregarding performance.
  1254. */
  1255. if (userHasSpecifiedFailoverInstructions()) {
  1256. /**
  1257. * Clear failover scores
  1258. */
  1259. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1260. if (_paths[i]) {
  1261. _paths[i]->_failoverScore = 0;
  1262. }
  1263. }
  1264. //fprintf(stderr, "AB: (fq) user has specified specific failover instructions, will follow them.\n");
  1265. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1266. if (!_paths[i] || !_paths[i]->allowed() || !_paths[i]->eligible(now,_ackSendInterval)) {
  1267. continue;
  1268. }
  1269. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1270. _paths[i]->address().toString(pathStr);
  1271. int failoverScoreHandicap = _paths[i]->_failoverScore;
  1272. if (_paths[i]->preferred())
  1273. {
  1274. failoverScoreHandicap += ZT_MULTIPATH_FAILOVER_HANDICAP_PREFERRED;
  1275. //fprintf(stderr, "%s on %s ----> %d for preferred\n", pathStr, _paths[i]->ifname().c_str(), failoverScoreHandicap);
  1276. }
  1277. if (link->primary()) {
  1278. // If using "optimize" primary reselect mode, ignore user link designations
  1279. failoverScoreHandicap += ZT_MULTIPATH_FAILOVER_HANDICAP_PRIMARY;
  1280. //fprintf(stderr, "%s on %s ----> %d for primary\n", pathStr, _paths[i]->ifname().c_str(), failoverScoreHandicap);
  1281. }
  1282. if (!_paths[i]->_failoverScore) {
  1283. // If we didn't inherit a failover score from a "parent" that wants to use this path as a failover
  1284. int newHandicap = failoverScoreHandicap ? failoverScoreHandicap : _paths[i]->_allocation;
  1285. _paths[i]->_failoverScore = newHandicap;
  1286. //fprintf(stderr, "%s on %s ----> %d for allocation\n", pathStr, _paths[i]->ifname().c_str(), newHandicap);
  1287. }
  1288. SharedPtr<Link> failoverLink;
  1289. if (link->failoverToLink().length()) {
  1290. failoverLink = RR->bc->getLinkByName(_policyAlias, link->failoverToLink());
  1291. }
  1292. if (failoverLink) {
  1293. for (int j=0; j<ZT_MAX_PEER_NETWORK_PATHS; j++) {
  1294. if (_paths[j] && getLink(_paths[j]) == failoverLink.ptr()) {
  1295. _paths[j]->address().toString(pathStr);
  1296. int inheritedHandicap = failoverScoreHandicap - 10;
  1297. int newHandicap = _paths[j]->_failoverScore > inheritedHandicap ? _paths[j]->_failoverScore : inheritedHandicap;
  1298. //fprintf(stderr, "\thanding down %s on %s ----> %d\n", pathStr, getLink(_paths[j])->ifname().c_str(), newHandicap);
  1299. if (!_paths[j]->preferred()) {
  1300. newHandicap--;
  1301. }
  1302. _paths[j]->_failoverScore = newHandicap;
  1303. }
  1304. }
  1305. }
  1306. if (_paths[i].ptr() != _abPath.ptr()) {
  1307. bool bFoundPathInQueue = false;
  1308. for (std::list<SharedPtr<Path> >::iterator it(_abFailoverQueue.begin()); it!=_abFailoverQueue.end();++it) {
  1309. if (_paths[i].ptr() == (*it).ptr()) {
  1310. bFoundPathInQueue = true;
  1311. }
  1312. }
  1313. if (!bFoundPathInQueue) {
  1314. _paths[i]->address().toString(curPathStr);
  1315. fprintf(stderr, "%llu AB: (fq) [%d] added %s on %s to queue\n", ((now - RR->bc->getBondStartTime())), i, curPathStr, getLink(_paths[i])->ifname().c_str());
  1316. _abFailoverQueue.push_front(_paths[i]);
  1317. }
  1318. }
  1319. }
  1320. }
  1321. /**
  1322. * No failover instructions provided by user, build queue according to performance
  1323. * and IPv preference.
  1324. */
  1325. else if (!userHasSpecifiedFailoverInstructions()) {
  1326. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1327. if (!_paths[i]
  1328. || !_paths[i]->allowed()
  1329. || !_paths[i]->eligible(now,_ackSendInterval)) {
  1330. continue;
  1331. }
  1332. int failoverScoreHandicap = 0;
  1333. if (_paths[i]->preferred()) {
  1334. failoverScoreHandicap = ZT_MULTIPATH_FAILOVER_HANDICAP_PREFERRED;
  1335. }
  1336. bool includeRefractoryPeriod = true;
  1337. if (!_paths[i]->eligible(now,includeRefractoryPeriod)) {
  1338. failoverScoreHandicap = -10000;
  1339. }
  1340. if (getLink(_paths[i])->primary() && _abLinkSelectMethod != ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE) {
  1341. // If using "optimize" primary reselect mode, ignore user link designations
  1342. failoverScoreHandicap = ZT_MULTIPATH_FAILOVER_HANDICAP_PRIMARY;
  1343. }
  1344. if (_paths[i].ptr() == negotiatedPath.ptr()) {
  1345. _paths[i]->_negotiated = true;
  1346. failoverScoreHandicap = ZT_MULTIPATH_FAILOVER_HANDICAP_NEGOTIATED;
  1347. } else {
  1348. _paths[i]->_negotiated = false;
  1349. }
  1350. _paths[i]->_failoverScore = _paths[i]->_allocation + failoverScoreHandicap;
  1351. if (_paths[i].ptr() != _abPath.ptr()) {
  1352. bool bFoundPathInQueue = false;
  1353. for (std::list<SharedPtr<Path> >::iterator it(_abFailoverQueue.begin()); it!=_abFailoverQueue.end();++it) {
  1354. if (_paths[i].ptr() == (*it).ptr()) {
  1355. bFoundPathInQueue = true;
  1356. }
  1357. }
  1358. if (!bFoundPathInQueue) {
  1359. _paths[i]->address().toString(curPathStr);
  1360. fprintf(stderr, "%llu AB: (fq) [%d] added %s on %s to queue\n", ((now - RR->bc->getBondStartTime())), i, curPathStr, getLink(_paths[i])->ifname().c_str());
  1361. _abFailoverQueue.push_front(_paths[i]);
  1362. }
  1363. }
  1364. }
  1365. }
  1366. _abFailoverQueue.sort(PathQualityComparator());
  1367. if (_abFailoverQueue.empty()) {
  1368. fprintf(stderr, "%llu AB: (fq) the failover queue is empty, the active-backup bond is no longer fault-tolerant\n", ((now - RR->bc->getBondStartTime())));
  1369. }
  1370. }
  1371. /**
  1372. * Short-circuit if we have no queued paths
  1373. */
  1374. if (_abFailoverQueue.empty()) {
  1375. return;
  1376. }
  1377. /**
  1378. * Fulfill primary reselect obligations
  1379. */
  1380. if (_abPath && !_abPath->eligible(now,_ackSendInterval)) { // Implicit ZT_MULTIPATH_RESELECTION_POLICY_FAILURE
  1381. _abPath->address().toString(curPathStr); fprintf(stderr, "%llu AB: (failure) failover event!, active backup path (%s) is no-longer eligible\n", ((now - RR->bc->getBondStartTime())), curPathStr);
  1382. if (!_abFailoverQueue.empty()) {
  1383. fprintf(stderr, "%llu AB: (failure) there are (%lu) links in queue to choose from...\n", ((now - RR->bc->getBondStartTime())), _abFailoverQueue.size());
  1384. dequeueNextActiveBackupPath(now);
  1385. _abPath->address().toString(curPathStr); fprintf(stderr, "%llu AB: (failure) switched to %s on %s\n", ((now - RR->bc->getBondStartTime())), curPathStr, getLink(_abPath)->ifname().c_str());
  1386. } else {
  1387. fprintf(stderr, "%llu AB: (failure) nothing available in the link queue, doing nothing.\n", ((now - RR->bc->getBondStartTime())));
  1388. }
  1389. }
  1390. /**
  1391. * Detect change to prevent flopping during later optimization step.
  1392. */
  1393. if (prevActiveBackupPath != _abPath) {
  1394. _lastActiveBackupPathChange = now;
  1395. }
  1396. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_ALWAYS) {
  1397. if (_abPath && !getLink(_abPath)->primary()
  1398. && getLink(_abFailoverQueue.front())->primary()) {
  1399. fprintf(stderr, "%llu AB: (always) switching to available primary\n", ((now - RR->bc->getBondStartTime())));
  1400. dequeueNextActiveBackupPath(now);
  1401. }
  1402. }
  1403. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_BETTER) {
  1404. if (_abPath && !getLink(_abPath)->primary()) {
  1405. fprintf(stderr, "%llu AB: (better) active backup has switched to \"better\" primary link according to re-select policy.\n", ((now - RR->bc->getBondStartTime())));
  1406. if (getLink(_abFailoverQueue.front())->primary()
  1407. && (_abFailoverQueue.front()->_failoverScore > _abPath->_failoverScore)) {
  1408. dequeueNextActiveBackupPath(now);
  1409. fprintf(stderr, "%llu AB: (better) switched back to user-defined primary\n", ((now - RR->bc->getBondStartTime())));
  1410. }
  1411. }
  1412. }
  1413. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE && !_abFailoverQueue.empty()) {
  1414. /**
  1415. * Implement link negotiation that was previously-decided
  1416. */
  1417. if (_abFailoverQueue.front()->_negotiated) {
  1418. dequeueNextActiveBackupPath(now);
  1419. _abPath->address().toString(prevPathStr);
  1420. fprintf(stderr, "%llu AB: (optimize) switched to negotiated path %s on %s\n", ((now - RR->bc->getBondStartTime())), prevPathStr, getLink(_abPath)->ifname().c_str());
  1421. _lastPathNegotiationCheck = now;
  1422. }
  1423. else {
  1424. // Try to find a better path and automatically switch to it -- not too often, though.
  1425. if ((now - _lastActiveBackupPathChange) > ZT_MULTIPATH_MIN_ACTIVE_BACKUP_AUTOFLOP_INTERVAL) {
  1426. if (!_abFailoverQueue.empty()) {
  1427. //fprintf(stderr, "AB: (optimize) there are (%d) links in queue to choose from...\n", _abFailoverQueue.size());
  1428. int newFScore = _abFailoverQueue.front()->_failoverScore;
  1429. int prevFScore = _abPath->_failoverScore;
  1430. // Establish a minimum switch threshold to prevent flapping
  1431. int failoverScoreDifference = _abFailoverQueue.front()->_failoverScore - _abPath->_failoverScore;
  1432. int thresholdQuantity = (ZT_MULTIPATH_ACTIVE_BACKUP_OPTIMIZE_MIN_THRESHOLD * (float)_abPath->_allocation);
  1433. if ((failoverScoreDifference > 0) && (failoverScoreDifference > thresholdQuantity)) {
  1434. SharedPtr<Path> oldPath = _abPath;
  1435. _abPath->address().toString(prevPathStr);
  1436. dequeueNextActiveBackupPath(now);
  1437. _abPath->address().toString(curPathStr);
  1438. fprintf(stderr, "%llu AB: (optimize) switched from %s on %s (fs=%d) to %s on %s (fs=%d)\n", ((now - RR->bc->getBondStartTime())), prevPathStr, getLink(oldPath)->ifname().c_str(), prevFScore, curPathStr, getLink(_abPath)->ifname().c_str(), newFScore);
  1439. }
  1440. }
  1441. }
  1442. }
  1443. }
  1444. }
  1445. void Bond::setReasonableDefaults(int policy, SharedPtr<Bond> templateBond, bool useTemplate)
  1446. {
  1447. // If invalid bonding policy, try default
  1448. int _defaultBondingPolicy = BondController::defaultBondingPolicy();
  1449. if (policy <= ZT_BONDING_POLICY_NONE || policy > ZT_BONDING_POLICY_BALANCE_AWARE) {
  1450. // If no default set, use NONE (effectively disabling this bond)
  1451. if (_defaultBondingPolicy < ZT_BONDING_POLICY_NONE || _defaultBondingPolicy > ZT_BONDING_POLICY_BALANCE_AWARE) {
  1452. _bondingPolicy= ZT_BONDING_POLICY_NONE;
  1453. }
  1454. _bondingPolicy= _defaultBondingPolicy;
  1455. } else {
  1456. _bondingPolicy= policy;
  1457. }
  1458. _freeRandomByte = 0;
  1459. _lastCheckUserPreferences = 0;
  1460. _lastBackgroundTaskCheck = 0;
  1461. _downDelay = 0;
  1462. _upDelay = 0;
  1463. _allowFlowHashing=false;
  1464. _bondMonitorInterval=0;
  1465. _shouldCollectPathStatistics=false;
  1466. // Path negotiation
  1467. _allowPathNegotiation=false;
  1468. _lastPathNegotiationReceived=0;
  1469. _lastPathNegotiationCheck=0;
  1470. _pathNegotiationCutoffCount=0;
  1471. _localUtility=0;
  1472. _lastFlowStatReset=0;
  1473. _lastFlowExpirationCheck=0;
  1474. _numBondedPaths=0;
  1475. _rrPacketsSentOnCurrLink=0;
  1476. _rrIdx=0;
  1477. _lastFlowRebalance=0;
  1478. _totalBondUnderload = 0;
  1479. _maxAcceptableLatency = 100;
  1480. _maxAcceptablePacketDelayVariance = 50;
  1481. _maxAcceptablePacketLossRatio = 0.10;
  1482. _maxAcceptablePacketErrorRatio = 0.10;
  1483. _userHasSpecifiedLinkSpeeds=0;
  1484. _lastFrame=0;
  1485. /* ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_PASSIVE is the most conservative strategy and is
  1486. least likely to cause unexpected behavior */
  1487. _flowRebalanceStrategy = ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_AGGRESSIVE;
  1488. /**
  1489. * Paths are actively monitored to provide a real-time quality/preference-ordered rapid failover queue.
  1490. */
  1491. switch (policy) {
  1492. case ZT_BONDING_POLICY_ACTIVE_BACKUP:
  1493. _failoverInterval = 500;
  1494. _abLinkSelectMethod = ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE;
  1495. _linkMonitorStrategy = ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC;
  1496. _qualityWeights[ZT_QOS_LAT_IDX] = 0.2f;
  1497. _qualityWeights[ZT_QOS_LTM_IDX] = 0.0f;
  1498. _qualityWeights[ZT_QOS_PDV_IDX] = 0.2f;
  1499. _qualityWeights[ZT_QOS_PLR_IDX] = 0.2f;
  1500. _qualityWeights[ZT_QOS_PER_IDX] = 0.2f;
  1501. _qualityWeights[ZT_QOS_THR_IDX] = 0.2f;
  1502. _qualityWeights[ZT_QOS_THM_IDX] = 0.0f;
  1503. _qualityWeights[ZT_QOS_THV_IDX] = 0.0f;
  1504. _qualityWeights[ZT_QOS_SCP_IDX] = 0.0f;
  1505. break;
  1506. /**
  1507. * All seemingly-alive paths are used. Paths are not actively monitored.
  1508. */
  1509. case ZT_BONDING_POLICY_BROADCAST:
  1510. _downDelay = 30000;
  1511. _upDelay = 0;
  1512. break;
  1513. /**
  1514. * Paths are monitored to determine when/if one needs to be added or removed from the rotation
  1515. */
  1516. case ZT_BONDING_POLICY_BALANCE_RR:
  1517. _failoverInterval = 500;
  1518. _allowFlowHashing = false;
  1519. _packetsPerLink = 1024;
  1520. _linkMonitorStrategy = ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC;
  1521. _qualityWeights[ZT_QOS_LAT_IDX] = 0.4f;
  1522. _qualityWeights[ZT_QOS_LTM_IDX] = 0.0f;
  1523. _qualityWeights[ZT_QOS_PDV_IDX] = 0.2f;
  1524. _qualityWeights[ZT_QOS_PLR_IDX] = 0.1f;
  1525. _qualityWeights[ZT_QOS_PER_IDX] = 0.1f;
  1526. _qualityWeights[ZT_QOS_THR_IDX] = 0.1f;
  1527. _qualityWeights[ZT_QOS_THM_IDX] = 0.0f;
  1528. _qualityWeights[ZT_QOS_THV_IDX] = 0.0f;
  1529. _qualityWeights[ZT_QOS_SCP_IDX] = 0.0f;
  1530. break;
  1531. /**
  1532. * Path monitoring is used to determine the capacity of each
  1533. * path and where to place the next flow.
  1534. */
  1535. case ZT_BONDING_POLICY_BALANCE_XOR:
  1536. _failoverInterval = 500;
  1537. _upDelay = _bondMonitorInterval * 2;
  1538. _allowFlowHashing = true;
  1539. _linkMonitorStrategy = ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC;
  1540. _qualityWeights[ZT_QOS_LAT_IDX] = 0.4f;
  1541. _qualityWeights[ZT_QOS_LTM_IDX] = 0.0f;
  1542. _qualityWeights[ZT_QOS_PDV_IDX] = 0.2f;
  1543. _qualityWeights[ZT_QOS_PLR_IDX] = 0.1f;
  1544. _qualityWeights[ZT_QOS_PER_IDX] = 0.1f;
  1545. _qualityWeights[ZT_QOS_THR_IDX] = 0.1f;
  1546. _qualityWeights[ZT_QOS_THM_IDX] = 0.0f;
  1547. _qualityWeights[ZT_QOS_THV_IDX] = 0.0f;
  1548. _qualityWeights[ZT_QOS_SCP_IDX] = 0.0f;
  1549. break;
  1550. /**
  1551. * Path monitoring is used to determine the capacity of each
  1552. * path and where to place the next flow. Additionally, re-shuffling
  1553. * of flows may take place.
  1554. */
  1555. case ZT_BONDING_POLICY_BALANCE_AWARE:
  1556. _failoverInterval = 3000;
  1557. _allowFlowHashing = true;
  1558. _linkMonitorStrategy = ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC;
  1559. _qualityWeights[ZT_QOS_LAT_IDX] = 0.4f;
  1560. _qualityWeights[ZT_QOS_LTM_IDX] = 0.0f;
  1561. _qualityWeights[ZT_QOS_PDV_IDX] = 0.4f;
  1562. _qualityWeights[ZT_QOS_PLR_IDX] = 0.2f;
  1563. _qualityWeights[ZT_QOS_PER_IDX] = 0.0f;
  1564. _qualityWeights[ZT_QOS_THR_IDX] = 0.0f;
  1565. _qualityWeights[ZT_QOS_THM_IDX] = 0.0f;
  1566. _qualityWeights[ZT_QOS_THV_IDX] = 0.0f;
  1567. _qualityWeights[ZT_QOS_SCP_IDX] = 0.0f;
  1568. break;
  1569. default:
  1570. break;
  1571. }
  1572. /* If a user has specified custom parameters for this bonding policy, overlay
  1573. them onto the defaults that were previously set */
  1574. if (useTemplate) {
  1575. _policyAlias = templateBond->_policyAlias;
  1576. _failoverInterval = templateBond->_failoverInterval;
  1577. _downDelay = templateBond->_downDelay;
  1578. _upDelay = templateBond->_upDelay;
  1579. fprintf(stderr, "TIMERS: strat=%d, fi= %d, bmi= %d, qos= %d, ack= %d, estimateInt= %d, refractory= %d, ud= %d, dd= %d\n",
  1580. _linkMonitorStrategy,
  1581. _failoverInterval,
  1582. _bondMonitorInterval,
  1583. _qosSendInterval,
  1584. _ackSendInterval,
  1585. _qualityEstimationInterval,
  1586. _defaultPathRefractoryPeriod,
  1587. _upDelay,
  1588. _downDelay);
  1589. if (templateBond->_linkMonitorStrategy == ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_PASSIVE
  1590. && templateBond->_failoverInterval != 0) {
  1591. fprintf(stderr, "warning: passive path monitoring was specified, this will prevent failovers from happening in a timely manner.\n");
  1592. }
  1593. _abLinkSelectMethod = templateBond->_abLinkSelectMethod;
  1594. memcpy(_qualityWeights, templateBond->_qualityWeights, ZT_QOS_WEIGHT_SIZE * sizeof(float));
  1595. }
  1596. //
  1597. // Second, apply user specified values (only if they make sense)
  1598. /**
  1599. * Timer geometries and counters
  1600. */
  1601. // TODO: Think more about the maximum
  1602. /*
  1603. if (originalBond._failoverInterval > 250 && originalBond._failoverInterval < 65535) {
  1604. _failoverInterval = originalBond._failoverInterval;
  1605. }
  1606. else {
  1607. fprintf(stderr, "warning: _failoverInterval (%d) is out of range, using default (%d)\n", originalBond._failoverInterval, _failoverInterval);
  1608. }
  1609. */
  1610. _bondMonitorInterval = _failoverInterval / 3;
  1611. BondController::setMinReqPathMonitorInterval(_bondMonitorInterval);
  1612. _ackSendInterval = _failoverInterval;
  1613. _qualityEstimationInterval = _failoverInterval * 2;
  1614. _dynamicPathMonitorInterval = 0;
  1615. _ackCutoffCount = 0;
  1616. _lastAckRateCheck = 0;
  1617. _qosSendInterval = _bondMonitorInterval * 4;
  1618. _qosCutoffCount = 0;
  1619. _lastQoSRateCheck = 0;
  1620. _lastQualityEstimation=0;
  1621. throughputMeasurementInterval = _ackSendInterval * 2;
  1622. _defaultPathRefractoryPeriod = 8000;
  1623. }
  1624. void Bond::setUserQualityWeights(float weights[], int len)
  1625. {
  1626. if (len == ZT_QOS_WEIGHT_SIZE) {
  1627. float weightTotal = 0.0;
  1628. for (unsigned int i=0; i<ZT_QOS_WEIGHT_SIZE; ++i) {
  1629. weightTotal += weights[i];
  1630. }
  1631. if (weightTotal > 0.99 && weightTotal < 1.01) {
  1632. memcpy(_qualityWeights, weights, len * sizeof(float));
  1633. }
  1634. }
  1635. }
  1636. bool Bond::relevant() {
  1637. return _peer->identity().address().toInt() == 0x16a03a3d03
  1638. || _peer->identity().address().toInt() == 0x4410300d03
  1639. || _peer->identity().address().toInt() == 0x795cbf86fa;
  1640. }
  1641. SharedPtr<Link> Bond::getLink(const SharedPtr<Path>& path)
  1642. {
  1643. return RR->bc->getLinkBySocket(_policyAlias, path->localSocket());
  1644. }
  1645. void Bond::dumpInfo(const int64_t now)
  1646. {
  1647. char pathStr[128];
  1648. //char oldPathStr[128];
  1649. char currPathStr[128];
  1650. if (!relevant()) {
  1651. return;
  1652. }
  1653. /*
  1654. fprintf(stderr, "---[ bp=%d, id=%llx, dd=%d, up=%d, pmi=%d, specifiedLinks=%d, _specifiedPrimaryLink=%d, _specifiedFailInst=%d ]\n",
  1655. _policy, _peer->identity().address().toInt(), _downDelay, _upDelay, _monitorInterval, _userHasSpecifiedLinks, _userHasSpecifiedPrimaryLink, _userHasSpecifiedFailoverInstructions);
  1656. if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  1657. fprintf(stderr, "Paths (bp=%d, stats=%d, primaryReselect=%d) :\n",
  1658. _policy, _shouldCollectPathStatistics, _abLinkSelectMethod);
  1659. }
  1660. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR
  1661. || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR
  1662. || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  1663. fprintf(stderr, "Paths (bp=%d, stats=%d, fh=%d) :\n",
  1664. _policy, _shouldCollectPathStatistics, _allowFlowHashing);
  1665. }*/
  1666. if ((now - _lastPrintTS) < 2000) {
  1667. return;
  1668. }
  1669. _lastPrintTS = now;
  1670. fprintf(stderr, "\n\n");
  1671. for(int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1672. if (_paths[i]) {
  1673. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1674. _paths[i]->address().toString(pathStr);
  1675. fprintf(stderr, " %2d: lat=%8.3f, ac=%3d, fail%5s, fscore=%6d, in=%7d, out=%7d, age=%7ld, ack=%7ld, ref=%6d, ls=%llx",
  1676. i,
  1677. _paths[i]->_latencyMean,
  1678. _paths[i]->_allocation,
  1679. link->failoverToLink().c_str(),
  1680. _paths[i]->_failoverScore,
  1681. _paths[i]->_packetsIn,
  1682. _paths[i]->_packetsOut,
  1683. (long)_paths[i]->age(now),
  1684. (long)_paths[i]->ackAge(now),
  1685. _paths[i]->_refractoryPeriod,
  1686. _paths[i]->localSocket()
  1687. );
  1688. if (link->spare()) {
  1689. fprintf(stderr, " SPR.");
  1690. } else {
  1691. fprintf(stderr, " ");
  1692. }
  1693. if (link->primary()) {
  1694. fprintf(stderr, " PRIM.");
  1695. } else {
  1696. fprintf(stderr, " ");
  1697. }
  1698. if (_paths[i]->allowed()) {
  1699. fprintf(stderr, " ALL.");
  1700. } else {
  1701. fprintf(stderr, " ");
  1702. }
  1703. if (_paths[i]->eligible(now,_ackSendInterval)) {
  1704. fprintf(stderr, " ELI.");
  1705. } else {
  1706. fprintf(stderr, " ");
  1707. }
  1708. if (_paths[i]->preferred()) {
  1709. fprintf(stderr, " PREF.");
  1710. } else {
  1711. fprintf(stderr, " ");
  1712. }
  1713. if (_paths[i]->_negotiated) {
  1714. fprintf(stderr, " NEG.");
  1715. } else {
  1716. fprintf(stderr, " ");
  1717. }
  1718. if (_paths[i]->bonded()) {
  1719. fprintf(stderr, " BOND ");
  1720. } else {
  1721. fprintf(stderr, " ");
  1722. }
  1723. if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP && _abPath && (_abPath == _paths[i].ptr())) {
  1724. fprintf(stderr, " ACTIVE ");
  1725. } else if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  1726. fprintf(stderr, " ");
  1727. }
  1728. if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP && _abFailoverQueue.size() && (_abFailoverQueue.front().ptr() == _paths[i].ptr())) {
  1729. fprintf(stderr, " NEXT ");
  1730. } else if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  1731. fprintf(stderr, " ");
  1732. }
  1733. fprintf(stderr, "%5s %s\n", link->ifname().c_str(), pathStr);
  1734. }
  1735. }
  1736. if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  1737. if (!_abFailoverQueue.empty()) {
  1738. fprintf(stderr, "\nFailover Queue:\n");
  1739. for (std::list<SharedPtr<Path> >::iterator it(_abFailoverQueue.begin()); it!=_abFailoverQueue.end();++it) {
  1740. (*it)->address().toString(currPathStr);
  1741. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, (*it)->localSocket());
  1742. fprintf(stderr, "\t%8s\tspeed=%7d\trelSpeed=%3d\tipvPref=%3d\tfscore=%9d\t\t%s\n",
  1743. link->ifname().c_str(),
  1744. link->speed(),
  1745. link->relativeSpeed(),
  1746. link->ipvPref(),
  1747. (*it)->_failoverScore,
  1748. currPathStr);
  1749. }
  1750. }
  1751. else
  1752. {
  1753. fprintf(stderr, "\nFailover Queue size = %lu\n", _abFailoverQueue.size());
  1754. }
  1755. }
  1756. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR
  1757. || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR
  1758. || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  1759. if (_numBondedPaths) {
  1760. fprintf(stderr, "\nBonded Paths:\n");
  1761. for (int i=0; i<_numBondedPaths; ++i) {
  1762. _paths[_bondedIdx[i]]->address().toString(currPathStr);
  1763. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[_bondedIdx[i]]->localSocket());
  1764. fprintf(stderr, " [%d]\t%8s\tflows=%3d\tspeed=%7d\trelSpeed=%3d\tipvPref=%3d\tfscore=%9d\t\t%s\n", i,
  1765. //fprintf(stderr, " [%d]\t%8s\tspeed=%7d\trelSpeed=%3d\tflowCount=%2d\tipvPref=%3d\tfscore=%9d\t\t%s\n", i,
  1766. link->ifname().c_str(),
  1767. _paths[_bondedIdx[i]]->_assignedFlowCount,
  1768. link->speed(),
  1769. link->relativeSpeed(),
  1770. //_paths[_bondedIdx[i]].p->assignedFlows.size(),
  1771. link->ipvPref(),
  1772. _paths[_bondedIdx[i]]->_failoverScore,
  1773. currPathStr);
  1774. }
  1775. }
  1776. }
  1777. }
  1778. } // namespace ZeroTier