Bond.cpp 59 KB

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