Bond.cpp 71 KB

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