Bond.cpp 69 KB

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