Bond.cpp 64 KB

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