Bond.cpp 70 KB

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