Bond.cpp 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772
  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. uint8_t tmpNumAliveLinks = 0;
  705. uint8_t tmpNumTotalLinks = 0;
  706. /**
  707. * Update path states
  708. */
  709. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  710. if (!_paths[i]) {
  711. continue;
  712. }
  713. tmpNumTotalLinks++;
  714. if (_paths[i]->alive(now, true)) {
  715. tmpNumAliveLinks++;
  716. }
  717. bool currEligibility = _paths[i]->eligible(now,_ackSendInterval);
  718. //_paths[i]->address().toString(pathStr);
  719. //fprintf(stderr, "\n\n%ld path eligibility (for %s, %s):\n", (RR->node->now() - RR->bc->getBondStartTime()), getLink(_paths[i])->ifname().c_str(), pathStr);
  720. //_paths[i]->printEligible(now,_ackSendInterval);
  721. if (currEligibility != _paths[i]->_lastEligibilityState) {
  722. _paths[i]->address().toString(pathStr);
  723. //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));
  724. if (currEligibility) {
  725. rebuildBond = true;
  726. }
  727. if (!currEligibility) {
  728. _paths[i]->adjustRefractoryPeriod(now, _defaultPathRefractoryPeriod, !currEligibility);
  729. if (_paths[i]->bonded()) {
  730. //fprintf(stderr, "the path was bonded, reallocation of its flows will occur soon\n");
  731. rebuildBond = true;
  732. _paths[i]->_shouldReallocateFlows = _paths[i]->bonded();
  733. _paths[i]->setBonded(false);
  734. } else {
  735. //fprintf(stderr, "the path was not bonded, no consequences\n");
  736. }
  737. }
  738. }
  739. if (currEligibility) {
  740. _paths[i]->adjustRefractoryPeriod(now, _defaultPathRefractoryPeriod, false);
  741. }
  742. _paths[i]->_lastEligibilityState = currEligibility;
  743. }
  744. _numAliveLinks = tmpNumAliveLinks;
  745. _numTotalLinks = tmpNumTotalLinks;
  746. /* Determine health status to report to user */
  747. bool tmpHealthStatus = true;
  748. if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  749. if (_numAliveLinks < 2) {
  750. // Considered healthy if there is at least one failover link
  751. tmpHealthStatus = false;
  752. }
  753. }
  754. if (_bondingPolicy == ZT_BONDING_POLICY_BROADCAST) {
  755. if (_numAliveLinks < 1) {
  756. // Considerd healthy if we're able to send frames at all
  757. tmpHealthStatus = false;
  758. }
  759. }
  760. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR) {
  761. if (_numAliveLinks < _numTotalLinks) {
  762. // Considerd healthy if all known paths are alive, this should be refined to account for user bond config settings
  763. tmpHealthStatus = false;
  764. }
  765. }
  766. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR) {
  767. if (_numAliveLinks < _numTotalLinks) {
  768. // Considerd healthy if all known paths are alive, this should be refined to account for user bond config settings
  769. tmpHealthStatus = false;
  770. }
  771. }
  772. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  773. if (_numAliveLinks < _numTotalLinks) {
  774. // Considerd healthy if all known paths are alive, this should be refined to account for user bond config settings
  775. tmpHealthStatus = false;
  776. }
  777. }
  778. _isHealthy = tmpHealthStatus;
  779. /**
  780. * Curate the set of paths that are part of the bond proper. Selects a single path
  781. * per logical link according to eligibility and user-specified constraints.
  782. */
  783. if ((_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR)
  784. || (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR)
  785. || (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE)) {
  786. if (!_numBondedPaths) {
  787. rebuildBond = true;
  788. }
  789. // TODO: Optimize
  790. if (rebuildBond) {
  791. int updatedBondedPathCount = 0;
  792. std::map<SharedPtr<Link>,int> linkMap;
  793. for (int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  794. if (_paths[i] && _paths[i]->allowed() && (_paths[i]->eligible(now,_ackSendInterval) || !_numBondedPaths)) {
  795. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  796. if (!linkMap.count(link)) {
  797. linkMap[link] = i;
  798. }
  799. else {
  800. bool overriden = false;
  801. _paths[i]->address().toString(pathStr);
  802. //fprintf(stderr, " link representative path already exists! (%s %s)\n", getLink(_paths[i])->ifname().c_str(), pathStr);
  803. if (_paths[i]->preferred() && !_paths[linkMap[link]]->preferred()) {
  804. // Override previous choice if preferred
  805. //fprintf(stderr, "overriding since its preferred!\n");
  806. if (_paths[linkMap[link]]->_assignedFlowCount) {
  807. _paths[linkMap[link]]->_deprecated = true;
  808. }
  809. else {
  810. _paths[linkMap[link]]->_deprecated = true;
  811. _paths[linkMap[link]]->setBonded(false);
  812. }
  813. linkMap[link] = i;
  814. overriden = true;
  815. }
  816. if ((_paths[i]->preferred() && _paths[linkMap[link]]->preferred())
  817. || (!_paths[i]->preferred() && !_paths[linkMap[link]]->preferred())) {
  818. if (_paths[i]->preferenceRank() > _paths[linkMap[link]]->preferenceRank()) {
  819. // Override if higher preference
  820. //fprintf(stderr, "overriding according to preference preferenceRank!\n");
  821. if (_paths[linkMap[link]]->_assignedFlowCount) {
  822. _paths[linkMap[link]]->_deprecated = true;
  823. }
  824. else {
  825. _paths[linkMap[link]]->_deprecated = true;
  826. _paths[linkMap[link]]->setBonded(false);
  827. }
  828. linkMap[link] = i;
  829. }
  830. }
  831. }
  832. }
  833. }
  834. std::map<SharedPtr<Link>,int>::iterator it = linkMap.begin();
  835. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  836. if (!_paths[i]) {
  837. continue;
  838. }
  839. _bondedIdx[i] = ZT_MAX_PEER_NETWORK_PATHS;
  840. if (it != linkMap.end()) {
  841. _bondedIdx[i] = it->second;
  842. _paths[_bondedIdx[i]]->setBonded(true);
  843. ++it;
  844. ++updatedBondedPathCount;
  845. _paths[_bondedIdx[i]]->address().toString(pathStr);
  846. //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);
  847. }
  848. }
  849. _numBondedPaths = updatedBondedPathCount;
  850. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR) {
  851. // Cause a RR reset since the currently used index might no longer be valid
  852. _rrPacketsSentOnCurrLink = _packetsPerLink;
  853. }
  854. }
  855. }
  856. }
  857. void Bond::estimatePathQuality(const int64_t now)
  858. {
  859. char pathStr[128];
  860. uint32_t totUserSpecifiedLinkSpeed = 0;
  861. if (_numBondedPaths) { // Compute relative user-specified speeds of links
  862. for(unsigned int i=0;i<_numBondedPaths;++i) {
  863. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  864. if (_paths[i] && _paths[i]->allowed()) {
  865. totUserSpecifiedLinkSpeed += link->speed();
  866. }
  867. }
  868. for(unsigned int i=0;i<_numBondedPaths;++i) {
  869. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  870. if (_paths[i] && _paths[i]->allowed()) {
  871. link->setRelativeSpeed(round( ((float)link->speed() / (float)totUserSpecifiedLinkSpeed) * 255));
  872. }
  873. }
  874. }
  875. float lat[ZT_MAX_PEER_NETWORK_PATHS];
  876. float pdv[ZT_MAX_PEER_NETWORK_PATHS];
  877. float plr[ZT_MAX_PEER_NETWORK_PATHS];
  878. float per[ZT_MAX_PEER_NETWORK_PATHS];
  879. float maxLAT = 0;
  880. float maxPDV = 0;
  881. float maxPLR = 0;
  882. float maxPER = 0;
  883. float quality[ZT_MAX_PEER_NETWORK_PATHS];
  884. uint8_t alloc[ZT_MAX_PEER_NETWORK_PATHS];
  885. float totQuality = 0.0f;
  886. memset(&lat, 0, sizeof(lat));
  887. memset(&pdv, 0, sizeof(pdv));
  888. memset(&plr, 0, sizeof(plr));
  889. memset(&per, 0, sizeof(per));
  890. memset(&quality, 0, sizeof(quality));
  891. memset(&alloc, 0, sizeof(alloc));
  892. // Compute initial summary statistics
  893. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  894. if (!_paths[i] || !_paths[i]->allowed()) {
  895. continue;
  896. }
  897. // Compute/Smooth average of real-world observations
  898. _paths[i]->_latencyMean = _paths[i]->latencySamples.mean();
  899. _paths[i]->_latencyVariance = _paths[i]->latencySamples.stddev();
  900. _paths[i]->_packetErrorRatio = 1.0 - (_paths[i]->packetValiditySamples.count() ? _paths[i]->packetValiditySamples.mean() : 1.0);
  901. if (userHasSpecifiedLinkSpeeds()) {
  902. // Use user-reported metrics
  903. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  904. if (link) {
  905. _paths[i]->_throughputMean = link->speed();
  906. _paths[i]->_throughputVariance = 0;
  907. }
  908. }
  909. // Drain unacknowledged QoS records
  910. std::map<uint64_t,uint64_t>::iterator it = _paths[i]->qosStatsOut.begin();
  911. uint64_t currentLostRecords = 0;
  912. while (it != _paths[i]->qosStatsOut.end()) {
  913. int qosRecordTimeout = 5000; //_paths[i]->monitorInterval() * ZT_MULTIPATH_QOS_ACK_INTERVAL_MULTIPLIER * 8;
  914. if ((now - it->second) >= qosRecordTimeout) {
  915. //fprintf(stderr, "packetId=%llx was lost\n", it->first);
  916. it = _paths[i]->qosStatsOut.erase(it);
  917. ++currentLostRecords;
  918. } else { ++it; }
  919. }
  920. quality[i]=0;
  921. totQuality=0;
  922. // Normalize raw observations according to sane limits and/or user specified values
  923. lat[i] = 1.0 / expf(4*Utils::normalize(_paths[i]->_latencyMean, 0, _maxAcceptableLatency, 0, 1));
  924. pdv[i] = 1.0 / expf(4*Utils::normalize(_paths[i]->_latencyVariance, 0, _maxAcceptablePacketDelayVariance, 0, 1));
  925. plr[i] = 1.0 / expf(4*Utils::normalize(_paths[i]->_packetLossRatio, 0, _maxAcceptablePacketLossRatio, 0, 1));
  926. per[i] = 1.0 / expf(4*Utils::normalize(_paths[i]->_packetErrorRatio, 0, _maxAcceptablePacketErrorRatio, 0, 1));
  927. //scp[i] = _paths[i]->ipvPref != 0 ? 1.0 : Utils::normalize(_paths[i]->ipScope(), InetAddress::IP_SCOPE_NONE, InetAddress::IP_SCOPE_PRIVATE, 0, 1);
  928. // Record bond-wide maximums to determine relative values
  929. maxLAT = lat[i] > maxLAT ? lat[i] : maxLAT;
  930. maxPDV = pdv[i] > maxPDV ? pdv[i] : maxPDV;
  931. maxPLR = plr[i] > maxPLR ? plr[i] : maxPLR;
  932. maxPER = per[i] > maxPER ? per[i] : maxPER;
  933. //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",
  934. // 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);
  935. }
  936. // Convert metrics to relative quantities and apply contribution weights
  937. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  938. if (_paths[i] && _paths[i]->bonded()) {
  939. quality[i] += ((maxLAT > 0.0f ? lat[i] / maxLAT : 0.0f) * _qualityWeights[ZT_QOS_LAT_IDX]);
  940. quality[i] += ((maxPDV > 0.0f ? pdv[i] / maxPDV : 0.0f) * _qualityWeights[ZT_QOS_PDV_IDX]);
  941. quality[i] += ((maxPLR > 0.0f ? plr[i] / maxPLR : 0.0f) * _qualityWeights[ZT_QOS_PLR_IDX]);
  942. quality[i] += ((maxPER > 0.0f ? per[i] / maxPER : 0.0f) * _qualityWeights[ZT_QOS_PER_IDX]);
  943. //quality[i] += (scp[i] * _qualityWeights[ZT_QOS_SCP_IDX]);
  944. totQuality += quality[i];
  945. }
  946. }
  947. //
  948. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  949. if (_paths[i] && _paths[i]->bonded()) {
  950. alloc[i] = std::ceil((quality[i] / totQuality) * (float)255);
  951. _paths[i]->_allocation = alloc[i];
  952. }
  953. }
  954. if ((now - _lastLogTS) > 500) {
  955. if (!relevant()) {return;}
  956. //fprintf(stderr, "\n");
  957. _lastLogTS = now;
  958. int numPlottablePaths=0;
  959. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  960. if (_paths[i]) {
  961. ++numPlottablePaths;
  962. _paths[i]->address().toString(pathStr);
  963. //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",
  964. // ((now - RR->bc->getBondStartTime())), i, _numBondedPaths, _paths[i]->monitorInterval,
  965. // lat[i], ltm[i], pdv[i], plr[i], per[i], thr[i], thm[i], thv[i], age[i], scp[i],
  966. // 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);
  967. }
  968. }
  969. if (numPlottablePaths < 2) {
  970. return;
  971. }
  972. if (!_header) {
  973. //fprintf(stdout, "now, bonded, relativeUnderload, flows, ");
  974. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  975. if (_paths[i]) {
  976. _paths[i]->address().toString(pathStr);
  977. std::string label = std::string((pathStr)) + " " + getLink(_paths[i])->ifname();
  978. for (int i=0; i<19; ++i) {
  979. //fprintf(stdout, "%s, ", label.c_str());
  980. }
  981. }
  982. }
  983. _header=true;
  984. }
  985. /*
  986. //fprintf(stdout, "%ld, %d, %d, %d, ",((now - RR->bc->getBondStartTime())),_numBondedPaths,_totalBondUnderload, _flows.size());
  987. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  988. if (_paths[i]) {
  989. _paths[i]->address().toString(pathStr);
  990. //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, ",
  991. 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],
  992. _paths[i]->_relativeByteLoad, _paths[i]->_assignedFlowCount, _paths[i]->alive(now, true), _paths[i]->eligible(now,_ackSendInterval), _paths[i]->qosStatsOut.size());
  993. }
  994. }*/
  995. //fprintf(stdout, "\n");
  996. }
  997. }
  998. void Bond::processBalanceTasks(const int64_t now)
  999. {
  1000. char curPathStr[128];
  1001. // TODO: Generalize
  1002. int totalAllocation = 0;
  1003. for (int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  1004. if (!_paths[i]) {
  1005. continue;
  1006. }
  1007. if (_paths[i] && _paths[i]->bonded() && _paths[i]->eligible(now,_ackSendInterval)) {
  1008. totalAllocation+=_paths[i]->_allocation;
  1009. }
  1010. }
  1011. unsigned char minimumAllocationValue = 0.33 * ((float)totalAllocation / (float)_numBondedPaths);
  1012. if (_allowFlowHashing) {
  1013. /**
  1014. * Clean up and reset flows if necessary
  1015. */
  1016. if ((now - _lastFlowExpirationCheck) > ZT_MULTIPATH_FLOW_CHECK_INTERVAL) {
  1017. Mutex::Lock _l(_flows_m);
  1018. forgetFlowsWhenNecessary(ZT_MULTIPATH_FLOW_EXPIRATION_INTERVAL,false,now);
  1019. _lastFlowExpirationCheck = now;
  1020. }
  1021. if ((now - _lastFlowStatReset) > ZT_FLOW_STATS_RESET_INTERVAL) {
  1022. Mutex::Lock _l(_flows_m);
  1023. _lastFlowStatReset = now;
  1024. std::map<int32_t,SharedPtr<Flow> >::iterator it = _flows.begin();
  1025. while (it != _flows.end()) {
  1026. it->second->resetByteCounts();
  1027. ++it;
  1028. }
  1029. }
  1030. /**
  1031. * Re-allocate flows from dead paths
  1032. */
  1033. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  1034. Mutex::Lock _l(_flows_m);
  1035. for (int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  1036. if (!_paths[i]) {
  1037. continue;
  1038. }
  1039. if (!_paths[i]->eligible(now,_ackSendInterval) && _paths[i]->_shouldReallocateFlows) {
  1040. _paths[i]->address().toString(curPathStr);
  1041. //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());
  1042. std::map<int32_t,SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1043. while (flow_it != _flows.end()) {
  1044. if (flow_it->second->assignedPath() == _paths[i]) {
  1045. if(assignFlowToBondedPath(flow_it->second, now)) {
  1046. _paths[i]->_assignedFlowCount--;
  1047. }
  1048. }
  1049. ++flow_it;
  1050. }
  1051. _paths[i]->_shouldReallocateFlows = false;
  1052. }
  1053. }
  1054. }
  1055. /**
  1056. * Re-allocate flows from under-performing
  1057. * NOTE: This could be part of the above block but was kept separate for clarity.
  1058. */
  1059. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  1060. Mutex::Lock _l(_flows_m);
  1061. for (int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  1062. if (!_paths[i]) {
  1063. continue;
  1064. }
  1065. if (_paths[i] && _paths[i]->bonded() && _paths[i]->eligible(now,_ackSendInterval) && (_paths[i]->_allocation < minimumAllocationValue) && _paths[i]->_assignedFlowCount) {
  1066. _paths[i]->address().toString(curPathStr);
  1067. //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());
  1068. std::map<int32_t,SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1069. while (flow_it != _flows.end()) {
  1070. if (flow_it->second->assignedPath() == _paths[i]) {
  1071. if(assignFlowToBondedPath(flow_it->second, now)) {
  1072. _paths[i]->_assignedFlowCount--;
  1073. }
  1074. }
  1075. ++flow_it;
  1076. }
  1077. _paths[i]->_shouldReallocateFlows = false;
  1078. }
  1079. }
  1080. }
  1081. }
  1082. /**
  1083. * Tasks specific to (Balance Round Robin)
  1084. */
  1085. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR) {
  1086. if (_allowFlowHashing) {
  1087. // TODO: Should ideally failover from (idx) to a random link, this is so that (idx+1) isn't overloaded
  1088. }
  1089. else if (!_allowFlowHashing) {
  1090. // Nothing
  1091. }
  1092. }
  1093. /**
  1094. * Tasks specific to (Balance XOR)
  1095. */
  1096. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR) {
  1097. // Nothing specific for XOR
  1098. }
  1099. /**
  1100. * Tasks specific to (Balance Aware)
  1101. */
  1102. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  1103. if (_allowFlowHashing) {
  1104. Mutex::Lock _l(_flows_m);
  1105. if (_flowRebalanceStrategy == ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_PASSIVE) {
  1106. // Do nothing here, this is taken care of in the more general case above.
  1107. }
  1108. if (_flowRebalanceStrategy == ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_OPPORTUNISTIC) {
  1109. // If the flow is temporarily inactive we should take this opportunity to re-assign the flow if needed.
  1110. }
  1111. if (_flowRebalanceStrategy == ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_AGGRESSIVE) {
  1112. /**
  1113. * Return flows to the original path if it has once again become available
  1114. */
  1115. if ((now - _lastFlowRebalance) > ZT_FLOW_REBALANCE_INTERVAL) {
  1116. std::map<int32_t,SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1117. while (flow_it != _flows.end()) {
  1118. if (flow_it->second->_previouslyAssignedPath && flow_it->second->_previouslyAssignedPath->eligible(now, _ackSendInterval)
  1119. && (flow_it->second->_previouslyAssignedPath->_allocation >= (minimumAllocationValue * 2))) {
  1120. //fprintf(stderr, "moving flow back onto its previous path assignment (based on eligibility)\n");
  1121. (flow_it->second->_assignedPath->_assignedFlowCount)--;
  1122. flow_it->second->assignPath(flow_it->second->_previouslyAssignedPath,now);
  1123. (flow_it->second->_previouslyAssignedPath->_assignedFlowCount)++;
  1124. }
  1125. ++flow_it;
  1126. }
  1127. _lastFlowRebalance = now;
  1128. }
  1129. /**
  1130. * Return flows to the original path if it has once again become (performant)
  1131. */
  1132. if ((now - _lastFlowRebalance) > ZT_FLOW_REBALANCE_INTERVAL) {
  1133. std::map<int32_t,SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1134. while (flow_it != _flows.end()) {
  1135. if (flow_it->second->_previouslyAssignedPath && flow_it->second->_previouslyAssignedPath->eligible(now, _ackSendInterval)
  1136. && (flow_it->second->_previouslyAssignedPath->_allocation >= (minimumAllocationValue * 2))) {
  1137. //fprintf(stderr, "moving flow back onto its previous path assignment (based on performance)\n");
  1138. (flow_it->second->_assignedPath->_assignedFlowCount)--;
  1139. flow_it->second->assignPath(flow_it->second->_previouslyAssignedPath,now);
  1140. (flow_it->second->_previouslyAssignedPath->_assignedFlowCount)++;
  1141. }
  1142. ++flow_it;
  1143. }
  1144. _lastFlowRebalance = now;
  1145. }
  1146. }
  1147. }
  1148. else if (!_allowFlowHashing) {
  1149. // Nothing
  1150. }
  1151. }
  1152. }
  1153. void Bond::dequeueNextActiveBackupPath(const uint64_t now)
  1154. {
  1155. //fprintf(stderr, "dequeueNextActiveBackupPath\n");
  1156. if (_abFailoverQueue.empty()) {
  1157. return;
  1158. }
  1159. _abPath = _abFailoverQueue.front();
  1160. _abFailoverQueue.pop_front();
  1161. _lastActiveBackupPathChange = now;
  1162. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1163. if (_paths[i]) {
  1164. _paths[i]->resetPacketCounts();
  1165. }
  1166. }
  1167. }
  1168. void Bond::processActiveBackupTasks(const int64_t now)
  1169. {
  1170. //fprintf(stderr, "%llu processActiveBackupTasks\n", (now - RR->bc->getBondStartTime()));
  1171. char pathStr[128]; char prevPathStr[128]; char curPathStr[128];
  1172. SharedPtr<Path> prevActiveBackupPath = _abPath;
  1173. SharedPtr<Path> nonPreferredPath;
  1174. bool bFoundPrimaryLink = false;
  1175. /**
  1176. * Select initial "active" active-backup link
  1177. */
  1178. if (!_abPath) {
  1179. //fprintf(stderr, "%llu no active backup path yet...\n", ((now - RR->bc->getBondStartTime())));
  1180. /**
  1181. * [Automatic mode]
  1182. * The user has not explicitly specified links or their failover schedule,
  1183. * the bonding policy will now select the first eligible path and set it as
  1184. * its active backup path, if a substantially better path is detected the bonding
  1185. * policy will assign it as the new active backup path. If the path fails it will
  1186. * simply find the next eligible path.
  1187. */
  1188. if (!userHasSpecifiedLinks()) {
  1189. //fprintf(stderr, "%llu AB: (auto) user did not specify any links. waiting until we know more\n", ((now - RR->bc->getBondStartTime())));
  1190. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1191. if (_paths[i] && _paths[i]->eligible(now,_ackSendInterval)) {
  1192. _paths[i]->address().toString(curPathStr);
  1193. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1194. if (link) {
  1195. //fprintf(stderr, "%llu AB: (initial) [%d] found eligible path %s on: %s\n", ((now - RR->bc->getBondStartTime())), i, curPathStr, link->ifname().c_str());
  1196. }
  1197. _abPath = _paths[i];
  1198. break;
  1199. }
  1200. }
  1201. }
  1202. /**
  1203. * [Manual mode]
  1204. * The user has specified links or failover rules that the bonding policy should adhere to.
  1205. */
  1206. else if (userHasSpecifiedLinks()) {
  1207. //fprintf(stderr, "%llu AB: (manual) no active backup link, checking local.conf\n", ((now - RR->bc->getBondStartTime())));
  1208. if (userHasSpecifiedPrimaryLink()) {
  1209. //fprintf(stderr, "%llu AB: (manual) user has specified primary link, looking for it.\n", ((now - RR->bc->getBondStartTime())));
  1210. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1211. if (!_paths[i]) {
  1212. continue;
  1213. }
  1214. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1215. if (_paths[i]->eligible(now,_ackSendInterval) && link->primary()) {
  1216. if (!_paths[i]->preferred()) {
  1217. _paths[i]->address().toString(curPathStr);
  1218. //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);
  1219. nonPreferredPath = _paths[i];
  1220. bFoundPrimaryLink = true;
  1221. }
  1222. if (_paths[i]->preferred()) {
  1223. _abPath = _paths[i];
  1224. _abPath->address().toString(curPathStr);
  1225. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1226. if (link) {
  1227. //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());
  1228. }
  1229. bFoundPrimaryLink = true;
  1230. break;
  1231. }
  1232. }
  1233. }
  1234. if (_abPath) {
  1235. _abPath->address().toString(curPathStr);
  1236. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _abPath->localSocket());
  1237. if (link) {
  1238. //fprintf(stderr, "%llu AB: (initial) found preferred primary path: %s on %s\n", ((now - RR->bc->getBondStartTime())), curPathStr, link->ifname().c_str());
  1239. }
  1240. }
  1241. else {
  1242. if (bFoundPrimaryLink && nonPreferredPath) {
  1243. //fprintf(stderr, "%llu AB: (initial) found a non-preferred primary path\n", ((now - RR->bc->getBondStartTime())));
  1244. _abPath = nonPreferredPath;
  1245. }
  1246. }
  1247. if (!_abPath) {
  1248. //fprintf(stderr, "%llu AB: (initial) designated primary link is not yet ready\n", ((now - RR->bc->getBondStartTime())));
  1249. // TODO: Should fail-over to specified backup or just wait?
  1250. }
  1251. }
  1252. else if (!userHasSpecifiedPrimaryLink()) {
  1253. int _abIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1254. //fprintf(stderr, "%llu AB: (initial) user did not specify primary link, just picking something\n", ((now - RR->bc->getBondStartTime())));
  1255. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1256. if (_paths[i] && _paths[i]->eligible(now,_ackSendInterval)) {
  1257. _abIdx = i;
  1258. break;
  1259. }
  1260. }
  1261. if (_abIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1262. //fprintf(stderr, "%llu AB: (initial) unable to find a candidate next-best, no change\n", ((now - RR->bc->getBondStartTime())));
  1263. }
  1264. else {
  1265. _abPath = _paths[_abIdx];
  1266. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _abPath->localSocket());
  1267. if (link) {
  1268. //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());
  1269. }
  1270. }
  1271. }
  1272. }
  1273. }
  1274. /**
  1275. * Update and maintain the active-backup failover queue
  1276. */
  1277. if (_abPath) {
  1278. // Don't worry about the failover queue until we have an active link
  1279. // Remove ineligible paths from the failover link queue
  1280. for (std::list<SharedPtr<Path> >::iterator it(_abFailoverQueue.begin()); it!=_abFailoverQueue.end();) {
  1281. if ((*it) && !(*it)->eligible(now,_ackSendInterval)) {
  1282. (*it)->address().toString(curPathStr);
  1283. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, (*it)->localSocket());
  1284. if (link) {
  1285. //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());
  1286. }
  1287. it = _abFailoverQueue.erase(it);
  1288. } else {
  1289. ++it;
  1290. }
  1291. }
  1292. /**
  1293. * Failover instructions were provided by user, build queue according those as well as IPv
  1294. * preference, disregarding performance.
  1295. */
  1296. if (userHasSpecifiedFailoverInstructions()) {
  1297. /**
  1298. * Clear failover scores
  1299. */
  1300. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1301. if (_paths[i]) {
  1302. _paths[i]->_failoverScore = 0;
  1303. }
  1304. }
  1305. //fprintf(stderr, "AB: (fq) user has specified specific failover instructions, will follow them.\n");
  1306. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1307. if (!_paths[i] || !_paths[i]->allowed() || !_paths[i]->eligible(now,_ackSendInterval)) {
  1308. continue;
  1309. }
  1310. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1311. _paths[i]->address().toString(pathStr);
  1312. int failoverScoreHandicap = _paths[i]->_failoverScore;
  1313. if (_paths[i]->preferred())
  1314. {
  1315. failoverScoreHandicap += ZT_MULTIPATH_FAILOVER_HANDICAP_PREFERRED;
  1316. //fprintf(stderr, "%s on %s ----> %d for preferred\n", pathStr, _paths[i]->ifname().c_str(), failoverScoreHandicap);
  1317. }
  1318. if (link->primary()) {
  1319. // If using "optimize" primary reselect mode, ignore user link designations
  1320. failoverScoreHandicap += ZT_MULTIPATH_FAILOVER_HANDICAP_PRIMARY;
  1321. //fprintf(stderr, "%s on %s ----> %d for primary\n", pathStr, _paths[i]->ifname().c_str(), failoverScoreHandicap);
  1322. }
  1323. if (!_paths[i]->_failoverScore) {
  1324. // If we didn't inherit a failover score from a "parent" that wants to use this path as a failover
  1325. int newHandicap = failoverScoreHandicap ? failoverScoreHandicap : _paths[i]->_allocation;
  1326. _paths[i]->_failoverScore = newHandicap;
  1327. //fprintf(stderr, "%s on %s ----> %d for allocation\n", pathStr, _paths[i]->ifname().c_str(), newHandicap);
  1328. }
  1329. SharedPtr<Link> failoverLink;
  1330. if (link->failoverToLink().length()) {
  1331. failoverLink = RR->bc->getLinkByName(_policyAlias, link->failoverToLink());
  1332. }
  1333. if (failoverLink) {
  1334. for (int j=0; j<ZT_MAX_PEER_NETWORK_PATHS; j++) {
  1335. if (_paths[j] && getLink(_paths[j]) == failoverLink.ptr()) {
  1336. _paths[j]->address().toString(pathStr);
  1337. int inheritedHandicap = failoverScoreHandicap - 10;
  1338. int newHandicap = _paths[j]->_failoverScore > inheritedHandicap ? _paths[j]->_failoverScore : inheritedHandicap;
  1339. //fprintf(stderr, "\thanding down %s on %s ----> %d\n", pathStr, getLink(_paths[j])->ifname().c_str(), newHandicap);
  1340. if (!_paths[j]->preferred()) {
  1341. newHandicap--;
  1342. }
  1343. _paths[j]->_failoverScore = newHandicap;
  1344. }
  1345. }
  1346. }
  1347. if (_paths[i].ptr() != _abPath.ptr()) {
  1348. bool bFoundPathInQueue = false;
  1349. for (std::list<SharedPtr<Path> >::iterator it(_abFailoverQueue.begin()); it!=_abFailoverQueue.end();++it) {
  1350. if (_paths[i].ptr() == (*it).ptr()) {
  1351. bFoundPathInQueue = true;
  1352. }
  1353. }
  1354. if (!bFoundPathInQueue) {
  1355. _paths[i]->address().toString(curPathStr);
  1356. //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());
  1357. _abFailoverQueue.push_front(_paths[i]);
  1358. }
  1359. }
  1360. }
  1361. }
  1362. /**
  1363. * No failover instructions provided by user, build queue according to performance
  1364. * and IPv preference.
  1365. */
  1366. else if (!userHasSpecifiedFailoverInstructions()) {
  1367. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1368. if (!_paths[i]
  1369. || !_paths[i]->allowed()
  1370. || !_paths[i]->eligible(now,_ackSendInterval)) {
  1371. continue;
  1372. }
  1373. int failoverScoreHandicap = 0;
  1374. if (_paths[i]->preferred()) {
  1375. failoverScoreHandicap = ZT_MULTIPATH_FAILOVER_HANDICAP_PREFERRED;
  1376. }
  1377. bool includeRefractoryPeriod = true;
  1378. if (!_paths[i]->eligible(now,includeRefractoryPeriod)) {
  1379. failoverScoreHandicap = -10000;
  1380. }
  1381. if (getLink(_paths[i])->primary() && _abLinkSelectMethod != ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE) {
  1382. // If using "optimize" primary reselect mode, ignore user link designations
  1383. failoverScoreHandicap = ZT_MULTIPATH_FAILOVER_HANDICAP_PRIMARY;
  1384. }
  1385. if (_paths[i].ptr() == negotiatedPath.ptr()) {
  1386. _paths[i]->_negotiated = true;
  1387. failoverScoreHandicap = ZT_MULTIPATH_FAILOVER_HANDICAP_NEGOTIATED;
  1388. } else {
  1389. _paths[i]->_negotiated = false;
  1390. }
  1391. _paths[i]->_failoverScore = _paths[i]->_allocation + failoverScoreHandicap;
  1392. if (_paths[i].ptr() != _abPath.ptr()) {
  1393. bool bFoundPathInQueue = false;
  1394. for (std::list<SharedPtr<Path> >::iterator it(_abFailoverQueue.begin()); it!=_abFailoverQueue.end();++it) {
  1395. if (_paths[i].ptr() == (*it).ptr()) {
  1396. bFoundPathInQueue = true;
  1397. }
  1398. }
  1399. if (!bFoundPathInQueue) {
  1400. _paths[i]->address().toString(curPathStr);
  1401. //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());
  1402. _abFailoverQueue.push_front(_paths[i]);
  1403. }
  1404. }
  1405. }
  1406. }
  1407. _abFailoverQueue.sort(PathQualityComparator());
  1408. if (_abFailoverQueue.empty()) {
  1409. //fprintf(stderr, "%llu AB: (fq) the failover queue is empty, the active-backup bond is no longer fault-tolerant\n", ((now - RR->bc->getBondStartTime())));
  1410. }
  1411. }
  1412. /**
  1413. * Short-circuit if we have no queued paths
  1414. */
  1415. if (_abFailoverQueue.empty()) {
  1416. return;
  1417. }
  1418. /**
  1419. * Fulfill primary reselect obligations
  1420. */
  1421. if (_abPath && !_abPath->eligible(now,_ackSendInterval)) { // Implicit ZT_MULTIPATH_RESELECTION_POLICY_FAILURE
  1422. _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);
  1423. if (!_abFailoverQueue.empty()) {
  1424. //fprintf(stderr, "%llu AB: (failure) there are (%lu) links in queue to choose from...\n", ((now - RR->bc->getBondStartTime())), _abFailoverQueue.size());
  1425. dequeueNextActiveBackupPath(now);
  1426. _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());
  1427. } else {
  1428. //fprintf(stderr, "%llu AB: (failure) nothing available in the link queue, doing nothing.\n", ((now - RR->bc->getBondStartTime())));
  1429. }
  1430. }
  1431. /**
  1432. * Detect change to prevent flopping during later optimization step.
  1433. */
  1434. if (prevActiveBackupPath != _abPath) {
  1435. _lastActiveBackupPathChange = now;
  1436. }
  1437. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_ALWAYS) {
  1438. if (_abPath && !getLink(_abPath)->primary()
  1439. && getLink(_abFailoverQueue.front())->primary()) {
  1440. //fprintf(stderr, "%llu AB: (always) switching to available primary\n", ((now - RR->bc->getBondStartTime())));
  1441. dequeueNextActiveBackupPath(now);
  1442. }
  1443. }
  1444. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_BETTER) {
  1445. if (_abPath && !getLink(_abPath)->primary()) {
  1446. //fprintf(stderr, "%llu AB: (better) active backup has switched to \"better\" primary link according to re-select policy.\n", ((now - RR->bc->getBondStartTime())));
  1447. if (getLink(_abFailoverQueue.front())->primary()
  1448. && (_abFailoverQueue.front()->_failoverScore > _abPath->_failoverScore)) {
  1449. dequeueNextActiveBackupPath(now);
  1450. //fprintf(stderr, "%llu AB: (better) switched back to user-defined primary\n", ((now - RR->bc->getBondStartTime())));
  1451. }
  1452. }
  1453. }
  1454. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE && !_abFailoverQueue.empty()) {
  1455. /**
  1456. * Implement link negotiation that was previously-decided
  1457. */
  1458. if (_abFailoverQueue.front()->_negotiated) {
  1459. dequeueNextActiveBackupPath(now);
  1460. _abPath->address().toString(prevPathStr);
  1461. //fprintf(stderr, "%llu AB: (optimize) switched to negotiated path %s on %s\n", ((now - RR->bc->getBondStartTime())), prevPathStr, getLink(_abPath)->ifname().c_str());
  1462. _lastPathNegotiationCheck = now;
  1463. }
  1464. else {
  1465. // Try to find a better path and automatically switch to it -- not too often, though.
  1466. if ((now - _lastActiveBackupPathChange) > ZT_MULTIPATH_MIN_ACTIVE_BACKUP_AUTOFLOP_INTERVAL) {
  1467. if (!_abFailoverQueue.empty()) {
  1468. //fprintf(stderr, "AB: (optimize) there are (%d) links in queue to choose from...\n", _abFailoverQueue.size());
  1469. int newFScore = _abFailoverQueue.front()->_failoverScore;
  1470. int prevFScore = _abPath->_failoverScore;
  1471. // Establish a minimum switch threshold to prevent flapping
  1472. int failoverScoreDifference = _abFailoverQueue.front()->_failoverScore - _abPath->_failoverScore;
  1473. int thresholdQuantity = (ZT_MULTIPATH_ACTIVE_BACKUP_OPTIMIZE_MIN_THRESHOLD * (float)_abPath->_allocation);
  1474. if ((failoverScoreDifference > 0) && (failoverScoreDifference > thresholdQuantity)) {
  1475. SharedPtr<Path> oldPath = _abPath;
  1476. _abPath->address().toString(prevPathStr);
  1477. dequeueNextActiveBackupPath(now);
  1478. _abPath->address().toString(curPathStr);
  1479. //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);
  1480. }
  1481. }
  1482. }
  1483. }
  1484. }
  1485. }
  1486. void Bond::setReasonableDefaults(int policy, SharedPtr<Bond> templateBond, bool useTemplate)
  1487. {
  1488. // If invalid bonding policy, try default
  1489. int _defaultBondingPolicy = BondController::defaultBondingPolicy();
  1490. if (policy <= ZT_BONDING_POLICY_NONE || policy > ZT_BONDING_POLICY_BALANCE_AWARE) {
  1491. // If no default set, use NONE (effectively disabling this bond)
  1492. if (_defaultBondingPolicy < ZT_BONDING_POLICY_NONE || _defaultBondingPolicy > ZT_BONDING_POLICY_BALANCE_AWARE) {
  1493. _bondingPolicy= ZT_BONDING_POLICY_NONE;
  1494. }
  1495. _bondingPolicy= _defaultBondingPolicy;
  1496. } else {
  1497. _bondingPolicy= policy;
  1498. }
  1499. _freeRandomByte = 0;
  1500. _lastCheckUserPreferences = 0;
  1501. _lastBackgroundTaskCheck = 0;
  1502. _isHealthy = false;
  1503. _numAliveLinks = 0;
  1504. _numTotalLinks = 0;
  1505. _downDelay = 0;
  1506. _upDelay = 0;
  1507. _allowFlowHashing=false;
  1508. _bondMonitorInterval=0;
  1509. _shouldCollectPathStatistics=false;
  1510. // Path negotiation
  1511. _allowPathNegotiation=false;
  1512. _lastPathNegotiationReceived=0;
  1513. _lastPathNegotiationCheck=0;
  1514. _pathNegotiationCutoffCount=0;
  1515. _localUtility=0;
  1516. _lastFlowStatReset=0;
  1517. _lastFlowExpirationCheck=0;
  1518. _numBondedPaths=0;
  1519. _rrPacketsSentOnCurrLink=0;
  1520. _rrIdx=0;
  1521. _lastFlowRebalance=0;
  1522. _totalBondUnderload = 0;
  1523. _maxAcceptableLatency = 100;
  1524. _maxAcceptablePacketDelayVariance = 50;
  1525. _maxAcceptablePacketLossRatio = 0.10;
  1526. _maxAcceptablePacketErrorRatio = 0.10;
  1527. _userHasSpecifiedLinkSpeeds=0;
  1528. _lastFrame=0;
  1529. /* ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_PASSIVE is the most conservative strategy and is
  1530. least likely to cause unexpected behavior */
  1531. _flowRebalanceStrategy = ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_AGGRESSIVE;
  1532. /**
  1533. * Paths are actively monitored to provide a real-time quality/preference-ordered rapid failover queue.
  1534. */
  1535. switch (policy) {
  1536. case ZT_BONDING_POLICY_ACTIVE_BACKUP:
  1537. _failoverInterval = 500;
  1538. _abLinkSelectMethod = ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE;
  1539. _linkMonitorStrategy = ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC;
  1540. _qualityWeights[ZT_QOS_LAT_IDX] = 0.2f;
  1541. _qualityWeights[ZT_QOS_LTM_IDX] = 0.0f;
  1542. _qualityWeights[ZT_QOS_PDV_IDX] = 0.2f;
  1543. _qualityWeights[ZT_QOS_PLR_IDX] = 0.2f;
  1544. _qualityWeights[ZT_QOS_PER_IDX] = 0.2f;
  1545. _qualityWeights[ZT_QOS_THR_IDX] = 0.2f;
  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. * All seemingly-alive paths are used. Paths are not actively monitored.
  1552. */
  1553. case ZT_BONDING_POLICY_BROADCAST:
  1554. _downDelay = 30000;
  1555. _upDelay = 0;
  1556. break;
  1557. /**
  1558. * Paths are monitored to determine when/if one needs to be added or removed from the rotation
  1559. */
  1560. case ZT_BONDING_POLICY_BALANCE_RR:
  1561. _failoverInterval = 500;
  1562. _allowFlowHashing = false;
  1563. _packetsPerLink = 1024;
  1564. _linkMonitorStrategy = ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC;
  1565. _qualityWeights[ZT_QOS_LAT_IDX] = 0.4f;
  1566. _qualityWeights[ZT_QOS_LTM_IDX] = 0.0f;
  1567. _qualityWeights[ZT_QOS_PDV_IDX] = 0.2f;
  1568. _qualityWeights[ZT_QOS_PLR_IDX] = 0.1f;
  1569. _qualityWeights[ZT_QOS_PER_IDX] = 0.1f;
  1570. _qualityWeights[ZT_QOS_THR_IDX] = 0.1f;
  1571. _qualityWeights[ZT_QOS_THM_IDX] = 0.0f;
  1572. _qualityWeights[ZT_QOS_THV_IDX] = 0.0f;
  1573. _qualityWeights[ZT_QOS_SCP_IDX] = 0.0f;
  1574. break;
  1575. /**
  1576. * Path monitoring is used to determine the capacity of each
  1577. * path and where to place the next flow.
  1578. */
  1579. case ZT_BONDING_POLICY_BALANCE_XOR:
  1580. _failoverInterval = 500;
  1581. _upDelay = _bondMonitorInterval * 2;
  1582. _allowFlowHashing = true;
  1583. _linkMonitorStrategy = ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC;
  1584. _qualityWeights[ZT_QOS_LAT_IDX] = 0.4f;
  1585. _qualityWeights[ZT_QOS_LTM_IDX] = 0.0f;
  1586. _qualityWeights[ZT_QOS_PDV_IDX] = 0.2f;
  1587. _qualityWeights[ZT_QOS_PLR_IDX] = 0.1f;
  1588. _qualityWeights[ZT_QOS_PER_IDX] = 0.1f;
  1589. _qualityWeights[ZT_QOS_THR_IDX] = 0.1f;
  1590. _qualityWeights[ZT_QOS_THM_IDX] = 0.0f;
  1591. _qualityWeights[ZT_QOS_THV_IDX] = 0.0f;
  1592. _qualityWeights[ZT_QOS_SCP_IDX] = 0.0f;
  1593. break;
  1594. /**
  1595. * Path monitoring is used to determine the capacity of each
  1596. * path and where to place the next flow. Additionally, re-shuffling
  1597. * of flows may take place.
  1598. */
  1599. case ZT_BONDING_POLICY_BALANCE_AWARE:
  1600. _failoverInterval = 3000;
  1601. _allowFlowHashing = true;
  1602. _linkMonitorStrategy = ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC;
  1603. _qualityWeights[ZT_QOS_LAT_IDX] = 0.4f;
  1604. _qualityWeights[ZT_QOS_LTM_IDX] = 0.0f;
  1605. _qualityWeights[ZT_QOS_PDV_IDX] = 0.4f;
  1606. _qualityWeights[ZT_QOS_PLR_IDX] = 0.2f;
  1607. _qualityWeights[ZT_QOS_PER_IDX] = 0.0f;
  1608. _qualityWeights[ZT_QOS_THR_IDX] = 0.0f;
  1609. _qualityWeights[ZT_QOS_THM_IDX] = 0.0f;
  1610. _qualityWeights[ZT_QOS_THV_IDX] = 0.0f;
  1611. _qualityWeights[ZT_QOS_SCP_IDX] = 0.0f;
  1612. break;
  1613. default:
  1614. break;
  1615. }
  1616. /* If a user has specified custom parameters for this bonding policy, overlay
  1617. them onto the defaults that were previously set */
  1618. if (useTemplate) {
  1619. _policyAlias = templateBond->_policyAlias;
  1620. _failoverInterval = templateBond->_failoverInterval;
  1621. _downDelay = templateBond->_downDelay;
  1622. _upDelay = templateBond->_upDelay;
  1623. /*fprintf(stderr, "TIMERS: strat=%d, fi= %d, bmi= %d, qos= %d, ack= %d, estimateInt= %d, refractory= %d, ud= %d, dd= %d\n",
  1624. _linkMonitorStrategy,
  1625. _failoverInterval,
  1626. _bondMonitorInterval,
  1627. _qosSendInterval,
  1628. _ackSendInterval,
  1629. _qualityEstimationInterval,
  1630. _defaultPathRefractoryPeriod,
  1631. _upDelay,
  1632. _downDelay);
  1633. */
  1634. if (templateBond->_linkMonitorStrategy == ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_PASSIVE
  1635. && templateBond->_failoverInterval != 0) {
  1636. //fprintf(stderr, "warning: passive path monitoring was specified, this will prevent failovers from happening in a timely manner.\n");
  1637. }
  1638. _abLinkSelectMethod = templateBond->_abLinkSelectMethod;
  1639. memcpy(_qualityWeights, templateBond->_qualityWeights, ZT_QOS_WEIGHT_SIZE * sizeof(float));
  1640. }
  1641. //
  1642. // Second, apply user specified values (only if they make sense)
  1643. /**
  1644. * Timer geometries and counters
  1645. */
  1646. // TODO: Think more about the maximum
  1647. /*
  1648. if (originalBond._failoverInterval > 250 && originalBond._failoverInterval < 65535) {
  1649. _failoverInterval = originalBond._failoverInterval;
  1650. }
  1651. else {
  1652. //fprintf(stderr, "warning: _failoverInterval (%d) is out of range, using default (%d)\n", originalBond._failoverInterval, _failoverInterval);
  1653. }
  1654. */
  1655. _bondMonitorInterval = _failoverInterval / 3;
  1656. BondController::setMinReqPathMonitorInterval(_bondMonitorInterval);
  1657. _ackSendInterval = _failoverInterval;
  1658. _qualityEstimationInterval = _failoverInterval * 2;
  1659. _dynamicPathMonitorInterval = 0;
  1660. _ackCutoffCount = 0;
  1661. _lastAckRateCheck = 0;
  1662. _qosSendInterval = _bondMonitorInterval * 4;
  1663. _qosCutoffCount = 0;
  1664. _lastQoSRateCheck = 0;
  1665. _lastQualityEstimation=0;
  1666. throughputMeasurementInterval = _ackSendInterval * 2;
  1667. _defaultPathRefractoryPeriod = 8000;
  1668. }
  1669. void Bond::setUserQualityWeights(float weights[], int len)
  1670. {
  1671. if (len == ZT_QOS_WEIGHT_SIZE) {
  1672. float weightTotal = 0.0;
  1673. for (unsigned int i=0; i<ZT_QOS_WEIGHT_SIZE; ++i) {
  1674. weightTotal += weights[i];
  1675. }
  1676. if (weightTotal > 0.99 && weightTotal < 1.01) {
  1677. memcpy(_qualityWeights, weights, len * sizeof(float));
  1678. }
  1679. }
  1680. }
  1681. bool Bond::relevant() {
  1682. return false;
  1683. }
  1684. SharedPtr<Link> Bond::getLink(const SharedPtr<Path>& path)
  1685. {
  1686. return RR->bc->getLinkBySocket(_policyAlias, path->localSocket());
  1687. }
  1688. void Bond::dumpInfo(const int64_t now)
  1689. {
  1690. // Omitted
  1691. }
  1692. } // namespace ZeroTier