Bond.cpp 59 KB

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