Bond.cpp 71 KB

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