Bond.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987
  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, 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. maxObservedLinkCap = linkSpeed > maxObservedLinkCap ? linkSpeed : maxObservedLinkCap;
  1181. }
  1182. }
  1183. }
  1184. // Compute relative link capacity (Used for weighting traffic allocations)
  1185. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1186. if (_paths[i].p && _paths[i].allowed()) {
  1187. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1188. if (link) {
  1189. float relativeCapacity = (link->capacity() / (float)maxObservedLinkCap);
  1190. link->setRelativeCapacity(relativeCapacity);
  1191. _paths[i].relativeLinkCapacity = relativeCapacity;
  1192. }
  1193. }
  1194. }
  1195. // Convert metrics to relative quantities and apply contribution weights
  1196. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1197. if (_paths[i].p && _paths[i].bonded) {
  1198. absoluteQuality[i] += ((maxLAT > 0.0f ? lat[i] / maxLAT : 0.0f) * _qw[ZT_QOS_LAT_WEIGHT_IDX]);
  1199. absoluteQuality[i] += ((maxPDV > 0.0f ? pdv[i] / maxPDV : 0.0f) * _qw[ZT_QOS_PDV_WEIGHT_IDX]);
  1200. absoluteQuality[i] += ((maxPLR > 0.0f ? plr[i] / maxPLR : 0.0f) * _qw[ZT_QOS_PLR_WEIGHT_IDX]);
  1201. absoluteQuality[i] += ((maxPER > 0.0f ? per[i] / maxPER : 0.0f) * _qw[ZT_QOS_PER_WEIGHT_IDX]);
  1202. absoluteQuality[i] *= _paths[i].relativeLinkCapacity;
  1203. totQuality += absoluteQuality[i];
  1204. }
  1205. }
  1206. // Compute quality of link relative to all others in the bond (also accounting for stated link capacity)
  1207. if (totQuality > 0.0) {
  1208. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1209. if (_paths[i].p && _paths[i].bonded) {
  1210. _paths[i].relativeQuality = absoluteQuality[i] / totQuality;
  1211. // debug("[%2d], abs=%f, tot=%f, rel=%f, relcap=%f", i, absoluteQuality[i], totQuality, _paths[i].relativeQuality, _paths[i].relativeLinkCapacity);
  1212. }
  1213. }
  1214. }
  1215. // Compute summary statistics
  1216. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1217. if (! _paths[i].p || ! _paths[i].allowed()) {
  1218. continue;
  1219. }
  1220. // Compute/Smooth average of real-world observations
  1221. if (_paths[i].latencySamples.count() == ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE) {
  1222. _paths[i].latency = _paths[i].latencySamples.mean();
  1223. }
  1224. if (_paths[i].latencySamples.count() == ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE) {
  1225. _paths[i].latencyVariance = _paths[i].latencySamples.stddev();
  1226. }
  1227. // Write values to external path object so that it can be propagated to the user
  1228. _paths[i].p->_latencyMean = _paths[i].latency;
  1229. _paths[i].p->_latencyVariance = _paths[i].latencyVariance;
  1230. _paths[i].p->_packetLossRatio = _paths[i].packetLossRatio;
  1231. _paths[i].p->_packetErrorRatio = _paths[i].packetErrorRatio;
  1232. _paths[i].p->_bonded = _paths[i].bonded;
  1233. _paths[i].p->_eligible = _paths[i].eligible;
  1234. //_paths[i].packetErrorRatio = 1.0 - (_paths[i].packetValiditySamples.count() ? _paths[i].packetValiditySamples.mean() : 1.0);
  1235. // _valid is written elsewhere
  1236. _paths[i].p->_relativeQuality = _paths[i].relativeQuality;
  1237. }
  1238. // Flag links for avoidance
  1239. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1240. if (! _paths[i].p || ! _paths[i].allowed()) {
  1241. continue;
  1242. }
  1243. bool shouldAvoid = false;
  1244. if (! _paths[i].shouldAvoid) {
  1245. if (_paths[i].latency > _qw[ZT_QOS_LAT_MAX_IDX]) {
  1246. 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]);
  1247. shouldAvoid = true;
  1248. }
  1249. if (_paths[i].latencyVariance > _qw[ZT_QOS_PDV_MAX_IDX]) {
  1250. 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]);
  1251. shouldAvoid = true;
  1252. }
  1253. if (_paths[i].packetErrorRatio > _qw[ZT_QOS_PER_MAX_IDX]) {
  1254. 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]);
  1255. shouldAvoid = true;
  1256. }
  1257. if (_paths[i].packetLossRatio > _qw[ZT_QOS_PLR_MAX_IDX]) {
  1258. 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]);
  1259. shouldAvoid = true;
  1260. }
  1261. _paths[i].shouldAvoid = shouldAvoid;
  1262. }
  1263. else {
  1264. if (! shouldAvoid) {
  1265. log("no longer avoiding link %s", pathToStr(_paths[i].p).c_str());
  1266. _paths[i].shouldAvoid = false;
  1267. }
  1268. }
  1269. }
  1270. }
  1271. void Bond::processBalanceTasks(int64_t now)
  1272. {
  1273. if (! _numBondedPaths) {
  1274. return;
  1275. }
  1276. /**
  1277. * Clean up and reset flows if necessary
  1278. */
  1279. if ((now - _lastFlowExpirationCheck) > ZT_PEER_PATH_EXPIRATION) {
  1280. Mutex::Lock _l(_flows_m);
  1281. forgetFlowsWhenNecessary(ZT_PEER_PATH_EXPIRATION, false, now);
  1282. std::map<int16_t, SharedPtr<Flow> >::iterator it = _flows.begin();
  1283. while (it != _flows.end()) {
  1284. it->second->resetByteCounts();
  1285. ++it;
  1286. }
  1287. _lastFlowExpirationCheck = now;
  1288. }
  1289. /**
  1290. * Move (all) flows from dead paths
  1291. */
  1292. if (_policy == ZT_BOND_POLICY_BALANCE_XOR || _policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  1293. Mutex::Lock _l(_flows_m);
  1294. std::map<int16_t, SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1295. while (flow_it != _flows.end()) {
  1296. if (_paths[flow_it->second->assignedPath].p) {
  1297. int originalPathIdx = flow_it->second->assignedPath;
  1298. if (! _paths[originalPathIdx].eligible) {
  1299. log("moving all flows from dead link %s", pathToStr(_paths[originalPathIdx].p).c_str());
  1300. if (assignFlowToBondedPath(flow_it->second, now, true)) {
  1301. _paths[originalPathIdx].assignedFlowCount--;
  1302. }
  1303. }
  1304. }
  1305. ++flow_it;
  1306. }
  1307. }
  1308. /**
  1309. * Move (some) flows from low quality paths
  1310. */
  1311. if (_policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  1312. Mutex::Lock _l(_flows_m);
  1313. std::map<int16_t, SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1314. while (flow_it != _flows.end()) {
  1315. if (_paths[flow_it->second->assignedPath].p) {
  1316. int originalPathIdx = flow_it->second->assignedPath;
  1317. if (_paths[originalPathIdx].shouldAvoid) {
  1318. if (assignFlowToBondedPath(flow_it->second, now, true)) {
  1319. _paths[originalPathIdx].assignedFlowCount--;
  1320. return; // Only move one flow at a time
  1321. }
  1322. }
  1323. }
  1324. ++flow_it;
  1325. }
  1326. }
  1327. }
  1328. void Bond::dequeueNextActiveBackupPath(uint64_t now)
  1329. {
  1330. if (_abFailoverQueue.empty()) {
  1331. return;
  1332. }
  1333. _abPathIdx = _abFailoverQueue.front();
  1334. _abFailoverQueue.pop_front();
  1335. _lastActiveBackupPathChange = now;
  1336. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1337. if (_paths[i].p) {
  1338. _paths[i].resetPacketCounts();
  1339. }
  1340. }
  1341. }
  1342. bool Bond::abForciblyRotateLink()
  1343. {
  1344. Mutex::Lock _l(_paths_m);
  1345. if (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP) {
  1346. int prevPathIdx = _abPathIdx;
  1347. dequeueNextActiveBackupPath(RR->node->now());
  1348. log("active link rotated from %s to %s", pathToStr(_paths[prevPathIdx].p).c_str(), pathToStr(_paths[_abPathIdx].p).c_str());
  1349. return true;
  1350. }
  1351. return false;
  1352. }
  1353. void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
  1354. {
  1355. int prevActiveBackupPathIdx = _abPathIdx;
  1356. int nonPreferredPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1357. bool bFoundPrimaryLink = false;
  1358. if (_abPathIdx != ZT_MAX_PEER_NETWORK_PATHS && ! _paths[_abPathIdx].p) {
  1359. _abPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1360. log("main active-backup path has been removed");
  1361. }
  1362. /**
  1363. * Generate periodic status report
  1364. */
  1365. if ((now - _lastBondStatusLog) > ZT_BOND_STATUS_INTERVAL) {
  1366. _lastBondStatusLog = now;
  1367. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1368. log("no active link");
  1369. }
  1370. else if (_paths[_abPathIdx].p) {
  1371. log("active link is %s, failover queue size is %zu", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
  1372. }
  1373. if (_abFailoverQueue.empty()) {
  1374. log("failover queue is empty, bond is no longer fault-tolerant");
  1375. }
  1376. }
  1377. /**
  1378. * Select initial "active" active-backup link
  1379. */
  1380. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1381. /**
  1382. * [Automatic mode]
  1383. * The user has not explicitly specified links or their failover schedule,
  1384. * the bonding policy will now select the first eligible path and set it as
  1385. * its active backup path, if a substantially better path is detected the bonding
  1386. * policy will assign it as the new active backup path. If the path fails it will
  1387. * simply find the next eligible path.
  1388. */
  1389. if (! userHasSpecifiedLinks()) {
  1390. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1391. if (_paths[i].p && _paths[i].eligible) {
  1392. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1393. if (link) {
  1394. log("found eligible link %s", pathToStr(_paths[i].p).c_str());
  1395. _abPathIdx = i;
  1396. break;
  1397. }
  1398. }
  1399. }
  1400. }
  1401. /**
  1402. * [Manual mode]
  1403. * The user has specified links or failover rules that the bonding policy should adhere to.
  1404. */
  1405. else if (userHasSpecifiedLinks()) {
  1406. if (userHasSpecifiedPrimaryLink()) {
  1407. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1408. if (! _paths[i].p) {
  1409. continue;
  1410. }
  1411. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1412. if (link) {
  1413. if (_paths[i].eligible && link->primary()) {
  1414. if (! _paths[i].preferred()) {
  1415. // Found path on primary link, take note in case we don't find a preferred path
  1416. nonPreferredPathIdx = i;
  1417. bFoundPrimaryLink = true;
  1418. }
  1419. if (_paths[i].preferred()) {
  1420. _abPathIdx = i;
  1421. bFoundPrimaryLink = true;
  1422. if (_paths[_abPathIdx].p) {
  1423. SharedPtr<Link> abLink = RR->bc->getLinkBySocket(_policyAlias, _paths[_abPathIdx].p->localSocket());
  1424. if (abLink) {
  1425. log("found preferred primary link %s", pathToStr(_paths[_abPathIdx].p).c_str());
  1426. }
  1427. break; // Found preferred path on primary link
  1428. }
  1429. }
  1430. }
  1431. }
  1432. }
  1433. if (bFoundPrimaryLink && (nonPreferredPathIdx != ZT_MAX_PEER_NETWORK_PATHS)) {
  1434. log("found non-preferred primary link");
  1435. _abPathIdx = nonPreferredPathIdx;
  1436. }
  1437. }
  1438. else if (! userHasSpecifiedPrimaryLink()) {
  1439. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1440. if (_paths[i].p && _paths[i].eligible) {
  1441. _abPathIdx = i;
  1442. break;
  1443. }
  1444. }
  1445. if (_abPathIdx != ZT_MAX_PEER_NETWORK_PATHS) {
  1446. if (_paths[_abPathIdx].p) {
  1447. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[_abPathIdx].p->localSocket());
  1448. if (link) {
  1449. log("select non-primary link %s", pathToStr(_paths[_abPathIdx].p).c_str());
  1450. }
  1451. }
  1452. }
  1453. }
  1454. }
  1455. }
  1456. // Short-circuit if we don't have an active link yet. Everything below is optimization from the base case
  1457. if (_abPathIdx < 0 || _abPathIdx == ZT_MAX_PEER_NETWORK_PATHS || (! _paths[_abPathIdx].p)) {
  1458. return;
  1459. }
  1460. // Remove ineligible paths from the failover link queue
  1461. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end();) {
  1462. if (! _paths[(*it)].p) {
  1463. log("link is no longer valid, removing from failover queue (%zu links remain in queue)", _abFailoverQueue.size());
  1464. it = _abFailoverQueue.erase(it);
  1465. continue;
  1466. }
  1467. if (_paths[(*it)].p && ! _paths[(*it)].eligible) {
  1468. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[(*it)].p->localSocket());
  1469. it = _abFailoverQueue.erase(it);
  1470. if (link) {
  1471. log("link %s is ineligible, removing from failover queue (%zu links remain in queue)", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
  1472. }
  1473. continue;
  1474. }
  1475. else {
  1476. ++it;
  1477. }
  1478. }
  1479. /**
  1480. * Failover instructions were provided by user, build queue according those as well as IPv
  1481. * preference, disregarding performance.
  1482. */
  1483. if (userHasSpecifiedFailoverInstructions()) {
  1484. /**
  1485. * Clear failover scores
  1486. */
  1487. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1488. if (_paths[i].p) {
  1489. _paths[i].failoverScore = 0;
  1490. }
  1491. }
  1492. // Follow user-specified failover instructions
  1493. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1494. if (! _paths[i].p || ! _paths[i].allowed() || ! _paths[i].eligible) {
  1495. continue;
  1496. }
  1497. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1498. if (! link) {
  1499. continue;
  1500. }
  1501. int failoverScoreHandicap = _paths[i].failoverScore;
  1502. if (_paths[i].preferred()) {
  1503. failoverScoreHandicap += ZT_BOND_FAILOVER_HANDICAP_PREFERRED;
  1504. }
  1505. if (link->primary()) {
  1506. // If using "optimize" primary re-select mode, ignore user link designations
  1507. failoverScoreHandicap += ZT_BOND_FAILOVER_HANDICAP_PRIMARY;
  1508. }
  1509. if (! _paths[i].failoverScore) {
  1510. // If we didn't inherit a failover score from a "parent" that wants to use this path as a failover
  1511. int newHandicap = failoverScoreHandicap ? failoverScoreHandicap : (_paths[i].relativeQuality * 255.0);
  1512. _paths[i].failoverScore = newHandicap;
  1513. }
  1514. SharedPtr<Link> failoverLink;
  1515. if (link->failoverToLink().length()) {
  1516. failoverLink = RR->bc->getLinkByName(_policyAlias, link->failoverToLink());
  1517. }
  1518. if (failoverLink) {
  1519. for (int j = 0; j < ZT_MAX_PEER_NETWORK_PATHS; j++) {
  1520. if (_paths[j].p && getLink(_paths[j].p) == failoverLink.ptr()) {
  1521. int inheritedHandicap = failoverScoreHandicap - 10;
  1522. int newHandicap = _paths[j].failoverScore > inheritedHandicap ? _paths[j].failoverScore : inheritedHandicap;
  1523. if (! _paths[j].preferred()) {
  1524. newHandicap--;
  1525. }
  1526. _paths[j].failoverScore = newHandicap;
  1527. }
  1528. }
  1529. }
  1530. if (_paths[i].p) {
  1531. if (_paths[i].p.ptr() != _paths[_abPathIdx].p.ptr()) {
  1532. bool bFoundPathInQueue = false;
  1533. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end(); ++it) {
  1534. if (_paths[(*it)].p && (_paths[i].p.ptr() == _paths[(*it)].p.ptr())) {
  1535. bFoundPathInQueue = true;
  1536. }
  1537. }
  1538. if (! bFoundPathInQueue) {
  1539. _abFailoverQueue.push_front(i);
  1540. log("add link %s to failover queue (%zu links in queue)", pathToStr(_paths[i].p).c_str(), _abFailoverQueue.size());
  1541. addPathToBond(0, i);
  1542. }
  1543. }
  1544. }
  1545. }
  1546. }
  1547. /**
  1548. * No failover instructions provided by user, build queue according to performance
  1549. * and IPv preference.
  1550. */
  1551. else if (! userHasSpecifiedFailoverInstructions()) {
  1552. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1553. if (! _paths[i].p || ! _paths[i].allowed() || ! _paths[i].eligible) {
  1554. continue;
  1555. }
  1556. int failoverScoreHandicap = 0;
  1557. if (_paths[i].preferred()) {
  1558. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_PREFERRED;
  1559. }
  1560. if (! _paths[i].eligible) {
  1561. failoverScoreHandicap = -10000;
  1562. }
  1563. SharedPtr<Link> link = getLink(_paths[i].p);
  1564. if (! link) {
  1565. continue;
  1566. }
  1567. if (link->primary() && _abLinkSelectMethod != ZT_BOND_RESELECTION_POLICY_OPTIMIZE) {
  1568. // If using "optimize" primary re-select mode, ignore user link designations
  1569. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_PRIMARY;
  1570. }
  1571. /*
  1572. if (_paths[i].p.ptr() == _paths[_negotiatedPathIdx].p.ptr()) {
  1573. _paths[i].negotiated = true;
  1574. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_NEGOTIATED;
  1575. }
  1576. else {
  1577. _paths[i].negotiated = false;
  1578. }
  1579. */
  1580. _paths[i].failoverScore = _paths[i].relativeQuality + failoverScoreHandicap;
  1581. if (_paths[i].p.ptr() != _paths[_abPathIdx].p.ptr()) {
  1582. bool bFoundPathInQueue = false;
  1583. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end(); ++it) {
  1584. if (_paths[i].p.ptr() == _paths[(*it)].p.ptr()) {
  1585. bFoundPathInQueue = true;
  1586. }
  1587. }
  1588. if (! bFoundPathInQueue) {
  1589. _abFailoverQueue.push_front(i);
  1590. log("add link %s to failover queue (%zu links in queue)", pathToStr(_paths[i].p).c_str(), _abFailoverQueue.size());
  1591. addPathToBond(0, i);
  1592. }
  1593. }
  1594. }
  1595. }
  1596. // Sort queue based on performance
  1597. if (! _abFailoverQueue.empty()) {
  1598. for (int i = 0; i < _abFailoverQueue.size(); i++) {
  1599. int value_to_insert = _abFailoverQueue[i];
  1600. int hole_position = i;
  1601. while (hole_position > 0 && (_abFailoverQueue[hole_position - 1] > value_to_insert)) {
  1602. _abFailoverQueue[hole_position] = _abFailoverQueue[hole_position - 1];
  1603. hole_position = hole_position - 1;
  1604. }
  1605. _abFailoverQueue[hole_position] = value_to_insert;
  1606. }
  1607. }
  1608. /**
  1609. * Short-circuit if we have no queued paths
  1610. */
  1611. if (_abFailoverQueue.empty()) {
  1612. return;
  1613. }
  1614. /**
  1615. * Fulfill primary re-select obligations
  1616. */
  1617. if (! _paths[_abPathIdx].eligible) { // Implicit ZT_BOND_RESELECTION_POLICY_FAILURE
  1618. log("link %s has failed, select link from failover queue (%zu links in queue)", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
  1619. if (! _abFailoverQueue.empty()) {
  1620. dequeueNextActiveBackupPath(now);
  1621. log("active link switched to %s", pathToStr(_paths[_abPathIdx].p).c_str());
  1622. }
  1623. else {
  1624. log("failover queue is empty, no links to choose from");
  1625. }
  1626. }
  1627. /**
  1628. * Detect change to prevent flopping during later optimization step.
  1629. */
  1630. if (prevActiveBackupPathIdx != _abPathIdx) {
  1631. _lastActiveBackupPathChange = now;
  1632. }
  1633. if (_abFailoverQueue.empty()) {
  1634. return; // No sense in continuing since there are no links to switch to
  1635. }
  1636. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_ALWAYS) {
  1637. SharedPtr<Link> abLink = getLink(_paths[_abPathIdx].p);
  1638. if (! _paths[_abFailoverQueue.front()].p) {
  1639. log("invalid link. not switching");
  1640. return;
  1641. }
  1642. SharedPtr<Link> abFailoverLink = getLink(_paths[_abFailoverQueue.front()].p);
  1643. if (abLink && ! abLink->primary() && _paths[_abFailoverQueue.front()].p && abFailoverLink && abFailoverLink->primary()) {
  1644. dequeueNextActiveBackupPath(now);
  1645. log("switch back to available primary link %s (select mode: always)", pathToStr(_paths[_abPathIdx].p).c_str());
  1646. }
  1647. }
  1648. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_BETTER) {
  1649. SharedPtr<Link> abLink = getLink(_paths[_abPathIdx].p);
  1650. if (abLink && ! abLink->primary()) {
  1651. // Active backup has switched to "better" primary link according to re-select policy.
  1652. SharedPtr<Link> abFailoverLink = getLink(_paths[_abFailoverQueue.front()].p);
  1653. if (_paths[_abFailoverQueue.front()].p && abFailoverLink && abFailoverLink->primary() && (_paths[_abFailoverQueue.front()].failoverScore > _paths[_abPathIdx].failoverScore)) {
  1654. dequeueNextActiveBackupPath(now);
  1655. log("switch back to user-defined primary link %s (select mode: better)", pathToStr(_paths[_abPathIdx].p).c_str());
  1656. }
  1657. }
  1658. }
  1659. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_OPTIMIZE && ! _abFailoverQueue.empty()) {
  1660. /**
  1661. * Implement link negotiation that was previously-decided
  1662. */
  1663. if (_paths[_abFailoverQueue.front()].negotiated) {
  1664. dequeueNextActiveBackupPath(now);
  1665. _lastPathNegotiationCheck = now;
  1666. log("switch negotiated link %s (select mode: optimize)", pathToStr(_paths[_abPathIdx].p).c_str());
  1667. }
  1668. else {
  1669. // Try to find a better path and automatically switch to it -- not too often, though.
  1670. if ((now - _lastActiveBackupPathChange) > ZT_BOND_OPTIMIZE_INTERVAL) {
  1671. if (! _abFailoverQueue.empty()) {
  1672. int newFScore = _paths[_abFailoverQueue.front()].failoverScore;
  1673. int prevFScore = _paths[_abPathIdx].failoverScore;
  1674. // Establish a minimum switch threshold to prevent flapping
  1675. int failoverScoreDifference = _paths[_abFailoverQueue.front()].failoverScore - _paths[_abPathIdx].failoverScore;
  1676. int thresholdQuantity = (int)(ZT_BOND_ACTIVE_BACKUP_OPTIMIZE_MIN_THRESHOLD * (float)_paths[_abPathIdx].relativeQuality);
  1677. if ((failoverScoreDifference > 0) && (failoverScoreDifference > thresholdQuantity)) {
  1678. SharedPtr<Path> oldPath = _paths[_abPathIdx].p;
  1679. dequeueNextActiveBackupPath(now);
  1680. 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);
  1681. }
  1682. }
  1683. }
  1684. }
  1685. }
  1686. }
  1687. void Bond::initTimers()
  1688. {
  1689. _lastFlowExpirationCheck = 0;
  1690. _lastFlowRebalance = 0;
  1691. _lastSentPathNegotiationRequest = 0;
  1692. _lastPathNegotiationCheck = 0;
  1693. _lastPathNegotiationReceived = 0;
  1694. _lastQoSRateCheck = 0;
  1695. _lastAckRateCheck = 0;
  1696. _lastQualityEstimation = 0;
  1697. _lastBondStatusLog = 0;
  1698. _lastSummaryDump = 0;
  1699. _lastActiveBackupPathChange = 0;
  1700. _lastFrame = 0;
  1701. _lastBackgroundTaskCheck = 0;
  1702. }
  1703. void Bond::setBondParameters(int policy, SharedPtr<Bond> templateBond, bool useTemplate)
  1704. {
  1705. // Sanity check for policy
  1706. _defaultPolicy = (_defaultPolicy <= ZT_BOND_POLICY_NONE || _defaultPolicy > ZT_BOND_POLICY_BALANCE_AWARE) ? ZT_BOND_POLICY_NONE : _defaultPolicy;
  1707. _policy = (policy <= ZT_BOND_POLICY_NONE || policy > ZT_BOND_POLICY_BALANCE_AWARE) ? _defaultPolicy : policy;
  1708. // Check if non-leaf to prevent spamming infrastructure
  1709. ZT_PeerRole role;
  1710. if (_peer) {
  1711. role = RR->topology->role(_peer->address());
  1712. }
  1713. _isLeaf = _peer ? (role != ZT_PEER_ROLE_PLANET && role != ZT_PEER_ROLE_MOON) : false;
  1714. // Path negotiation
  1715. _allowPathNegotiation = false;
  1716. _pathNegotiationCutoffCount = 0;
  1717. _localUtility = 0;
  1718. _negotiatedPathIdx = 0;
  1719. // User preferences which may override the default bonding algorithm's behavior
  1720. _userHasSpecifiedPrimaryLink = false;
  1721. _userHasSpecifiedFailoverInstructions = false;
  1722. _userHasSpecifiedLinkCapacities = 0;
  1723. // Bond status
  1724. _numAliveLinks = 0;
  1725. _numTotalLinks = 0;
  1726. _numBondedPaths = 0;
  1727. // General parameters
  1728. _downDelay = 0;
  1729. _upDelay = 0;
  1730. _monitorInterval = 0;
  1731. // balance-aware
  1732. _totalBondUnderload = 0;
  1733. _overheadBytes = 0;
  1734. /**
  1735. * Policy defaults
  1736. */
  1737. _abPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1738. _abLinkSelectMethod = ZT_BOND_RESELECTION_POLICY_OPTIMIZE;
  1739. _rrPacketsSentOnCurrLink = 0;
  1740. _rrIdx = 0;
  1741. _packetsPerLink = 64;
  1742. // Sane quality defaults
  1743. _qw[ZT_QOS_LAT_MAX_IDX] = 500.0f;
  1744. _qw[ZT_QOS_PDV_MAX_IDX] = 100.0f;
  1745. _qw[ZT_QOS_PLR_MAX_IDX] = 0.001f;
  1746. _qw[ZT_QOS_PER_MAX_IDX] = 0.0001f;
  1747. _qw[ZT_QOS_LAT_WEIGHT_IDX] = 0.25f;
  1748. _qw[ZT_QOS_PDV_WEIGHT_IDX] = 0.25f;
  1749. _qw[ZT_QOS_PLR_WEIGHT_IDX] = 0.25f;
  1750. _qw[ZT_QOS_PER_WEIGHT_IDX] = 0.25f;
  1751. _failoverInterval = ZT_BOND_FAILOVER_DEFAULT_INTERVAL;
  1752. /* If a user has specified custom parameters for this bonding policy, overlay them onto the defaults */
  1753. if (useTemplate) {
  1754. _policyAlias = templateBond->_policyAlias;
  1755. _policy = templateBond->policy();
  1756. _failoverInterval = templateBond->_failoverInterval >= ZT_BOND_FAILOVER_MIN_INTERVAL ? templateBond->_failoverInterval : ZT_BOND_FAILOVER_MIN_INTERVAL;
  1757. _downDelay = templateBond->_downDelay;
  1758. _upDelay = templateBond->_upDelay;
  1759. _abLinkSelectMethod = templateBond->_abLinkSelectMethod;
  1760. memcpy(_qw, templateBond->_qw, ZT_QOS_PARAMETER_SIZE * sizeof(float));
  1761. 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]);
  1762. }
  1763. if (! _isLeaf) {
  1764. _policy = ZT_BOND_POLICY_ACTIVE_BACKUP;
  1765. }
  1766. // Timer geometry
  1767. _monitorInterval = _failoverInterval / ZT_BOND_ECHOS_PER_FAILOVER_INTERVAL;
  1768. _qualityEstimationInterval = _failoverInterval * 2;
  1769. _qosSendInterval = _failoverInterval * 2;
  1770. _ackSendInterval = _failoverInterval * 2;
  1771. _qosCutoffCount = 0;
  1772. _ackCutoffCount = 0;
  1773. _defaultPathRefractoryPeriod = 8000;
  1774. }
  1775. void Bond::setUserLinkQualitySpec(float weights[], int len)
  1776. {
  1777. if (len != ZT_QOS_PARAMETER_SIZE) {
  1778. debug("link quality spec has an invalid number of parameters (%d out of %d), ignoring", len, ZT_QOS_PARAMETER_SIZE);
  1779. return;
  1780. }
  1781. float weightTotal = 0.0;
  1782. for (unsigned int i = 4; i < ZT_QOS_PARAMETER_SIZE; ++i) {
  1783. weightTotal += weights[i];
  1784. }
  1785. if (weightTotal > 0.99 && weightTotal < 1.01) {
  1786. memcpy(_qw, weights, len * sizeof(float));
  1787. }
  1788. }
  1789. SharedPtr<Link> Bond::getLink(const SharedPtr<Path>& path)
  1790. {
  1791. return ! path ? SharedPtr<Link>() : RR->bc->getLinkBySocket(_policyAlias, path->localSocket());
  1792. }
  1793. std::string Bond::pathToStr(const SharedPtr<Path>& path)
  1794. {
  1795. #ifdef ZT_TRACE
  1796. if (path) {
  1797. char pathStr[64] = { 0 };
  1798. char fullPathStr[384] = { 0 };
  1799. path->address().toString(pathStr);
  1800. SharedPtr<Link> link = getLink(path);
  1801. if (link) {
  1802. std::string ifnameStr = std::string(link->ifname());
  1803. snprintf(fullPathStr, 384, "%.16" PRIx64 "-%s/%s", path->localSocket(), ifnameStr.c_str(), pathStr);
  1804. return std::string(fullPathStr);
  1805. }
  1806. }
  1807. return "";
  1808. #else
  1809. return "";
  1810. #endif
  1811. }
  1812. void Bond::dumpPathStatus(int64_t now, int pathIdx)
  1813. {
  1814. #ifdef ZT_TRACE
  1815. std::string aliveOrDead = _paths[pathIdx].alive ? std::string("alive") : std::string("dead");
  1816. std::string eligibleOrNot = _paths[pathIdx].eligible ? std::string("eligible") : std::string("ineligible");
  1817. std::string bondedOrNot = _paths[pathIdx].bonded ? std::string("bonded") : std::string("unbonded");
  1818. 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",
  1819. pathIdx,
  1820. aliveOrDead.c_str(),
  1821. _paths[pathIdx].p->age(now),
  1822. _paths[pathIdx].p->_lastOut == 0 ? static_cast<int64_t>(0) : now - _paths[pathIdx].p->_lastOut,
  1823. eligibleOrNot.c_str(),
  1824. bondedOrNot.c_str(),
  1825. _paths[pathIdx].assignedFlowCount,
  1826. _paths[pathIdx].latency,
  1827. _paths[pathIdx].latencyVariance,
  1828. _paths[pathIdx].packetErrorRatio,
  1829. _paths[pathIdx].packetLossRatio,
  1830. _paths[pathIdx].relativeQuality,
  1831. pathToStr(_paths[pathIdx].p).c_str(),
  1832. _paths[pathIdx].isSpare());
  1833. #endif
  1834. }
  1835. void Bond::dumpInfo(int64_t now, bool force)
  1836. {
  1837. #ifdef ZT_TRACE
  1838. uint64_t timeSinceLastDump = now - _lastSummaryDump;
  1839. if (! force && timeSinceLastDump < ZT_BOND_STATUS_INTERVAL) {
  1840. return;
  1841. }
  1842. _lastSummaryDump = now;
  1843. float overhead = (_overheadBytes / (timeSinceLastDump / 1000.0f) / 1000.0f);
  1844. _overheadBytes = 0;
  1845. log("bond: bp=%d, fi=%" PRIu64 ", mi=%d, ud=%d, dd=%d, flows=%zu, leaf=%d, overhead=%f KB/s, links=(%d/%d)",
  1846. _policy,
  1847. _failoverInterval,
  1848. _monitorInterval,
  1849. _upDelay,
  1850. _downDelay,
  1851. _flows.size(),
  1852. _isLeaf,
  1853. overhead,
  1854. _numAliveLinks,
  1855. _numTotalLinks);
  1856. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1857. if (_paths[i].p) {
  1858. dumpPathStatus(now, i);
  1859. }
  1860. }
  1861. log("");
  1862. #endif
  1863. }
  1864. } // namespace ZeroTier