Bond.cpp 69 KB

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