Bond.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  1. /*
  2. * Copyright (c)2013-2021 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: 2026-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 "Bond.hpp"
  14. #include "Switch.hpp"
  15. #include <cmath>
  16. #include <string>
  17. #include <cstdio>
  18. namespace ZeroTier {
  19. static unsigned char s_freeRandomByteCounter = 0;
  20. int Bond::_minReqMonitorInterval = ZT_BOND_FAILOVER_DEFAULT_INTERVAL;
  21. uint8_t Bond::_defaultPolicy = ZT_BOND_POLICY_NONE;
  22. Phy<Bond*>* Bond::_phy;
  23. Mutex Bond::_bonds_m;
  24. Mutex Bond::_links_m;
  25. std::string Bond::_defaultPolicyStr;
  26. std::map<int64_t, SharedPtr<Bond> > Bond::_bonds;
  27. std::map<int64_t, std::string> Bond::_policyTemplateAssignments;
  28. std::map<std::string, SharedPtr<Bond> > Bond::_bondPolicyTemplates;
  29. std::map<std::string, std::vector<SharedPtr<Link> > > Bond::_linkDefinitions;
  30. std::map<std::string, std::map<std::string, SharedPtr<Link> > > Bond::_interfaceToLinkMap;
  31. bool Bond::linkAllowed(std::string& policyAlias, SharedPtr<Link> link)
  32. {
  33. bool foundInDefinitions = false;
  34. if (_linkDefinitions.count(policyAlias)) {
  35. auto it = _linkDefinitions[policyAlias].begin();
  36. while (it != _linkDefinitions[policyAlias].end()) {
  37. if (link->ifname() == (*it)->ifname()) {
  38. foundInDefinitions = true;
  39. break;
  40. }
  41. ++it;
  42. }
  43. }
  44. return _linkDefinitions[policyAlias].empty() || foundInDefinitions;
  45. }
  46. void Bond::addCustomLink(std::string& policyAlias, SharedPtr<Link> link)
  47. {
  48. Mutex::Lock _l(_links_m);
  49. _linkDefinitions[policyAlias].push_back(link);
  50. auto search = _interfaceToLinkMap[policyAlias].find(link->ifname());
  51. if (search == _interfaceToLinkMap[policyAlias].end()) {
  52. link->setAsUserSpecified(true);
  53. _interfaceToLinkMap[policyAlias].insert(std::pair<std::string, SharedPtr<Link> >(link->ifname(), link));
  54. }
  55. }
  56. bool Bond::addCustomPolicy(const SharedPtr<Bond>& newBond)
  57. {
  58. Mutex::Lock _l(_bonds_m);
  59. if (! _bondPolicyTemplates.count(newBond->policyAlias())) {
  60. _bondPolicyTemplates[newBond->policyAlias()] = newBond;
  61. return true;
  62. }
  63. return false;
  64. }
  65. bool Bond::assignBondingPolicyToPeer(int64_t identity, const std::string& policyAlias)
  66. {
  67. Mutex::Lock _l(_bonds_m);
  68. if (! _policyTemplateAssignments.count(identity)) {
  69. _policyTemplateAssignments[identity] = policyAlias;
  70. return true;
  71. }
  72. return false;
  73. }
  74. SharedPtr<Bond> Bond::getBondByPeerId(int64_t identity)
  75. {
  76. Mutex::Lock _l(_bonds_m);
  77. return _bonds.count(identity) ? _bonds[identity] : SharedPtr<Bond>();
  78. }
  79. SharedPtr<Bond> Bond::createTransportTriggeredBond(const RuntimeEnvironment* renv, const SharedPtr<Peer>& peer)
  80. {
  81. Mutex::Lock _l(_bonds_m);
  82. int64_t identity = peer->identity().address().toInt();
  83. Bond* bond = nullptr;
  84. if (! _bonds.count(identity)) {
  85. if (! _policyTemplateAssignments.count(identity)) {
  86. if (_defaultPolicy) {
  87. bond = new Bond(renv, _defaultPolicy, peer);
  88. bond->debug("new default bond");
  89. }
  90. if (! _defaultPolicy && _defaultPolicyStr.length()) {
  91. bond = new Bond(renv, _bondPolicyTemplates[_defaultPolicyStr].ptr(), peer);
  92. bond->debug("new default custom bond (based on %s)", bond->getPolicyStrByCode(bond->policy()).c_str());
  93. }
  94. }
  95. else {
  96. if (! _bondPolicyTemplates[_policyTemplateAssignments[identity]]) {
  97. bond = new Bond(renv, _defaultPolicy, peer);
  98. bond->debug("peer-specific bond, was specified as %s but the bond definition was not found, using default %s", _policyTemplateAssignments[identity].c_str(), getPolicyStrByCode(_defaultPolicy).c_str());
  99. }
  100. else {
  101. bond = new Bond(renv, _bondPolicyTemplates[_policyTemplateAssignments[identity]].ptr(), peer);
  102. bond->debug("new default bond");
  103. }
  104. }
  105. }
  106. if (bond) {
  107. _bonds[identity] = bond;
  108. /**
  109. * Determine if user has specified anything that could affect the bonding policy's decisions
  110. */
  111. if (_interfaceToLinkMap.count(bond->policyAlias())) {
  112. std::map<std::string, SharedPtr<Link> >::iterator it = _interfaceToLinkMap[bond->policyAlias()].begin();
  113. while (it != _interfaceToLinkMap[bond->policyAlias()].end()) {
  114. if (it->second->isUserSpecified()) {
  115. bond->_userHasSpecifiedLinks = true;
  116. }
  117. if (it->second->isUserSpecified() && it->second->primary()) {
  118. bond->_userHasSpecifiedPrimaryLink = true;
  119. }
  120. if (it->second->isUserSpecified() && it->second->userHasSpecifiedFailoverInstructions()) {
  121. bond->_userHasSpecifiedFailoverInstructions = true;
  122. }
  123. if (it->second->isUserSpecified() && (it->second->speed() > 0)) {
  124. bond->_userHasSpecifiedLinkSpeeds = true;
  125. }
  126. ++it;
  127. }
  128. }
  129. return bond;
  130. }
  131. return SharedPtr<Bond>();
  132. }
  133. SharedPtr<Link> Bond::getLinkBySocket(const std::string& policyAlias, uint64_t localSocket)
  134. {
  135. Mutex::Lock _l(_links_m);
  136. char ifname[64] = { 0 };
  137. _phy->getIfName((PhySocket*)((uintptr_t)localSocket), ifname, sizeof(ifname) - 1);
  138. std::string ifnameStr(ifname);
  139. auto search = _interfaceToLinkMap[policyAlias].find(ifnameStr);
  140. if (search == _interfaceToLinkMap[policyAlias].end()) {
  141. // If the link wasn't already known, add a new entry
  142. SharedPtr<Link> s = new Link(ifnameStr, 0, 0, true, ZT_BOND_SLAVE_MODE_SPARE, "", 0.0);
  143. _interfaceToLinkMap[policyAlias].insert(std::pair<std::string, SharedPtr<Link> >(ifnameStr, s));
  144. return s;
  145. }
  146. else {
  147. return search->second;
  148. }
  149. }
  150. SharedPtr<Link> Bond::getLinkByName(const std::string& policyAlias, const std::string& ifname)
  151. {
  152. Mutex::Lock _l(_links_m);
  153. auto search = _interfaceToLinkMap[policyAlias].find(ifname);
  154. if (search != _interfaceToLinkMap[policyAlias].end()) {
  155. return search->second;
  156. }
  157. return SharedPtr<Link>();
  158. }
  159. void Bond::processBackgroundTasks(void* tPtr, const int64_t now)
  160. {
  161. unsigned long _currMinReqMonitorInterval = ZT_BOND_FAILOVER_DEFAULT_INTERVAL;
  162. Mutex::Lock _l(_bonds_m);
  163. std::map<int64_t, SharedPtr<Bond> >::iterator bondItr = _bonds.begin();
  164. while (bondItr != _bonds.end()) {
  165. // Update Bond Controller's background processing timer
  166. _currMinReqMonitorInterval = std::min(_currMinReqMonitorInterval, (unsigned long)(bondItr->second->monitorInterval()));
  167. bondItr->second->processBackgroundBondTasks(tPtr, now);
  168. ++bondItr;
  169. }
  170. _minReqMonitorInterval = std::min(_currMinReqMonitorInterval, (unsigned long)ZT_BOND_FAILOVER_DEFAULT_INTERVAL);
  171. }
  172. Bond::Bond(const RuntimeEnvironment* renv) : RR(renv)
  173. {
  174. initTimers();
  175. }
  176. Bond::Bond(const RuntimeEnvironment* renv, int policy, const SharedPtr<Peer>& peer) : RR(renv), _freeRandomByte((unsigned char)((uintptr_t)this >> 4) ^ ++s_freeRandomByteCounter), _peer(peer), _peerId(_peer->_id.address().toInt())
  177. {
  178. initTimers();
  179. setBondParameters(policy, SharedPtr<Bond>(), false);
  180. _policyAlias = getPolicyStrByCode(policy);
  181. }
  182. Bond::Bond(const RuntimeEnvironment* renv, std::string& basePolicy, std::string& policyAlias, const SharedPtr<Peer>& peer) : RR(renv), _policyAlias(policyAlias), _peer(peer)
  183. {
  184. initTimers();
  185. setBondParameters(getPolicyCodeByStr(basePolicy), SharedPtr<Bond>(), false);
  186. }
  187. Bond::Bond(const RuntimeEnvironment* renv, SharedPtr<Bond> originalBond, const SharedPtr<Peer>& peer)
  188. : RR(renv)
  189. , _freeRandomByte((unsigned char)((uintptr_t)this >> 4) ^ ++s_freeRandomByteCounter)
  190. , _peer(peer)
  191. , _peerId(_peer->_id.address().toInt())
  192. {
  193. initTimers();
  194. setBondParameters(originalBond->_policy, originalBond, true);
  195. }
  196. void Bond::nominatePathToBond(const SharedPtr<Path>& path, int64_t now)
  197. {
  198. Mutex::Lock _l(_paths_m);
  199. /**
  200. * Ensure the link is allowed and the path is not already present
  201. */
  202. if (! RR->bc->linkAllowed(_policyAlias, getLink(path))) {
  203. return;
  204. }
  205. bool alreadyPresent = false;
  206. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  207. // Sanity check
  208. if (path.ptr() == _paths[i].p.ptr()) {
  209. alreadyPresent = true;
  210. break;
  211. }
  212. }
  213. if (! alreadyPresent) {
  214. /**
  215. * Find somewhere to stick it
  216. */
  217. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  218. if (! _paths[i].p) {
  219. _paths[i].set(now, path);
  220. /**
  221. * Set user preferences and update state variables of other paths on the same link
  222. */
  223. SharedPtr<Link> sl = getLink(_paths[i].p);
  224. if (sl) {
  225. // Determine if there are any other paths on this link
  226. bool bFoundCommonLink = false;
  227. SharedPtr<Link> commonLink = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  228. for (unsigned int j = 0; j < ZT_MAX_PEER_NETWORK_PATHS; ++j) {
  229. if (_paths[j].p && _paths[j].p.ptr() != _paths[i].p.ptr()) {
  230. if (RR->bc->getLinkBySocket(_policyAlias, _paths[j].p->localSocket()) == commonLink) {
  231. bFoundCommonLink = true;
  232. _paths[j].onlyPathOnLink = false;
  233. }
  234. }
  235. }
  236. _paths[i].ipvPref = sl->ipvPref();
  237. _paths[i].mode = sl->mode();
  238. _paths[i].enabled = sl->enabled();
  239. _paths[i].onlyPathOnLink = ! bFoundCommonLink;
  240. }
  241. log("nominate link %s", pathToStr(path).c_str());
  242. break;
  243. }
  244. }
  245. }
  246. curateBond(now, true);
  247. estimatePathQuality(now);
  248. }
  249. void Bond::addPathToBond(int nominatedIdx, int bondedIdx)
  250. {
  251. // Map bonded set to nominated set
  252. _bondIdxMap[bondedIdx] = nominatedIdx;
  253. // Tell the bonding layer that we can now use this bond for traffic
  254. _paths[nominatedIdx].bonded = true;
  255. }
  256. SharedPtr<Path> Bond::getAppropriatePath(int64_t now, int32_t flowId)
  257. {
  258. Mutex::Lock _l(_paths_m);
  259. /**
  260. * active-backup
  261. */
  262. if (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP) {
  263. if (_abPathIdx != ZT_MAX_PEER_NETWORK_PATHS && _paths[_abPathIdx].p) {
  264. return _paths[_abPathIdx].p;
  265. }
  266. }
  267. /**
  268. * broadcast
  269. */
  270. if (_policy == ZT_BOND_POLICY_BROADCAST) {
  271. return SharedPtr<Path>(); // Handled in Switch::_trySend()
  272. }
  273. if (! _numBondedPaths) {
  274. return SharedPtr<Path>(); // No paths assigned to bond yet, cannot balance traffic
  275. }
  276. /**
  277. * balance-rr
  278. */
  279. if (_policy == ZT_BOND_POLICY_BALANCE_RR) {
  280. if (! _allowFlowHashing) {
  281. if (_packetsPerLink == 0) {
  282. // Randomly select a path
  283. return _paths[_bondIdxMap[_freeRandomByte % _numBondedPaths]].p;
  284. }
  285. if (_rrPacketsSentOnCurrLink < _packetsPerLink) {
  286. // Continue to use this link
  287. ++_rrPacketsSentOnCurrLink;
  288. return _paths[_bondIdxMap[_rrIdx]].p;
  289. }
  290. // Reset striping counter
  291. _rrPacketsSentOnCurrLink = 0;
  292. if (_numBondedPaths == 1 || _rrIdx >= (ZT_MAX_PEER_NETWORK_PATHS-1)) {
  293. _rrIdx = 0;
  294. }
  295. else {
  296. int _tempIdx = _rrIdx;
  297. for (int searchCount = 0; searchCount < (_numBondedPaths - 1); searchCount++) {
  298. _tempIdx = (_tempIdx == (_numBondedPaths - 1)) ? 0 : _tempIdx + 1;
  299. if (_bondIdxMap[_tempIdx] != ZT_MAX_PEER_NETWORK_PATHS) {
  300. if (_paths[_bondIdxMap[_tempIdx]].p && _paths[_bondIdxMap[_tempIdx]].eligible) {
  301. _rrIdx = _tempIdx;
  302. break;
  303. }
  304. }
  305. }
  306. }
  307. if (_paths[_bondIdxMap[_rrIdx]].p) {
  308. return _paths[_bondIdxMap[_rrIdx]].p;
  309. }
  310. }
  311. }
  312. /**
  313. * balance-xor
  314. */
  315. if (_policy == ZT_BOND_POLICY_BALANCE_XOR || _policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  316. if (! _allowFlowHashing || flowId == -1) {
  317. // No specific path required for unclassified traffic, send on anything
  318. int m_idx = _bondIdxMap[_freeRandomByte % _numBondedPaths];
  319. return _paths[m_idx].p;
  320. }
  321. else if (_allowFlowHashing) {
  322. Mutex::Lock _l(_flows_m);
  323. SharedPtr<Flow> flow;
  324. if (_flows.count(flowId)) {
  325. flow = _flows[flowId];
  326. flow->lastActivity = now;
  327. }
  328. else {
  329. unsigned char entropy;
  330. Utils::getSecureRandom(&entropy, 1);
  331. flow = createFlow(ZT_MAX_PEER_NETWORK_PATHS, flowId, entropy, now);
  332. }
  333. if (flow) {
  334. return _paths[flow->assignedPath].p;
  335. }
  336. }
  337. }
  338. return SharedPtr<Path>();
  339. }
  340. void Bond::recordIncomingInvalidPacket(const SharedPtr<Path>& path)
  341. {
  342. Mutex::Lock _l(_paths_m);
  343. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  344. if (_paths[i].p == path) {
  345. _paths[i].packetValiditySamples.push(false);
  346. }
  347. }
  348. }
  349. void Bond::recordOutgoingPacket(const SharedPtr<Path>& path, uint64_t packetId, uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  350. {
  351. _freeRandomByte += (unsigned char)(packetId >> 8); // Grab entropy to use in path selection logic
  352. bool isFrame = (verb == Packet::Packet::VERB_ECHO || verb == Packet::VERB_FRAME || verb == Packet::VERB_EXT_FRAME);
  353. bool shouldRecord = (packetId & (ZT_QOS_ACK_DIVISOR - 1) && (verb != Packet::VERB_ACK) && (verb != Packet::VERB_QOS_MEASUREMENT));
  354. if (isFrame || shouldRecord) {
  355. Mutex::Lock _l(_paths_m);
  356. int pathIdx = getNominatedPathIdx(path);
  357. if (pathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  358. return;
  359. }
  360. if (isFrame) {
  361. ++(_paths[pathIdx].packetsOut);
  362. _lastFrame = now;
  363. }
  364. if (shouldRecord) {
  365. //_paths[pathIdx].unackedBytes += payloadLength;
  366. // Take note that we're expecting a VERB_ACK on this path as of a specific time
  367. if (_paths[pathIdx].qosStatsOut.size() < ZT_QOS_MAX_OUTSTANDING_RECORDS) {
  368. _paths[pathIdx].qosStatsOut[packetId] = now;
  369. }
  370. }
  371. }
  372. if (_allowFlowHashing && (flowId != ZT_QOS_NO_FLOW)) {
  373. Mutex::Lock _l(_flows_m);
  374. if (_flows.count(flowId)) {
  375. _flows[flowId]->bytesOut += payloadLength;
  376. }
  377. }
  378. }
  379. void Bond::recordIncomingPacket(const SharedPtr<Path>& path, uint64_t packetId, uint16_t payloadLength, Packet::Verb verb, int32_t flowId, int64_t now)
  380. {
  381. bool isFrame = (verb == Packet::Packet::VERB_ECHO || verb == Packet::VERB_FRAME || verb == Packet::VERB_EXT_FRAME);
  382. bool shouldRecord = (packetId & (ZT_QOS_ACK_DIVISOR - 1) && (verb != Packet::VERB_ACK) && (verb != Packet::VERB_QOS_MEASUREMENT));
  383. Mutex::Lock _l(_paths_m);
  384. int pathIdx = getNominatedPathIdx(path);
  385. if (pathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  386. return;
  387. }
  388. // Take note of the time that this previously-dead path received a packet
  389. if (! _paths[pathIdx].alive) {
  390. _paths[pathIdx].lastAliveToggle = now;
  391. }
  392. if (isFrame || shouldRecord) {
  393. if (_paths[pathIdx].allowed()) {
  394. if (isFrame) {
  395. ++(_paths[pathIdx].packetsIn);
  396. _lastFrame = now;
  397. }
  398. if (shouldRecord) {
  399. _paths[pathIdx].qosStatsIn[packetId] = now;
  400. ++(_paths[pathIdx].packetsReceivedSinceLastQoS);
  401. _paths[pathIdx].packetValiditySamples.push(true);
  402. }
  403. }
  404. }
  405. /**
  406. * Learn new flows and pro-actively create entries for them in the bond so
  407. * that the next time we send a packet out that is part of a flow we know
  408. * which path to use.
  409. */
  410. if ((flowId != ZT_QOS_NO_FLOW) && (_policy == ZT_BOND_POLICY_BALANCE_RR || _policy == ZT_BOND_POLICY_BALANCE_XOR || _policy == ZT_BOND_POLICY_BALANCE_AWARE)) {
  411. Mutex::Lock _l(_flows_m);
  412. SharedPtr<Flow> flow;
  413. if (! _flows.count(flowId)) {
  414. flow = createFlow(pathIdx, flowId, 0, now);
  415. }
  416. else {
  417. flow = _flows[flowId];
  418. }
  419. if (flow) {
  420. flow->bytesIn += payloadLength;
  421. }
  422. }
  423. }
  424. void Bond::receivedQoS(const SharedPtr<Path>& path, int64_t now, int count, uint64_t* rx_id, uint16_t* rx_ts)
  425. {
  426. Mutex::Lock _l(_paths_m);
  427. int pathIdx = getNominatedPathIdx(path);
  428. if (pathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  429. return;
  430. }
  431. // debug("received QoS packet (sampling %d frames) via %s", count, pathToStr(path).c_str());
  432. // Look up egress times and compute latency values for each record
  433. std::map<uint64_t, uint64_t>::iterator it;
  434. for (int j = 0; j < count; j++) {
  435. it = _paths[pathIdx].qosStatsOut.find(rx_id[j]);
  436. if (it != _paths[pathIdx].qosStatsOut.end()) {
  437. _paths[pathIdx].latencySamples.push(((uint16_t)(now - it->second) - rx_ts[j]) / 2);
  438. _paths[pathIdx].qosStatsOut.erase(it);
  439. }
  440. }
  441. _paths[pathIdx].qosRecordSize.push(count);
  442. }
  443. int32_t Bond::generateQoSPacket(int pathIdx, int64_t now, char* qosBuffer)
  444. {
  445. int32_t len = 0;
  446. std::map<uint64_t, uint64_t>::iterator it = _paths[pathIdx].qosStatsIn.begin();
  447. int i = 0;
  448. int numRecords = std::min(_paths[pathIdx].packetsReceivedSinceLastQoS, ZT_QOS_TABLE_SIZE);
  449. while (i < numRecords && it != _paths[pathIdx].qosStatsIn.end()) {
  450. uint64_t id = it->first;
  451. memcpy(qosBuffer, &id, sizeof(uint64_t));
  452. qosBuffer += sizeof(uint64_t);
  453. uint16_t holdingTime = (uint16_t)(now - it->second);
  454. memcpy(qosBuffer, &holdingTime, sizeof(uint16_t));
  455. qosBuffer += sizeof(uint16_t);
  456. len += sizeof(uint64_t) + sizeof(uint16_t);
  457. _paths[pathIdx].qosStatsIn.erase(it++);
  458. ++i;
  459. }
  460. return len;
  461. }
  462. bool Bond::assignFlowToBondedPath(SharedPtr<Flow>& flow, int64_t now)
  463. {
  464. if (! _numBondedPaths) {
  465. debug("unable to assign flow %x (bond has no links)\n", flow->id);
  466. return false;
  467. }
  468. unsigned int idx = ZT_MAX_PEER_NETWORK_PATHS;
  469. if (_policy == ZT_BOND_POLICY_BALANCE_XOR) {
  470. idx = abs((int)(flow->id % (_numBondedPaths)));
  471. flow->assignPath(_bondIdxMap[idx], now);
  472. ++(_paths[_bondIdxMap[idx]].assignedFlowCount);
  473. }
  474. if (_policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  475. unsigned char entropy;
  476. Utils::getSecureRandom(&entropy, 1);
  477. if (_totalBondUnderload) {
  478. entropy %= _totalBondUnderload;
  479. }
  480. /* Since there may be scenarios where a path is removed before we can re-estimate
  481. relative qualities (and thus allocations) we need to down-modulate the entropy
  482. value that we use to randomly assign among the surviving paths, otherwise we risk
  483. not being able to find a path to assign this flow to. */
  484. int totalIncompleteAllocation = 0;
  485. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  486. if (_paths[i].p && _paths[i].bonded) {
  487. totalIncompleteAllocation += _paths[i].allocation;
  488. }
  489. }
  490. entropy %= totalIncompleteAllocation;
  491. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  492. if (_paths[i].p && _paths[i].bonded) {
  493. uint8_t probabilitySegment = (_totalBondUnderload > 0) ? _paths[i].affinity : _paths[i].allocation;
  494. if (entropy <= probabilitySegment) {
  495. idx = i;
  496. break;
  497. }
  498. entropy -= probabilitySegment;
  499. }
  500. }
  501. if (idx < ZT_MAX_PEER_NETWORK_PATHS) {
  502. flow->assignPath(idx, now);
  503. ++(_paths[idx].assignedFlowCount);
  504. }
  505. else {
  506. debug("unable to assign out-flow %x (unknown reason)", flow->id);
  507. return false;
  508. }
  509. }
  510. if (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP) {
  511. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  512. debug("unable to assign out-flow %x (no active backup link)", flow->id);
  513. }
  514. flow->assignPath(_abPathIdx, now);
  515. }
  516. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[flow->assignedPath].p->localSocket());
  517. debug("assign out-flow %04x to link %s (%lu / %lu flows)", flow->id, pathToStr(_paths[flow->assignedPath].p).c_str(), _paths[flow->assignedPath].assignedFlowCount, (unsigned long)_flows.size());
  518. return true;
  519. }
  520. SharedPtr<Bond::Flow> Bond::createFlow(int pathIdx, int32_t flowId, unsigned char entropy, int64_t now)
  521. {
  522. if (! _numBondedPaths) {
  523. debug("unable to assign flow %x (bond has no links)\n", flowId);
  524. return SharedPtr<Flow>();
  525. }
  526. if (_flows.size() >= ZT_FLOW_MAX_COUNT) {
  527. debug("forget oldest flow (max flows reached: %d)\n", ZT_FLOW_MAX_COUNT);
  528. forgetFlowsWhenNecessary(0, true, now);
  529. }
  530. SharedPtr<Flow> flow = new Flow(flowId, now);
  531. _flows[flowId] = flow;
  532. /**
  533. * Add a flow with a given Path already provided. This is the case when a packet
  534. * is received on a path but no flow exists, in this case we simply assign the path
  535. * that the remote peer chose for us.
  536. */
  537. if (pathIdx != ZT_MAX_PEER_NETWORK_PATHS) {
  538. flow->assignPath(pathIdx, now);
  539. _paths[pathIdx].assignedFlowCount++;
  540. debug("assign in-flow %x to link %s (%lu / %lu)", flow->id, pathToStr(_paths[pathIdx].p).c_str(), _paths[pathIdx].assignedFlowCount, (unsigned long)_flows.size());
  541. }
  542. /**
  543. * Add a flow when no path was provided. This means that it is an outgoing packet
  544. * and that it is up to the local peer to decide how to load-balance its transmission.
  545. */
  546. else {
  547. assignFlowToBondedPath(flow, now);
  548. }
  549. return flow;
  550. }
  551. void Bond::forgetFlowsWhenNecessary(uint64_t age, bool oldest, int64_t now)
  552. {
  553. std::map<int32_t, SharedPtr<Flow> >::iterator it = _flows.begin();
  554. std::map<int32_t, SharedPtr<Flow> >::iterator oldestFlow = _flows.end();
  555. SharedPtr<Flow> expiredFlow;
  556. if (age) { // Remove by specific age
  557. while (it != _flows.end()) {
  558. if (it->second->age(now) > age) {
  559. debug("forget flow %x (age %llu) (%lu / %lu)", it->first, (unsigned long long)it->second->age(now), _paths[it->second->assignedPath].assignedFlowCount, (unsigned long)(_flows.size() - 1));
  560. _paths[it->second->assignedPath].assignedFlowCount--;
  561. it = _flows.erase(it);
  562. }
  563. else {
  564. ++it;
  565. }
  566. }
  567. }
  568. else if (oldest) { // Remove single oldest by natural expiration
  569. uint64_t maxAge = 0;
  570. while (it != _flows.end()) {
  571. if (it->second->age(now) > maxAge) {
  572. maxAge = (now - it->second->age(now));
  573. oldestFlow = it;
  574. }
  575. ++it;
  576. }
  577. if (oldestFlow != _flows.end()) {
  578. debug("forget oldest flow %x (age %llu) (total flows: %lu)", oldestFlow->first, (unsigned long long)oldestFlow->second->age(now), (unsigned long)(_flows.size() - 1));
  579. _paths[oldestFlow->second->assignedPath].assignedFlowCount--;
  580. _flows.erase(oldestFlow);
  581. }
  582. }
  583. }
  584. void Bond::processIncomingPathNegotiationRequest(uint64_t now, SharedPtr<Path>& path, int16_t remoteUtility)
  585. {
  586. char pathStr[64] = { 0 };
  587. if (_abLinkSelectMethod != ZT_BOND_RESELECTION_POLICY_OPTIMIZE) {
  588. return;
  589. }
  590. Mutex::Lock _l(_paths_m);
  591. int pathIdx = getNominatedPathIdx(path);
  592. if (pathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  593. return;
  594. }
  595. _paths[pathIdx].p->address().toString(pathStr);
  596. if (! _lastPathNegotiationCheck) {
  597. return;
  598. }
  599. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[pathIdx].p->localSocket());
  600. if (remoteUtility > _localUtility) {
  601. _paths[pathIdx].p->address().toString(pathStr);
  602. debug("peer suggests alternate link %s/%s, remote utility (%d) greater than local utility (%d), switching to suggested link\n", link->ifname().c_str(), pathStr, remoteUtility, _localUtility);
  603. _negotiatedPathIdx = pathIdx;
  604. }
  605. if (remoteUtility < _localUtility) {
  606. debug("peer suggests alternate link %s/%s, remote utility (%d) less than local utility (%d), not switching\n", link->ifname().c_str(), pathStr, remoteUtility, _localUtility);
  607. }
  608. if (remoteUtility == _localUtility) {
  609. debug("peer suggests alternate link %s/%s, remote utility (%d) equal to local utility (%d)\n", link->ifname().c_str(), pathStr, remoteUtility, _localUtility);
  610. if (_peer->_id.address().toInt() > RR->node->identity().address().toInt()) {
  611. debug("agree with peer to use alternate link %s/%s\n", link->ifname().c_str(), pathStr);
  612. _negotiatedPathIdx = pathIdx;
  613. }
  614. else {
  615. debug("ignore petition from peer to use alternate link %s/%s\n", link->ifname().c_str(), pathStr);
  616. }
  617. }
  618. }
  619. void Bond::pathNegotiationCheck(void* tPtr, int64_t now)
  620. {
  621. int maxInPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  622. int maxOutPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  623. uint64_t maxInCount = 0;
  624. uint64_t maxOutCount = 0;
  625. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  626. if (! _paths[i].p) {
  627. continue;
  628. }
  629. if (_paths[i].packetsIn > maxInCount) {
  630. maxInCount = _paths[i].packetsIn;
  631. maxInPathIdx = i;
  632. }
  633. if (_paths[i].packetsOut > maxOutCount) {
  634. maxOutCount = _paths[i].packetsOut;
  635. maxOutPathIdx = i;
  636. }
  637. _paths[i].resetPacketCounts();
  638. }
  639. bool _peerLinksSynchronized = ((maxInPathIdx != ZT_MAX_PEER_NETWORK_PATHS) && (maxOutPathIdx != ZT_MAX_PEER_NETWORK_PATHS) && (maxInPathIdx != maxOutPathIdx)) ? false : true;
  640. /**
  641. * Determine utility and attempt to petition remote peer to switch to our chosen path
  642. */
  643. if (! _peerLinksSynchronized) {
  644. _localUtility = _paths[maxOutPathIdx].failoverScore - _paths[maxInPathIdx].failoverScore;
  645. if (_paths[maxOutPathIdx].negotiated) {
  646. _localUtility -= ZT_BOND_FAILOVER_HANDICAP_NEGOTIATED;
  647. }
  648. if ((now - _lastSentPathNegotiationRequest) > ZT_PATH_NEGOTIATION_CUTOFF_TIME) {
  649. // fprintf(stderr, "BT: (sync) it's been long enough, sending more requests.\n");
  650. _numSentPathNegotiationRequests = 0;
  651. }
  652. if (_numSentPathNegotiationRequests < ZT_PATH_NEGOTIATION_TRY_COUNT) {
  653. if (_localUtility >= 0) {
  654. // fprintf(stderr, "BT: (sync) paths appear to be out of sync (utility=%d)\n", _localUtility);
  655. sendPATH_NEGOTIATION_REQUEST(tPtr, _paths[maxOutPathIdx].p);
  656. ++_numSentPathNegotiationRequests;
  657. _lastSentPathNegotiationRequest = now;
  658. // fprintf(stderr, "sending request to use %s on %s, ls=%llx, utility=%d\n", pathStr, link->ifname().c_str(), _paths[maxOutPathIdx].p->localSocket(), _localUtility);
  659. }
  660. }
  661. /**
  662. * Give up negotiating and consider switching
  663. */
  664. else if ((now - _lastSentPathNegotiationRequest) > (2 * ZT_BOND_OPTIMIZE_INTERVAL)) {
  665. if (_localUtility == 0) {
  666. // There's no loss to us, just switch without sending a another request
  667. // fprintf(stderr, "BT: (sync) giving up, switching to remote peer's path.\n");
  668. _negotiatedPathIdx = maxInPathIdx;
  669. }
  670. }
  671. }
  672. }
  673. void Bond::sendPATH_NEGOTIATION_REQUEST(void* tPtr, int pathIdx)
  674. {
  675. debug("send link negotiation request to peer via link %s, local utility is %d", pathToStr(_paths[pathIdx].p).c_str(), _localUtility);
  676. if (_abLinkSelectMethod != ZT_BOND_RESELECTION_POLICY_OPTIMIZE) {
  677. return;
  678. }
  679. Packet outp(_peer->_id.address(), RR->identity.address(), Packet::VERB_PATH_NEGOTIATION_REQUEST);
  680. outp.append<int16_t>(_localUtility);
  681. if (_paths[pathIdx].p->address()) {
  682. outp.armor(_peer->key(), false, _peer->aesKeysIfSupported());
  683. RR->node->putPacket(tPtr, _paths[pathIdx].p->localSocket(), _paths[pathIdx].p->address(), outp.data(), outp.size());
  684. }
  685. }
  686. void Bond::sendQOS_MEASUREMENT(void* tPtr, int pathIdx, int64_t localSocket, const InetAddress& atAddress, int64_t now)
  687. {
  688. int64_t _now = RR->node->now();
  689. Packet outp(_peer->_id.address(), RR->identity.address(), Packet::VERB_QOS_MEASUREMENT);
  690. char qosData[ZT_QOS_MAX_PACKET_SIZE];
  691. int16_t len = generateQoSPacket(pathIdx, _now, qosData);
  692. _overheadBytes += len;
  693. if (len) {
  694. outp.append(qosData, len);
  695. if (atAddress) {
  696. outp.armor(_peer->key(), false, _peer->aesKeysIfSupported());
  697. RR->node->putPacket(tPtr, localSocket, atAddress, outp.data(), outp.size());
  698. }
  699. else {
  700. RR->sw->send(tPtr, outp, false);
  701. }
  702. _paths[pathIdx].packetsReceivedSinceLastQoS = 0;
  703. _paths[pathIdx].lastQoSMeasurement = now;
  704. }
  705. // debug("send QOS via link %s (len=%d)", pathToStr(_paths[pathIdx].p).c_str(), len);
  706. }
  707. void Bond::processBackgroundBondTasks(void* tPtr, int64_t now)
  708. {
  709. if (! _peer->_localMultipathSupported || (now - _lastBackgroundTaskCheck) < ZT_BOND_BACKGROUND_TASK_MIN_INTERVAL) {
  710. return;
  711. }
  712. _lastBackgroundTaskCheck = now;
  713. Mutex::Lock _l(_paths_m);
  714. curateBond(now, false);
  715. if ((now - _lastQualityEstimation) > _qualityEstimationInterval) {
  716. _lastQualityEstimation = now;
  717. estimatePathQuality(now);
  718. }
  719. dumpInfo(now, false);
  720. // Send ambient monitoring traffic
  721. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  722. if (_paths[i].p && _paths[i].allowed()) {
  723. if (_isLeaf) {
  724. if ((_monitorInterval > 0) && (((now - _paths[i].p->_lastIn) >= _monitorInterval) /*|| ((now - _paths[i].p->_lastOut) >= _monitorInterval)*/)) {
  725. if ((_peer->remoteVersionProtocol() >= 5) && (! ((_peer->remoteVersionMajor() == 1) && (_peer->remoteVersionMinor() == 1) && (_peer->remoteVersionRevision() == 0)))) {
  726. Packet outp(_peer->address(), RR->identity.address(), Packet::VERB_ECHO); // ECHO (this is our bond's heartbeat)
  727. outp.armor(_peer->key(), true, _peer->aesKeysIfSupported());
  728. RR->node->expectReplyTo(outp.packetId());
  729. RR->node->putPacket(tPtr, _paths[i].p->localSocket(), _paths[i].p->address(), outp.data(), outp.size());
  730. _paths[i].p->_lastOut = now;
  731. _overheadBytes += outp.size();
  732. debug("tx: verb 0x%-2x of len %4d via %s (ECHO)", Packet::VERB_ECHO, outp.size(), pathToStr(_paths[i].p).c_str());
  733. }
  734. }
  735. // QOS
  736. if (_paths[i].needsToSendQoS(now, _qosSendInterval)) {
  737. sendQOS_MEASUREMENT(tPtr, i, _paths[i].p->localSocket(), _paths[i].p->address(), now);
  738. }
  739. }
  740. }
  741. }
  742. // Perform periodic background tasks unique to each bonding policy
  743. switch (_policy) {
  744. case ZT_BOND_POLICY_ACTIVE_BACKUP:
  745. processActiveBackupTasks(tPtr, now);
  746. break;
  747. case ZT_BOND_POLICY_BROADCAST:
  748. break;
  749. case ZT_BOND_POLICY_BALANCE_RR:
  750. case ZT_BOND_POLICY_BALANCE_XOR:
  751. case ZT_BOND_POLICY_BALANCE_AWARE:
  752. processBalanceTasks(now);
  753. break;
  754. default:
  755. break;
  756. }
  757. // Check whether or not a path negotiation needs to be performed
  758. if (((now - _lastPathNegotiationCheck) > ZT_BOND_OPTIMIZE_INTERVAL) && _allowPathNegotiation) {
  759. _lastPathNegotiationCheck = now;
  760. pathNegotiationCheck(tPtr, now);
  761. }
  762. }
  763. void Bond::curateBond(int64_t now, bool rebuildBond)
  764. {
  765. uint8_t tmpNumAliveLinks = 0;
  766. uint8_t tmpNumTotalLinks = 0;
  767. /**
  768. * Update path state variables. State variables are used so that critical
  769. * blocks that perform fast packet processing won't need to make as many
  770. * function calls or computations.
  771. */
  772. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  773. if (! _paths[i].p) {
  774. continue;
  775. }
  776. tmpNumTotalLinks++;
  777. if (_paths[i].eligible) {
  778. tmpNumAliveLinks++;
  779. }
  780. /**
  781. * Determine aliveness
  782. */
  783. _paths[i].alive = _isLeaf ? (now - _paths[i].p->_lastIn) < _failoverInterval : (now - _paths[i].p->_lastIn) < ZT_PEER_PATH_EXPIRATION;
  784. /**
  785. * Determine current eligibility
  786. */
  787. bool currEligibility = false;
  788. // Simple RX age (driven by packets of any type and gratuitous VERB_HELLOs)
  789. bool acceptableAge = _isLeaf ? (_paths[i].p->age(now) < (_failoverInterval + _downDelay)) : _paths[i].alive;
  790. // Whether we've waited long enough since the link last came online
  791. bool satisfiedUpDelay = (now - _paths[i].lastAliveToggle) >= _upDelay;
  792. // Whether this path is still in its trial period
  793. bool inTrial = (now - _paths[i].whenNominated) < ZT_BOND_OPTIMIZE_INTERVAL;
  794. // if (includeRefractoryPeriod && _paths[i].refractoryPeriod) {
  795. // As long as the refractory period value has not fully drained this path is not eligible
  796. // currEligibility = false;
  797. //}
  798. currEligibility = _paths[i].allowed() && ((acceptableAge && satisfiedUpDelay) || inTrial);
  799. // debug("[%d] allowed=%d, acceptableAge=%d, satisfiedUpDelay=%d, inTrial=%d ==== %d", i, _paths[i].allowed(), acceptableAge, satisfiedUpDelay, inTrial, currEligibility);
  800. /**
  801. * Note eligibility state change (if any) and take appropriate action
  802. */
  803. if (currEligibility != _paths[i].eligible) {
  804. if (currEligibility == 0) {
  805. log("link %s is no longer eligible", pathToStr(_paths[i].p).c_str());
  806. }
  807. if (currEligibility == 1) {
  808. log("link %s is eligible", pathToStr(_paths[i].p).c_str());
  809. }
  810. dumpPathStatus(now, i);
  811. if (currEligibility) {
  812. rebuildBond = true;
  813. }
  814. if (! currEligibility) {
  815. _paths[i].adjustRefractoryPeriod(now, _defaultPathRefractoryPeriod, ! currEligibility);
  816. if (_paths[i].bonded) {
  817. if (_allowFlowHashing) {
  818. debug("link %s was bonded, flow reallocation will occur soon", pathToStr(_paths[i].p).c_str());
  819. rebuildBond = true;
  820. _paths[i].shouldReallocateFlows = _paths[i].bonded;
  821. }
  822. _paths[i].bonded = false;
  823. }
  824. }
  825. }
  826. if (currEligibility) {
  827. _paths[i].adjustRefractoryPeriod(now, _defaultPathRefractoryPeriod, false);
  828. }
  829. _paths[i].eligible = currEligibility;
  830. }
  831. /**
  832. * Determine health status to report to user
  833. */
  834. _numAliveLinks = tmpNumAliveLinks;
  835. _numTotalLinks = tmpNumTotalLinks;
  836. bool tmpHealthStatus = true;
  837. if (_policy == ZT_BOND_POLICY_BROADCAST) {
  838. if (_numAliveLinks < 1) {
  839. // Considered healthy if we're able to send frames at all
  840. tmpHealthStatus = false;
  841. }
  842. }
  843. if ((_policy == ZT_BOND_POLICY_BALANCE_RR) || (_policy == ZT_BOND_POLICY_BALANCE_XOR) || (_policy == ZT_BOND_POLICY_BALANCE_AWARE || (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP))) {
  844. if (_numAliveLinks < _numTotalLinks) {
  845. tmpHealthStatus = false;
  846. }
  847. }
  848. if (tmpHealthStatus != _isHealthy) {
  849. std::string healthStatusStr;
  850. if (tmpHealthStatus == true) {
  851. healthStatusStr = "HEALTHY";
  852. }
  853. else {
  854. healthStatusStr = "DEGRADED";
  855. }
  856. log("bond is %s (%d/%d links)", healthStatusStr.c_str(), _numAliveLinks, _numTotalLinks);
  857. dumpInfo(now, true);
  858. }
  859. _isHealthy = tmpHealthStatus;
  860. /**
  861. * Curate the set of paths that are part of the bond proper. Select a set of paths
  862. * per logical link according to eligibility and user-specified constraints.
  863. */
  864. if ((_policy == ZT_BOND_POLICY_BALANCE_RR) || (_policy == ZT_BOND_POLICY_BALANCE_XOR) || (_policy == ZT_BOND_POLICY_BALANCE_AWARE)) {
  865. if (! _numBondedPaths) {
  866. rebuildBond = true;
  867. }
  868. if (rebuildBond) {
  869. debug("rebuilding bond");
  870. int updatedBondedPathCount = 0;
  871. // Build map associating paths with local physical links. Will be selected from in next step
  872. std::map<SharedPtr<Link>, std::vector<int> > linkMap;
  873. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  874. if (_paths[i].p) {
  875. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  876. linkMap[link].push_back(i);
  877. }
  878. }
  879. // Re-form bond from link<->path map
  880. std::map<SharedPtr<Link>, std::vector<int> >::iterator it = linkMap.begin();
  881. while (it != linkMap.end()) {
  882. SharedPtr<Link> link = it->first;
  883. int ipvPref = link->ipvPref();
  884. // If user has no address type preference, then use every path we find on a link
  885. if (ipvPref == 0) {
  886. for (int j = 0; j < it->second.size(); j++) {
  887. int idx = it->second.at(j);
  888. if (! _paths[idx].p || ! _paths[idx].eligible || ! _paths[idx].allowed()) {
  889. continue;
  890. }
  891. addPathToBond(idx, updatedBondedPathCount);
  892. ++updatedBondedPathCount;
  893. debug("add %s (no user addr preference)", pathToStr(_paths[idx].p).c_str());
  894. }
  895. }
  896. // If the user prefers to only use one address type (IPv4 or IPv6)
  897. if (ipvPref == 4 || ipvPref == 6) {
  898. for (int j = 0; j < it->second.size(); j++) {
  899. int idx = it->second.at(j);
  900. if (! _paths[idx].p || ! _paths[idx].eligible) {
  901. continue;
  902. }
  903. if (! _paths[idx].allowed()) {
  904. debug("did not add %s (user addr preference %d)", pathToStr(_paths[idx].p).c_str(), ipvPref);
  905. continue;
  906. }
  907. addPathToBond(idx, updatedBondedPathCount);
  908. ++updatedBondedPathCount;
  909. debug("add path %s (user addr preference %d)", pathToStr(_paths[idx].p).c_str(), ipvPref);
  910. }
  911. }
  912. // If the users prefers one address type to another, try to find at least
  913. // one path of that type before considering others.
  914. if (ipvPref == 46 || ipvPref == 64) {
  915. bool foundPreferredPath = false;
  916. // Search for preferred paths
  917. for (int j = 0; j < it->second.size(); j++) {
  918. int idx = it->second.at(j);
  919. if (! _paths[idx].p || ! _paths[idx].eligible || ! _paths[idx].allowed()) {
  920. continue;
  921. }
  922. if (_paths[idx].preferred()) {
  923. addPathToBond(idx, updatedBondedPathCount);
  924. ++updatedBondedPathCount;
  925. debug("add %s (user addr preference %d)", pathToStr(_paths[idx].p).c_str(), ipvPref);
  926. foundPreferredPath = true;
  927. }
  928. }
  929. // Unable to find a path that matches user preference, settle for another address type
  930. if (! foundPreferredPath) {
  931. debug("did not find first-choice path type on link %s (user preference %d)", link->ifname().c_str(), ipvPref);
  932. for (int j = 0; j < it->second.size(); j++) {
  933. int idx = it->second.at(j);
  934. if (! _paths[idx].p || ! _paths[idx].eligible) {
  935. continue;
  936. }
  937. addPathToBond(idx, updatedBondedPathCount);
  938. ++updatedBondedPathCount;
  939. debug("add %s (user addr preference %d)", pathToStr(_paths[idx].p).c_str(), ipvPref);
  940. foundPreferredPath = true;
  941. }
  942. }
  943. }
  944. ++it; // Next link
  945. }
  946. _numBondedPaths = updatedBondedPathCount;
  947. if (_policy == ZT_BOND_POLICY_BALANCE_RR) {
  948. // Cause a RR reset since the current index might no longer be valid
  949. _rrPacketsSentOnCurrLink = _packetsPerLink;
  950. }
  951. }
  952. }
  953. }
  954. void Bond::estimatePathQuality(int64_t now)
  955. {
  956. uint32_t totUserSpecifiedLinkSpeed = 0;
  957. if (_numBondedPaths) { // Compute relative user-specified speeds of links
  958. for (unsigned int i = 0; i < _numBondedPaths; ++i) {
  959. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  960. if (_paths[i].p && _paths[i].allowed()) {
  961. totUserSpecifiedLinkSpeed += link->speed();
  962. }
  963. }
  964. for (unsigned int i = 0; i < _numBondedPaths; ++i) {
  965. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  966. if (_paths[i].p && _paths[i].allowed()) {
  967. link->setRelativeSpeed((uint8_t)round(((float)link->speed() / (float)totUserSpecifiedLinkSpeed) * 255));
  968. }
  969. }
  970. }
  971. float lat[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  972. float pdv[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  973. float plr[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  974. float per[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  975. float maxLAT = 0;
  976. float maxPDV = 0;
  977. float maxPLR = 0;
  978. float maxPER = 0;
  979. float quality[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  980. uint8_t alloc[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  981. float totQuality = 0.0f;
  982. // Compute initial summary statistics
  983. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  984. if (! _paths[i].p || ! _paths[i].allowed()) {
  985. continue;
  986. }
  987. // Compute/Smooth average of real-world observations
  988. _paths[i].latencyMean = _paths[i].latencySamples.mean();
  989. _paths[i].latencyVariance = _paths[i].latencySamples.stddev();
  990. _paths[i].packetErrorRatio = 1.0 - (_paths[i].packetValiditySamples.count() ? _paths[i].packetValiditySamples.mean() : 1.0);
  991. if (userHasSpecifiedLinkSpeeds()) {
  992. // Use user-reported metrics
  993. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  994. if (link) {
  995. _paths[i].throughputMean = link->speed();
  996. _paths[i].throughputVariance = 0;
  997. }
  998. }
  999. // Drain unacknowledged QoS records
  1000. std::map<uint64_t, uint64_t>::iterator it = _paths[i].qosStatsOut.begin();
  1001. uint64_t currentLostRecords = 0;
  1002. while (it != _paths[i].qosStatsOut.end()) {
  1003. int qosRecordTimeout = 5000; //_paths[i].p->monitorInterval() * ZT_BOND_QOS_ACK_INTERVAL_MULTIPLIER * 8;
  1004. if ((now - it->second) >= qosRecordTimeout) {
  1005. // Packet was lost
  1006. it = _paths[i].qosStatsOut.erase(it);
  1007. ++currentLostRecords;
  1008. }
  1009. else {
  1010. ++it;
  1011. }
  1012. }
  1013. quality[i] = 0;
  1014. totQuality = 0;
  1015. // Normalize raw observations according to sane limits and/or user specified values
  1016. lat[i] = 1.0 / expf(4 * Utils::normalize(_paths[i].latencyMean, 0, _maxAcceptableLatency, 0, 1));
  1017. pdv[i] = 1.0 / expf(4 * Utils::normalize(_paths[i].latencyVariance, 0, _maxAcceptablePacketDelayVariance, 0, 1));
  1018. plr[i] = 1.0 / expf(4 * Utils::normalize(_paths[i].packetLossRatio, 0, _maxAcceptablePacketLossRatio, 0, 1));
  1019. per[i] = 1.0 / expf(4 * Utils::normalize(_paths[i].packetErrorRatio, 0, _maxAcceptablePacketErrorRatio, 0, 1));
  1020. // Record bond-wide maximums to determine relative values
  1021. maxLAT = lat[i] > maxLAT ? lat[i] : maxLAT;
  1022. maxPDV = pdv[i] > maxPDV ? pdv[i] : maxPDV;
  1023. maxPLR = plr[i] > maxPLR ? plr[i] : maxPLR;
  1024. maxPER = per[i] > maxPER ? per[i] : maxPER;
  1025. }
  1026. // Convert metrics to relative quantities and apply contribution weights
  1027. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1028. if (_paths[i].p && _paths[i].bonded) {
  1029. quality[i] += ((maxLAT > 0.0f ? lat[i] / maxLAT : 0.0f) * _qw[ZT_QOS_LAT_IDX]);
  1030. quality[i] += ((maxPDV > 0.0f ? pdv[i] / maxPDV : 0.0f) * _qw[ZT_QOS_PDV_IDX]);
  1031. quality[i] += ((maxPLR > 0.0f ? plr[i] / maxPLR : 0.0f) * _qw[ZT_QOS_PLR_IDX]);
  1032. quality[i] += ((maxPER > 0.0f ? per[i] / maxPER : 0.0f) * _qw[ZT_QOS_PER_IDX]);
  1033. totQuality += quality[i];
  1034. }
  1035. }
  1036. // Normalize to 8-bit allocation values
  1037. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1038. if (_paths[i].p && _paths[i].bonded) {
  1039. alloc[i] = (uint8_t)(std::ceil((quality[i] / totQuality) * (float)255));
  1040. _paths[i].allocation = alloc[i];
  1041. }
  1042. }
  1043. }
  1044. void Bond::processBalanceTasks(int64_t now)
  1045. {
  1046. if (_allowFlowHashing) {
  1047. /**
  1048. * Clean up and reset flows if necessary
  1049. */
  1050. if ((now - _lastFlowExpirationCheck) > ZT_PEER_PATH_EXPIRATION) {
  1051. Mutex::Lock _l(_flows_m);
  1052. forgetFlowsWhenNecessary(ZT_PEER_PATH_EXPIRATION, false, now);
  1053. std::map<int32_t, SharedPtr<Flow> >::iterator it = _flows.begin();
  1054. while (it != _flows.end()) {
  1055. it->second->resetByteCounts();
  1056. ++it;
  1057. }
  1058. _lastFlowExpirationCheck = now;
  1059. }
  1060. /**
  1061. * Re-allocate flows from dead paths
  1062. */
  1063. if (_policy == ZT_BOND_POLICY_BALANCE_XOR || _policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  1064. Mutex::Lock _l(_flows_m);
  1065. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1066. if (! _paths[i].p) {
  1067. continue;
  1068. }
  1069. if (! _paths[i].eligible && _paths[i].shouldReallocateFlows) {
  1070. log("reallocate flows from dead link %s", pathToStr(_paths[i].p).c_str());
  1071. std::map<int32_t, SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1072. while (flow_it != _flows.end()) {
  1073. if (_paths[flow_it->second->assignedPath].p == _paths[i].p) {
  1074. if (assignFlowToBondedPath(flow_it->second, now)) {
  1075. _paths[i].assignedFlowCount--;
  1076. }
  1077. }
  1078. ++flow_it;
  1079. }
  1080. _paths[i].shouldReallocateFlows = false;
  1081. }
  1082. }
  1083. }
  1084. /**
  1085. * Re-allocate flows from under-performing
  1086. * NOTE: This could be part of the above block but was kept separate for clarity.
  1087. */
  1088. if (_policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  1089. int totalAllocation = 0;
  1090. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1091. if (! _paths[i].p) {
  1092. continue;
  1093. }
  1094. if (_paths[i].p && _paths[i].bonded && _paths[i].eligible) {
  1095. totalAllocation += _paths[i].allocation;
  1096. }
  1097. }
  1098. unsigned char minimumAllocationValue = (uint8_t)(0.33 * ((float)totalAllocation / (float)_numBondedPaths));
  1099. Mutex::Lock _l(_flows_m);
  1100. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1101. if (! _paths[i].p) {
  1102. continue;
  1103. }
  1104. if (_paths[i].p && _paths[i].bonded && _paths[i].eligible && (_paths[i].allocation < minimumAllocationValue) && _paths[i].assignedFlowCount) {
  1105. log("reallocate flows from under-performing link %s\n", pathToStr(_paths[i].p).c_str());
  1106. std::map<int32_t, SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1107. while (flow_it != _flows.end()) {
  1108. if (flow_it->second->assignedPath == _paths[i].p) {
  1109. if (assignFlowToBondedPath(flow_it->second, now)) {
  1110. _paths[i].assignedFlowCount--;
  1111. }
  1112. }
  1113. ++flow_it;
  1114. }
  1115. _paths[i].shouldReallocateFlows = false;
  1116. }
  1117. }
  1118. }
  1119. }
  1120. }
  1121. void Bond::dequeueNextActiveBackupPath(uint64_t now)
  1122. {
  1123. if (_abFailoverQueue.empty()) {
  1124. return;
  1125. }
  1126. _abPathIdx = _abFailoverQueue.front();
  1127. _abFailoverQueue.pop_front();
  1128. _lastActiveBackupPathChange = now;
  1129. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1130. if (_paths[i].p) {
  1131. _paths[i].resetPacketCounts();
  1132. }
  1133. }
  1134. }
  1135. bool Bond::abForciblyRotateLink()
  1136. {
  1137. if (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP) {
  1138. int prevPathIdx = _abPathIdx;
  1139. dequeueNextActiveBackupPath(RR->node->now());
  1140. log("active link rotated from %s to %s", pathToStr(_paths[prevPathIdx].p).c_str(), pathToStr(_paths[_abPathIdx].p).c_str());
  1141. return true;
  1142. }
  1143. return false;
  1144. }
  1145. void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
  1146. {
  1147. int prevActiveBackupPathIdx = _abPathIdx;
  1148. int nonPreferredPathIdx;
  1149. bool bFoundPrimaryLink = false;
  1150. /**
  1151. * Generate periodic status report
  1152. */
  1153. if ((now - _lastBondStatusLog) > ZT_BOND_STATUS_INTERVAL) {
  1154. _lastBondStatusLog = now;
  1155. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1156. log("no active link");
  1157. }
  1158. else if (_paths[_abPathIdx].p) {
  1159. log("active link is %s, failover queue size is %zu", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
  1160. }
  1161. if (_abFailoverQueue.empty()) {
  1162. log("failover queue is empty, bond is no longer fault-tolerant");
  1163. }
  1164. }
  1165. /**
  1166. * Select initial "active" active-backup link
  1167. */
  1168. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1169. /**
  1170. * [Automatic mode]
  1171. * The user has not explicitly specified links or their failover schedule,
  1172. * the bonding policy will now select the first eligible path and set it as
  1173. * its active backup path, if a substantially better path is detected the bonding
  1174. * policy will assign it as the new active backup path. If the path fails it will
  1175. * simply find the next eligible path.
  1176. */
  1177. if (! userHasSpecifiedLinks()) {
  1178. debug("no user-specified links");
  1179. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1180. if (_paths[i].p && _paths[i].eligible) {
  1181. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1182. if (link) {
  1183. log("found eligible link %s", pathToStr(_paths[i].p).c_str());
  1184. _abPathIdx = i;
  1185. break;
  1186. }
  1187. }
  1188. }
  1189. }
  1190. /**
  1191. * [Manual mode]
  1192. * The user has specified links or failover rules that the bonding policy should adhere to.
  1193. */
  1194. else if (userHasSpecifiedLinks()) {
  1195. if (userHasSpecifiedPrimaryLink()) {
  1196. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1197. if (! _paths[i].p) {
  1198. continue;
  1199. }
  1200. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1201. if (_paths[i].eligible && link->primary()) {
  1202. if (! _paths[i].preferred()) {
  1203. // Found path on primary link, take note in case we don't find a preferred path
  1204. nonPreferredPathIdx = i;
  1205. bFoundPrimaryLink = true;
  1206. }
  1207. if (_paths[i].preferred()) {
  1208. _abPathIdx = i;
  1209. bFoundPrimaryLink = true;
  1210. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[_abPathIdx].p->localSocket());
  1211. if (link) {
  1212. log("found preferred primary link %s", pathToStr(_paths[_abPathIdx].p).c_str());
  1213. }
  1214. break; // Found preferred path on primary link
  1215. }
  1216. }
  1217. }
  1218. if (bFoundPrimaryLink && nonPreferredPathIdx) {
  1219. log("found non-preferred primary link");
  1220. _abPathIdx = nonPreferredPathIdx;
  1221. }
  1222. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1223. log("user-designated primary link is not yet ready");
  1224. // TODO: Should wait for some time (failover interval?) and then switch to spare link
  1225. }
  1226. }
  1227. else if (! userHasSpecifiedPrimaryLink()) {
  1228. log("user did not specify a primary link, select first available link");
  1229. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1230. if (_paths[i].p && _paths[i].eligible) {
  1231. _abPathIdx = i;
  1232. break;
  1233. }
  1234. }
  1235. if (_abPathIdx != ZT_MAX_PEER_NETWORK_PATHS) {
  1236. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[_abPathIdx].p->localSocket());
  1237. if (link) {
  1238. log("select non-primary link %s", pathToStr(_paths[_abPathIdx].p).c_str());
  1239. }
  1240. }
  1241. }
  1242. }
  1243. }
  1244. // Short-circuit if we don't have an active link yet
  1245. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1246. return;
  1247. }
  1248. // Remove ineligible paths from the failover link queue
  1249. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end();) {
  1250. if (_paths[(*it)].p && ! _paths[(*it)].eligible) {
  1251. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[(*it)].p->localSocket());
  1252. it = _abFailoverQueue.erase(it);
  1253. if (link) {
  1254. log("link %s is ineligible, removing from failover queue (%zu links in queue)", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
  1255. }
  1256. }
  1257. else {
  1258. ++it;
  1259. }
  1260. }
  1261. /**
  1262. * Failover instructions were provided by user, build queue according those as well as IPv
  1263. * preference, disregarding performance.
  1264. */
  1265. if (userHasSpecifiedFailoverInstructions()) {
  1266. /**
  1267. * Clear failover scores
  1268. */
  1269. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1270. if (_paths[i].p) {
  1271. _paths[i].failoverScore = 0;
  1272. }
  1273. }
  1274. // Follow user-specified failover instructions
  1275. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1276. if (! _paths[i].p || ! _paths[i].allowed() || ! _paths[i].eligible) {
  1277. continue;
  1278. }
  1279. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1280. int failoverScoreHandicap = _paths[i].failoverScore;
  1281. if (_paths[i].preferred()) {
  1282. failoverScoreHandicap += ZT_BOND_FAILOVER_HANDICAP_PREFERRED;
  1283. }
  1284. if (link->primary()) {
  1285. // If using "optimize" primary re-select mode, ignore user link designations
  1286. failoverScoreHandicap += ZT_BOND_FAILOVER_HANDICAP_PRIMARY;
  1287. }
  1288. if (! _paths[i].failoverScore) {
  1289. // If we didn't inherit a failover score from a "parent" that wants to use this path as a failover
  1290. int newHandicap = failoverScoreHandicap ? failoverScoreHandicap : _paths[i].allocation;
  1291. _paths[i].failoverScore = newHandicap;
  1292. }
  1293. SharedPtr<Link> failoverLink;
  1294. if (link->failoverToLink().length()) {
  1295. failoverLink = RR->bc->getLinkByName(_policyAlias, link->failoverToLink());
  1296. }
  1297. if (failoverLink) {
  1298. for (int j = 0; j < ZT_MAX_PEER_NETWORK_PATHS; j++) {
  1299. if (_paths[j].p && getLink(_paths[j].p) == failoverLink.ptr()) {
  1300. int inheritedHandicap = failoverScoreHandicap - 10;
  1301. int newHandicap = _paths[j].failoverScore > inheritedHandicap ? _paths[j].failoverScore : inheritedHandicap;
  1302. if (! _paths[j].preferred()) {
  1303. newHandicap--;
  1304. }
  1305. _paths[j].failoverScore = newHandicap;
  1306. }
  1307. }
  1308. }
  1309. if (_paths[i].p.ptr() != _paths[_abPathIdx].p.ptr()) {
  1310. bool bFoundPathInQueue = false;
  1311. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end(); ++it) {
  1312. if (_paths[i].p.ptr() == _paths[(*it)].p.ptr()) {
  1313. bFoundPathInQueue = true;
  1314. }
  1315. }
  1316. if (! bFoundPathInQueue) {
  1317. _abFailoverQueue.push_front(i);
  1318. log("add link %s to failover queue (%zu links in queue)", pathToStr(_paths[i].p).c_str(), _abFailoverQueue.size());
  1319. addPathToBond(0, i);
  1320. }
  1321. }
  1322. }
  1323. }
  1324. /**
  1325. * No failover instructions provided by user, build queue according to performance
  1326. * and IPv preference.
  1327. */
  1328. else if (! userHasSpecifiedFailoverInstructions()) {
  1329. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1330. if (! _paths[i].p || ! _paths[i].allowed() || ! _paths[i].eligible) {
  1331. continue;
  1332. }
  1333. int failoverScoreHandicap = 0;
  1334. if (_paths[i].preferred()) {
  1335. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_PREFERRED;
  1336. }
  1337. if (! _paths[i].eligible) {
  1338. failoverScoreHandicap = -10000;
  1339. }
  1340. if (getLink(_paths[i].p)->primary() && _abLinkSelectMethod != ZT_BOND_RESELECTION_POLICY_OPTIMIZE) {
  1341. // If using "optimize" primary re-select mode, ignore user link designations
  1342. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_PRIMARY;
  1343. }
  1344. /*
  1345. if (_paths[i].p.ptr() == _paths[_negotiatedPathIdx].p.ptr()) {
  1346. _paths[i].negotiated = true;
  1347. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_NEGOTIATED;
  1348. }
  1349. else {
  1350. _paths[i].negotiated = false;
  1351. }
  1352. */
  1353. _paths[i].failoverScore = _paths[i].allocation + failoverScoreHandicap;
  1354. if (_paths[i].p.ptr() != _paths[_abPathIdx].p.ptr()) {
  1355. bool bFoundPathInQueue = false;
  1356. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end(); ++it) {
  1357. if (_paths[i].p.ptr() == _paths[(*it)].p.ptr()) {
  1358. bFoundPathInQueue = true;
  1359. }
  1360. }
  1361. if (! bFoundPathInQueue) {
  1362. _abFailoverQueue.push_front(i);
  1363. log("add link %s to failover queue (%zu links in queue)", pathToStr(_paths[i].p).c_str(), _abFailoverQueue.size());
  1364. addPathToBond(0, i);
  1365. }
  1366. }
  1367. }
  1368. }
  1369. // Sort queue based on performance
  1370. if (! _abFailoverQueue.empty()) {
  1371. for (int i = 0; i < _abFailoverQueue.size(); i++) {
  1372. int value_to_insert = _abFailoverQueue[i];
  1373. int hole_position = i;
  1374. while (hole_position > 0 && (_abFailoverQueue[hole_position - 1] > value_to_insert)) {
  1375. _abFailoverQueue[hole_position] = _abFailoverQueue[hole_position - 1];
  1376. hole_position = hole_position - 1;
  1377. }
  1378. _abFailoverQueue[hole_position] = value_to_insert;
  1379. }
  1380. }
  1381. /**
  1382. * Short-circuit if we have no queued paths
  1383. */
  1384. if (_abFailoverQueue.empty()) {
  1385. return;
  1386. }
  1387. /**
  1388. * Fulfill primary re-select obligations
  1389. */
  1390. if (_paths[_abPathIdx].p && ! _paths[_abPathIdx].eligible) { // Implicit ZT_BOND_RESELECTION_POLICY_FAILURE
  1391. log("link %s has failed, select link from failover queue (%zu links in queue)", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
  1392. if (! _abFailoverQueue.empty()) {
  1393. dequeueNextActiveBackupPath(now);
  1394. log("active link switched to %s", pathToStr(_paths[_abPathIdx].p).c_str());
  1395. }
  1396. else {
  1397. log("failover queue is empty, no links to choose from");
  1398. }
  1399. }
  1400. /**
  1401. * Detect change to prevent flopping during later optimization step.
  1402. */
  1403. if (prevActiveBackupPathIdx != _abPathIdx) {
  1404. _lastActiveBackupPathChange = now;
  1405. }
  1406. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_ALWAYS) {
  1407. if (_paths[_abPathIdx].p && ! getLink(_paths[_abPathIdx].p)->primary() && getLink(_paths[_abFailoverQueue.front()].p)->primary()) {
  1408. dequeueNextActiveBackupPath(now);
  1409. log("switch back to available primary link %s (select mode: always)", pathToStr(_paths[_abPathIdx].p).c_str());
  1410. }
  1411. }
  1412. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_BETTER) {
  1413. if (_paths[_abPathIdx].p && ! getLink(_paths[_abPathIdx].p)->primary()) {
  1414. // Active backup has switched to "better" primary link according to re-select policy.
  1415. if (getLink(_paths[_abFailoverQueue.front()].p)->primary() && (_paths[_abFailoverQueue.front()].failoverScore > _paths[_abPathIdx].failoverScore)) {
  1416. dequeueNextActiveBackupPath(now);
  1417. log("switch back to user-defined primary link %s (select mode: better)", pathToStr(_paths[_abPathIdx].p).c_str());
  1418. }
  1419. }
  1420. }
  1421. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_OPTIMIZE && ! _abFailoverQueue.empty()) {
  1422. /**
  1423. * Implement link negotiation that was previously-decided
  1424. */
  1425. if (_paths[_abFailoverQueue.front()].negotiated) {
  1426. dequeueNextActiveBackupPath(now);
  1427. _lastPathNegotiationCheck = now;
  1428. log("switch negotiated link %s (select mode: optimize)", pathToStr(_paths[_abPathIdx].p).c_str());
  1429. }
  1430. else {
  1431. // Try to find a better path and automatically switch to it -- not too often, though.
  1432. if ((now - _lastActiveBackupPathChange) > ZT_BOND_OPTIMIZE_INTERVAL) {
  1433. if (! _abFailoverQueue.empty()) {
  1434. int newFScore = _paths[_abFailoverQueue.front()].failoverScore;
  1435. int prevFScore = _paths[_abPathIdx].failoverScore;
  1436. // Establish a minimum switch threshold to prevent flapping
  1437. int failoverScoreDifference = _paths[_abFailoverQueue.front()].failoverScore - _paths[_abPathIdx].failoverScore;
  1438. int thresholdQuantity = (int)(ZT_BOND_ACTIVE_BACKUP_OPTIMIZE_MIN_THRESHOLD * (float)_paths[_abPathIdx].allocation);
  1439. if ((failoverScoreDifference > 0) && (failoverScoreDifference > thresholdQuantity)) {
  1440. SharedPtr<Path> oldPath = _paths[_abPathIdx].p;
  1441. dequeueNextActiveBackupPath(now);
  1442. log("switch from %s (score: %d) to better link %s (score: %d) (select mode: optimize)",
  1443. pathToStr(oldPath).c_str(),
  1444. prevFScore,
  1445. pathToStr(_paths[_abPathIdx].p).c_str(),
  1446. newFScore);
  1447. }
  1448. }
  1449. }
  1450. }
  1451. }
  1452. }
  1453. void Bond::initTimers()
  1454. {
  1455. _lastFlowExpirationCheck = 0;
  1456. _lastFlowRebalance = 0;
  1457. _lastSentPathNegotiationRequest = 0;
  1458. _lastPathNegotiationCheck = 0;
  1459. _lastPathNegotiationReceived = 0;
  1460. _lastQoSRateCheck = 0;
  1461. _lastQualityEstimation = 0;
  1462. _lastBondStatusLog = 0;
  1463. _lastSummaryDump = 0;
  1464. _lastActiveBackupPathChange = 0;
  1465. _lastFrame = 0;
  1466. _lastBackgroundTaskCheck = 0;
  1467. }
  1468. void Bond::setBondParameters(int policy, SharedPtr<Bond> templateBond, bool useTemplate)
  1469. {
  1470. // Sanity check for policy
  1471. _defaultPolicy = (_defaultPolicy <= ZT_BOND_POLICY_NONE || _defaultPolicy > ZT_BOND_POLICY_BALANCE_AWARE) ? ZT_BOND_POLICY_NONE : _defaultPolicy;
  1472. _policy = (policy <= ZT_BOND_POLICY_NONE || policy > ZT_BOND_POLICY_BALANCE_AWARE) ? ZT_BOND_POLICY_NONE : _defaultPolicy;
  1473. // Check if non-leaf to prevent spamming infrastructure
  1474. if (_peer) {
  1475. ZT_PeerRole role = RR->topology->role(_peer->address());
  1476. _isLeaf = (role != ZT_PEER_ROLE_PLANET && role != ZT_PEER_ROLE_MOON);
  1477. }
  1478. // Flows
  1479. _allowFlowHashing = false;
  1480. // Path negotiation
  1481. _allowPathNegotiation = false;
  1482. _pathNegotiationCutoffCount = 0;
  1483. _localUtility = 0;
  1484. _negotiatedPathIdx = 0;
  1485. // QOS Verb (and related checks)
  1486. _qosCutoffCount = 0;
  1487. // User preferences which may override the default bonding algorithm's behavior
  1488. _userHasSpecifiedPrimaryLink = false;
  1489. _userHasSpecifiedFailoverInstructions = false;
  1490. _userHasSpecifiedLinkSpeeds = 0;
  1491. // Bond status
  1492. _isHealthy = false;
  1493. _numAliveLinks = 0;
  1494. _numTotalLinks = 0;
  1495. _numBondedPaths = 0;
  1496. // active-backup
  1497. _abPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1498. // rr
  1499. _rrPacketsSentOnCurrLink = 0;
  1500. _rrIdx = 0;
  1501. // General parameters
  1502. _downDelay = 0;
  1503. _upDelay = 0;
  1504. _monitorInterval = 0;
  1505. // (Sane?) limits
  1506. _maxAcceptableLatency = 100;
  1507. _maxAcceptablePacketDelayVariance = 50;
  1508. _maxAcceptablePacketLossRatio = 0.10f;
  1509. _maxAcceptablePacketErrorRatio = 0.10f;
  1510. // balance-aware
  1511. _totalBondUnderload = 0;
  1512. _overheadBytes = 0;
  1513. /**
  1514. * Policy-specific defaults
  1515. */
  1516. switch (_policy) {
  1517. case ZT_BOND_POLICY_ACTIVE_BACKUP:
  1518. _abLinkSelectMethod = ZT_BOND_RESELECTION_POLICY_OPTIMIZE;
  1519. break;
  1520. case ZT_BOND_POLICY_BROADCAST:
  1521. _downDelay = 30000;
  1522. _upDelay = 0;
  1523. break;
  1524. case ZT_BOND_POLICY_BALANCE_RR:
  1525. _packetsPerLink = 64;
  1526. break;
  1527. case ZT_BOND_POLICY_BALANCE_XOR:
  1528. _allowFlowHashing = true;
  1529. break;
  1530. case ZT_BOND_POLICY_BALANCE_AWARE:
  1531. _allowFlowHashing = true;
  1532. break;
  1533. default:
  1534. break;
  1535. }
  1536. _qw[ZT_QOS_LAT_IDX] = 0.3f;
  1537. _qw[ZT_QOS_LTM_IDX] = 0.1f;
  1538. _qw[ZT_QOS_PDV_IDX] = 0.3f;
  1539. _qw[ZT_QOS_PLR_IDX] = 0.1f;
  1540. _qw[ZT_QOS_PER_IDX] = 0.1f;
  1541. _qw[ZT_QOS_SCP_IDX] = 0.1f;
  1542. _failoverInterval = ZT_BOND_FAILOVER_DEFAULT_INTERVAL;
  1543. /* If a user has specified custom parameters for this bonding policy, overlay them onto the defaults */
  1544. if (useTemplate) {
  1545. _policyAlias = templateBond->_policyAlias;
  1546. _policy = templateBond->policy();
  1547. _failoverInterval = templateBond->_failoverInterval >= ZT_BOND_FAILOVER_MIN_INTERVAL ? templateBond->_failoverInterval : ZT_BOND_FAILOVER_MIN_INTERVAL;
  1548. _downDelay = templateBond->_downDelay;
  1549. _upDelay = templateBond->_upDelay;
  1550. _abLinkSelectMethod = templateBond->_abLinkSelectMethod;
  1551. memcpy(_qw, templateBond->_qw, ZT_QOS_WEIGHT_SIZE * sizeof(float));
  1552. }
  1553. if (!_isLeaf) {
  1554. _policy = ZT_BOND_POLICY_ACTIVE_BACKUP;
  1555. }
  1556. // Timer geometry
  1557. _monitorInterval = _failoverInterval / ZT_BOND_ECHOS_PER_FAILOVER_INTERVAL;
  1558. _qualityEstimationInterval = _failoverInterval * 2;
  1559. _qosSendInterval = _failoverInterval * 2;
  1560. _qosCutoffCount = 0;
  1561. _defaultPathRefractoryPeriod = 8000;
  1562. }
  1563. void Bond::setUserQualityWeights(float weights[], int len)
  1564. {
  1565. if (len == ZT_QOS_WEIGHT_SIZE) {
  1566. float weightTotal = 0.0;
  1567. for (unsigned int i = 0; i < ZT_QOS_WEIGHT_SIZE; ++i) {
  1568. weightTotal += weights[i];
  1569. }
  1570. if (weightTotal > 0.99 && weightTotal < 1.01) {
  1571. memcpy(_qw, weights, len * sizeof(float));
  1572. }
  1573. }
  1574. }
  1575. SharedPtr<Link> Bond::getLink(const SharedPtr<Path>& path)
  1576. {
  1577. return RR->bc->getLinkBySocket(_policyAlias, path->localSocket());
  1578. }
  1579. std::string Bond::pathToStr(const SharedPtr<Path>& path)
  1580. {
  1581. #ifdef ZT_TRACE
  1582. char pathStr[64] = { 0 };
  1583. char fullPathStr[384] = { 0 };
  1584. path->address().toString(pathStr);
  1585. snprintf(fullPathStr, 384, "%.16llx-%s/%s", (unsigned long long)(path->localSocket()), getLink(path)->ifname().c_str(), pathStr);
  1586. return std::string(fullPathStr);
  1587. #else
  1588. return "";
  1589. #endif
  1590. }
  1591. void Bond::dumpPathStatus(int64_t now, int pathIdx)
  1592. {
  1593. #ifdef ZT_TRACE
  1594. std::string aliveOrDead = _paths[pathIdx].alive ? std::string("alive") : std::string("dead");
  1595. std::string eligibleOrNot = _paths[pathIdx].eligible ? std::string("eligible") : std::string("ineligible");
  1596. std::string bondedOrNot = _paths[pathIdx].bonded ? std::string("bonded") : std::string("unbonded");
  1597. log("path[%2d] --- %5s (in %7d, out: %7d), %10s, %8s, flows=%-6d lat=%-8.3f pdv=%-7.3f err=%-6.4f loss=%-6.4f alloc=%-3d --- (%s)",
  1598. pathIdx,
  1599. aliveOrDead.c_str(),
  1600. _paths[pathIdx].p->age(now),
  1601. (now - _paths[pathIdx].p->_lastOut),
  1602. eligibleOrNot.c_str(),
  1603. bondedOrNot.c_str(),
  1604. _paths[pathIdx].assignedFlowCount,
  1605. _paths[pathIdx].latencyMean,
  1606. _paths[pathIdx].latencyVariance,
  1607. _paths[pathIdx].packetErrorRatio,
  1608. _paths[pathIdx].packetLossRatio,
  1609. _paths[pathIdx].allocation,
  1610. pathToStr(_paths[pathIdx].p).c_str());
  1611. #endif
  1612. }
  1613. void Bond::dumpInfo(int64_t now, bool force)
  1614. {
  1615. #ifdef ZT_TRACE
  1616. uint64_t timeSinceLastDump = now - _lastSummaryDump;
  1617. if (! force && timeSinceLastDump < ZT_BOND_STATUS_INTERVAL) {
  1618. return;
  1619. }
  1620. _lastSummaryDump = now;
  1621. float overhead = (_overheadBytes / (timeSinceLastDump / 1000.0f) / 1000.0f);
  1622. _overheadBytes = 0;
  1623. log("bond: bp=%d, fi=%d, mi=%d, ud=%d, dd=%d, flows=%lu, leaf=%d, overhead=%f KB/s",
  1624. _policy,
  1625. _failoverInterval,
  1626. _monitorInterval,
  1627. _upDelay,
  1628. _downDelay,
  1629. (unsigned long)_flows.size(),
  1630. _isLeaf,
  1631. overhead);
  1632. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1633. if (_paths[i].p) {
  1634. dumpPathStatus(now, i);
  1635. }
  1636. }
  1637. log("");
  1638. #endif
  1639. }
  1640. } // namespace ZeroTier