Bond.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750
  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::createBond(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->debug("new default bond");
  89. }
  90. if (! _defaultPolicy && _defaultPolicyStr.length()) {
  91. bond = new Bond(renv, _bondPolicyTemplates[_defaultPolicyStr].ptr(), peer);
  92. bond->debug("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->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());
  99. }
  100. else {
  101. bond = new Bond(renv, _bondPolicyTemplates[_policyTemplateAssignments[identity]].ptr(), peer);
  102. bond->debug("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. void Bond::destroyBond(uint64_t peerId)
  134. {
  135. Mutex::Lock _l(_bonds_m);
  136. _bonds.erase(peerId);
  137. }
  138. SharedPtr<Link> Bond::getLinkBySocket(const std::string& policyAlias, uint64_t localSocket)
  139. {
  140. Mutex::Lock _l(_links_m);
  141. char ifname[64] = { 0 };
  142. _phy->getIfName((PhySocket*)((uintptr_t)localSocket), ifname, sizeof(ifname) - 1);
  143. std::string ifnameStr(ifname);
  144. auto search = _interfaceToLinkMap[policyAlias].find(ifnameStr);
  145. if (search == _interfaceToLinkMap[policyAlias].end()) {
  146. // If the link wasn't already known, add a new entry
  147. SharedPtr<Link> s = new Link(ifnameStr, 0, 0, true, ZT_BOND_SLAVE_MODE_SPARE, "", 0.0);
  148. _interfaceToLinkMap[policyAlias].insert(std::pair<std::string, SharedPtr<Link> >(ifnameStr, s));
  149. return s;
  150. }
  151. else {
  152. return search->second;
  153. }
  154. }
  155. SharedPtr<Link> Bond::getLinkByName(const std::string& policyAlias, const std::string& ifname)
  156. {
  157. Mutex::Lock _l(_links_m);
  158. auto search = _interfaceToLinkMap[policyAlias].find(ifname);
  159. if (search != _interfaceToLinkMap[policyAlias].end()) {
  160. return search->second;
  161. }
  162. return SharedPtr<Link>();
  163. }
  164. void Bond::processBackgroundTasks(void* tPtr, const int64_t now)
  165. {
  166. unsigned long _currMinReqMonitorInterval = ZT_BOND_FAILOVER_DEFAULT_INTERVAL;
  167. Mutex::Lock _l(_bonds_m);
  168. std::map<int64_t, SharedPtr<Bond> >::iterator bondItr = _bonds.begin();
  169. while (bondItr != _bonds.end()) {
  170. // Update Bond Controller's background processing timer
  171. _currMinReqMonitorInterval = std::min(_currMinReqMonitorInterval, (unsigned long)(bondItr->second->monitorInterval()));
  172. bondItr->second->processBackgroundBondTasks(tPtr, now);
  173. ++bondItr;
  174. }
  175. _minReqMonitorInterval = std::min(_currMinReqMonitorInterval, (unsigned long)ZT_BOND_FAILOVER_DEFAULT_INTERVAL);
  176. }
  177. Bond::Bond(const RuntimeEnvironment* renv) : RR(renv)
  178. {
  179. initTimers();
  180. }
  181. 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())
  182. {
  183. initTimers();
  184. setBondParameters(policy, SharedPtr<Bond>(), false);
  185. _policyAlias = getPolicyStrByCode(policy);
  186. }
  187. Bond::Bond(const RuntimeEnvironment* renv, std::string& basePolicy, std::string& policyAlias, const SharedPtr<Peer>& peer) : RR(renv), _policyAlias(policyAlias), _peer(peer)
  188. {
  189. initTimers();
  190. setBondParameters(getPolicyCodeByStr(basePolicy), SharedPtr<Bond>(), false);
  191. }
  192. Bond::Bond(const RuntimeEnvironment* renv, SharedPtr<Bond> originalBond, const SharedPtr<Peer>& peer)
  193. : RR(renv)
  194. , _freeRandomByte((unsigned char)((uintptr_t)this >> 4) ^ ++s_freeRandomByteCounter)
  195. , _peer(peer)
  196. , _peerId(_peer->_id.address().toInt())
  197. {
  198. initTimers();
  199. setBondParameters(originalBond->_policy, originalBond, true);
  200. }
  201. void Bond::nominatePathToBond(const SharedPtr<Path>& path, int64_t now)
  202. {
  203. Mutex::Lock _l(_paths_m);
  204. /**
  205. * Ensure the link is allowed and the path is not already present
  206. */
  207. if (! RR->bc->linkAllowed(_policyAlias, getLink(path))) {
  208. return;
  209. }
  210. bool alreadyPresent = false;
  211. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  212. // Sanity check
  213. if (path.ptr() == _paths[i].p.ptr()) {
  214. alreadyPresent = true;
  215. break;
  216. }
  217. }
  218. if (! alreadyPresent) {
  219. /**
  220. * Find somewhere to stick it
  221. */
  222. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  223. if (! _paths[i].p) {
  224. _paths[i].set(now, path);
  225. /**
  226. * Set user preferences and update state variables of other paths on the same link
  227. */
  228. SharedPtr<Link> sl = getLink(_paths[i].p);
  229. if (sl) {
  230. // Determine if there are any other paths on this link
  231. bool bFoundCommonLink = false;
  232. SharedPtr<Link> commonLink = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  233. for (unsigned int j = 0; j < ZT_MAX_PEER_NETWORK_PATHS; ++j) {
  234. if (_paths[j].p && _paths[j].p.ptr() != _paths[i].p.ptr()) {
  235. if (RR->bc->getLinkBySocket(_policyAlias, _paths[j].p->localSocket()) == commonLink) {
  236. bFoundCommonLink = true;
  237. _paths[j].onlyPathOnLink = false;
  238. }
  239. }
  240. }
  241. _paths[i].ipvPref = sl->ipvPref();
  242. _paths[i].mode = sl->mode();
  243. _paths[i].enabled = sl->enabled();
  244. _paths[i].onlyPathOnLink = ! bFoundCommonLink;
  245. }
  246. log("nominate link %s", pathToStr(path).c_str());
  247. break;
  248. }
  249. }
  250. }
  251. curateBond(now, true);
  252. estimatePathQuality(now);
  253. }
  254. void Bond::addPathToBond(int nominatedIdx, int bondedIdx)
  255. {
  256. // Map bonded set to nominated set
  257. _bondIdxMap[bondedIdx] = nominatedIdx;
  258. // Tell the bonding layer that we can now use this bond for traffic
  259. _paths[nominatedIdx].bonded = true;
  260. }
  261. SharedPtr<Path> Bond::getAppropriatePath(int64_t now, int32_t flowId)
  262. {
  263. Mutex::Lock _l(_paths_m);
  264. /**
  265. * active-backup
  266. */
  267. if (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP) {
  268. if (_abPathIdx != ZT_MAX_PEER_NETWORK_PATHS && _paths[_abPathIdx].p) {
  269. return _paths[_abPathIdx].p;
  270. }
  271. }
  272. /**
  273. * broadcast
  274. */
  275. if (_policy == ZT_BOND_POLICY_BROADCAST) {
  276. return SharedPtr<Path>(); // Handled in Switch::_trySend()
  277. }
  278. if (! _numBondedPaths) {
  279. return SharedPtr<Path>(); // No paths assigned to bond yet, cannot balance traffic
  280. }
  281. /**
  282. * balance-rr
  283. */
  284. if (_policy == ZT_BOND_POLICY_BALANCE_RR) {
  285. if (! _allowFlowHashing) {
  286. if (_packetsPerLink == 0) {
  287. // Randomly select a path
  288. return _paths[_bondIdxMap[_freeRandomByte % _numBondedPaths]].p;
  289. }
  290. if (_rrPacketsSentOnCurrLink < _packetsPerLink) {
  291. // Continue to use this link
  292. ++_rrPacketsSentOnCurrLink;
  293. return _paths[_bondIdxMap[_rrIdx]].p;
  294. }
  295. // Reset striping counter
  296. _rrPacketsSentOnCurrLink = 0;
  297. if (_numBondedPaths == 1 || _rrIdx >= (ZT_MAX_PEER_NETWORK_PATHS-1)) {
  298. _rrIdx = 0;
  299. }
  300. else {
  301. int _tempIdx = _rrIdx;
  302. for (int searchCount = 0; searchCount < (_numBondedPaths - 1); searchCount++) {
  303. _tempIdx = (_tempIdx == (_numBondedPaths - 1)) ? 0 : _tempIdx + 1;
  304. if (_bondIdxMap[_tempIdx] != ZT_MAX_PEER_NETWORK_PATHS) {
  305. if (_paths[_bondIdxMap[_tempIdx]].p && _paths[_bondIdxMap[_tempIdx]].eligible) {
  306. _rrIdx = _tempIdx;
  307. break;
  308. }
  309. }
  310. }
  311. }
  312. if (_paths[_bondIdxMap[_rrIdx]].p) {
  313. return _paths[_bondIdxMap[_rrIdx]].p;
  314. }
  315. }
  316. }
  317. /**
  318. * balance-xor
  319. */
  320. if (_policy == ZT_BOND_POLICY_BALANCE_XOR || _policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  321. if (! _allowFlowHashing || flowId == -1) {
  322. // No specific path required for unclassified traffic, send on anything
  323. int m_idx = _bondIdxMap[_freeRandomByte % _numBondedPaths];
  324. return _paths[m_idx].p;
  325. }
  326. else if (_allowFlowHashing) {
  327. Mutex::Lock _l(_flows_m);
  328. SharedPtr<Flow> flow;
  329. if (_flows.count(flowId)) {
  330. flow = _flows[flowId];
  331. flow->lastActivity = now;
  332. }
  333. else {
  334. unsigned char entropy;
  335. Utils::getSecureRandom(&entropy, 1);
  336. flow = createFlow(ZT_MAX_PEER_NETWORK_PATHS, flowId, entropy, now);
  337. }
  338. if (flow) {
  339. return _paths[flow->assignedPath].p;
  340. }
  341. }
  342. }
  343. return SharedPtr<Path>();
  344. }
  345. void Bond::recordIncomingInvalidPacket(const SharedPtr<Path>& path)
  346. {
  347. Mutex::Lock _l(_paths_m);
  348. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  349. if (_paths[i].p == path) {
  350. _paths[i].packetValiditySamples.push(false);
  351. }
  352. }
  353. }
  354. void Bond::recordOutgoingPacket(const SharedPtr<Path>& path, uint64_t packetId, uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  355. {
  356. _freeRandomByte += (unsigned char)(packetId >> 8); // Grab entropy to use in path selection logic
  357. bool isFrame = (verb == Packet::Packet::VERB_ECHO || verb == Packet::VERB_FRAME || verb == Packet::VERB_EXT_FRAME);
  358. bool shouldRecord = (packetId & (ZT_QOS_ACK_DIVISOR - 1) && (verb != Packet::VERB_ACK) && (verb != Packet::VERB_QOS_MEASUREMENT));
  359. if (isFrame || shouldRecord) {
  360. Mutex::Lock _l(_paths_m);
  361. int pathIdx = getNominatedPathIdx(path);
  362. if (pathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  363. return;
  364. }
  365. if (isFrame) {
  366. ++(_paths[pathIdx].packetsOut);
  367. _lastFrame = now;
  368. }
  369. if (shouldRecord) {
  370. //_paths[pathIdx].unackedBytes += payloadLength;
  371. // Take note that we're expecting a VERB_ACK on this path as of a specific time
  372. if (_paths[pathIdx].qosStatsOut.size() < ZT_QOS_MAX_OUTSTANDING_RECORDS) {
  373. _paths[pathIdx].qosStatsOut[packetId] = now;
  374. }
  375. }
  376. }
  377. if (_allowFlowHashing && (flowId != ZT_QOS_NO_FLOW)) {
  378. Mutex::Lock _l(_flows_m);
  379. if (_flows.count(flowId)) {
  380. _flows[flowId]->bytesOut += payloadLength;
  381. }
  382. }
  383. }
  384. void Bond::recordIncomingPacket(const SharedPtr<Path>& path, uint64_t packetId, uint16_t payloadLength, Packet::Verb verb, int32_t flowId, int64_t now)
  385. {
  386. bool isFrame = (verb == Packet::Packet::VERB_ECHO || verb == Packet::VERB_FRAME || verb == Packet::VERB_EXT_FRAME);
  387. bool shouldRecord = (packetId & (ZT_QOS_ACK_DIVISOR - 1) && (verb != Packet::VERB_ACK) && (verb != Packet::VERB_QOS_MEASUREMENT));
  388. Mutex::Lock _l(_paths_m);
  389. int pathIdx = getNominatedPathIdx(path);
  390. if (pathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  391. return;
  392. }
  393. // Take note of the time that this previously-dead path received a packet
  394. if (! _paths[pathIdx].alive) {
  395. _paths[pathIdx].lastAliveToggle = now;
  396. }
  397. if (isFrame || shouldRecord) {
  398. if (_paths[pathIdx].allowed()) {
  399. if (isFrame) {
  400. ++(_paths[pathIdx].packetsIn);
  401. _lastFrame = now;
  402. }
  403. if (shouldRecord) {
  404. _paths[pathIdx].qosStatsIn[packetId] = now;
  405. ++(_paths[pathIdx].packetsReceivedSinceLastQoS);
  406. _paths[pathIdx].packetValiditySamples.push(true);
  407. }
  408. }
  409. }
  410. /**
  411. * Learn new flows and pro-actively create entries for them in the bond so
  412. * that the next time we send a packet out that is part of a flow we know
  413. * which path to use.
  414. */
  415. if ((flowId != ZT_QOS_NO_FLOW) && (_policy == ZT_BOND_POLICY_BALANCE_RR || _policy == ZT_BOND_POLICY_BALANCE_XOR || _policy == ZT_BOND_POLICY_BALANCE_AWARE)) {
  416. Mutex::Lock _l(_flows_m);
  417. SharedPtr<Flow> flow;
  418. if (! _flows.count(flowId)) {
  419. flow = createFlow(pathIdx, flowId, 0, now);
  420. }
  421. else {
  422. flow = _flows[flowId];
  423. }
  424. if (flow) {
  425. flow->bytesIn += payloadLength;
  426. }
  427. }
  428. }
  429. void Bond::receivedQoS(const SharedPtr<Path>& path, int64_t now, int count, uint64_t* rx_id, uint16_t* rx_ts)
  430. {
  431. Mutex::Lock _l(_paths_m);
  432. int pathIdx = getNominatedPathIdx(path);
  433. if (pathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  434. return;
  435. }
  436. // debug("received QoS packet (sampling %d frames) via %s", count, pathToStr(path).c_str());
  437. // Look up egress times and compute latency values for each record
  438. std::map<uint64_t, uint64_t>::iterator it;
  439. for (int j = 0; j < count; j++) {
  440. it = _paths[pathIdx].qosStatsOut.find(rx_id[j]);
  441. if (it != _paths[pathIdx].qosStatsOut.end()) {
  442. _paths[pathIdx].latencySamples.push(((uint16_t)(now - it->second) - rx_ts[j]) / 2);
  443. _paths[pathIdx].qosStatsOut.erase(it);
  444. }
  445. }
  446. _paths[pathIdx].qosRecordSize.push(count);
  447. }
  448. int32_t Bond::generateQoSPacket(int pathIdx, int64_t now, char* qosBuffer)
  449. {
  450. int32_t len = 0;
  451. std::map<uint64_t, uint64_t>::iterator it = _paths[pathIdx].qosStatsIn.begin();
  452. int i = 0;
  453. int numRecords = std::min(_paths[pathIdx].packetsReceivedSinceLastQoS, ZT_QOS_TABLE_SIZE);
  454. while (i < numRecords && it != _paths[pathIdx].qosStatsIn.end()) {
  455. uint64_t id = it->first;
  456. memcpy(qosBuffer, &id, sizeof(uint64_t));
  457. qosBuffer += sizeof(uint64_t);
  458. uint16_t holdingTime = (uint16_t)(now - it->second);
  459. memcpy(qosBuffer, &holdingTime, sizeof(uint16_t));
  460. qosBuffer += sizeof(uint16_t);
  461. len += sizeof(uint64_t) + sizeof(uint16_t);
  462. _paths[pathIdx].qosStatsIn.erase(it++);
  463. ++i;
  464. }
  465. return len;
  466. }
  467. bool Bond::assignFlowToBondedPath(SharedPtr<Flow>& flow, int64_t now)
  468. {
  469. if (! _numBondedPaths) {
  470. debug("unable to assign flow %x (bond has no links)\n", flow->id);
  471. return false;
  472. }
  473. unsigned int idx = ZT_MAX_PEER_NETWORK_PATHS;
  474. if (_policy == ZT_BOND_POLICY_BALANCE_XOR) {
  475. idx = abs((int)(flow->id % (_numBondedPaths)));
  476. flow->assignPath(_bondIdxMap[idx], now);
  477. ++(_paths[_bondIdxMap[idx]].assignedFlowCount);
  478. }
  479. if (_policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  480. unsigned char entropy;
  481. Utils::getSecureRandom(&entropy, 1);
  482. if (_totalBondUnderload) {
  483. entropy %= _totalBondUnderload;
  484. }
  485. /* Since there may be scenarios where a path is removed before we can re-estimate
  486. relative qualities (and thus allocations) we need to down-modulate the entropy
  487. value that we use to randomly assign among the surviving paths, otherwise we risk
  488. not being able to find a path to assign this flow to. */
  489. int totalIncompleteAllocation = 0;
  490. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  491. if (_paths[i].p && _paths[i].bonded) {
  492. totalIncompleteAllocation += _paths[i].allocation;
  493. }
  494. }
  495. entropy %= totalIncompleteAllocation;
  496. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  497. if (_paths[i].p && _paths[i].bonded) {
  498. uint8_t probabilitySegment = (_totalBondUnderload > 0) ? _paths[i].affinity : _paths[i].allocation;
  499. if (entropy <= probabilitySegment) {
  500. idx = i;
  501. break;
  502. }
  503. entropy -= probabilitySegment;
  504. }
  505. }
  506. if (idx < ZT_MAX_PEER_NETWORK_PATHS) {
  507. flow->assignPath(idx, now);
  508. ++(_paths[idx].assignedFlowCount);
  509. }
  510. else {
  511. debug("unable to assign out-flow %x (unknown reason)", flow->id);
  512. return false;
  513. }
  514. }
  515. if (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP) {
  516. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  517. debug("unable to assign out-flow %x (no active backup link)", flow->id);
  518. }
  519. flow->assignPath(_abPathIdx, now);
  520. }
  521. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[flow->assignedPath].p->localSocket());
  522. debug("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());
  523. return true;
  524. }
  525. SharedPtr<Bond::Flow> Bond::createFlow(int pathIdx, int32_t flowId, unsigned char entropy, int64_t now)
  526. {
  527. if (! _numBondedPaths) {
  528. debug("unable to assign flow %x (bond has no links)\n", flowId);
  529. return SharedPtr<Flow>();
  530. }
  531. if (_flows.size() >= ZT_FLOW_MAX_COUNT) {
  532. debug("forget oldest flow (max flows reached: %d)\n", ZT_FLOW_MAX_COUNT);
  533. forgetFlowsWhenNecessary(0, true, now);
  534. }
  535. SharedPtr<Flow> flow = new Flow(flowId, now);
  536. _flows[flowId] = flow;
  537. /**
  538. * Add a flow with a given Path already provided. This is the case when a packet
  539. * is received on a path but no flow exists, in this case we simply assign the path
  540. * that the remote peer chose for us.
  541. */
  542. if (pathIdx != ZT_MAX_PEER_NETWORK_PATHS) {
  543. flow->assignPath(pathIdx, now);
  544. _paths[pathIdx].assignedFlowCount++;
  545. debug("assign in-flow %x to link %s (%lu / %lu)", flow->id, pathToStr(_paths[pathIdx].p).c_str(), _paths[pathIdx].assignedFlowCount, (unsigned long)_flows.size());
  546. }
  547. /**
  548. * Add a flow when no path was provided. This means that it is an outgoing packet
  549. * and that it is up to the local peer to decide how to load-balance its transmission.
  550. */
  551. else {
  552. assignFlowToBondedPath(flow, now);
  553. }
  554. return flow;
  555. }
  556. void Bond::forgetFlowsWhenNecessary(uint64_t age, bool oldest, int64_t now)
  557. {
  558. std::map<int32_t, SharedPtr<Flow> >::iterator it = _flows.begin();
  559. std::map<int32_t, SharedPtr<Flow> >::iterator oldestFlow = _flows.end();
  560. SharedPtr<Flow> expiredFlow;
  561. if (age) { // Remove by specific age
  562. while (it != _flows.end()) {
  563. if (it->second->age(now) > age) {
  564. debug("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));
  565. _paths[it->second->assignedPath].assignedFlowCount--;
  566. it = _flows.erase(it);
  567. }
  568. else {
  569. ++it;
  570. }
  571. }
  572. }
  573. else if (oldest) { // Remove single oldest by natural expiration
  574. uint64_t maxAge = 0;
  575. while (it != _flows.end()) {
  576. if (it->second->age(now) > maxAge) {
  577. maxAge = (now - it->second->age(now));
  578. oldestFlow = it;
  579. }
  580. ++it;
  581. }
  582. if (oldestFlow != _flows.end()) {
  583. debug("forget oldest flow %x (age %llu) (total flows: %lu)", oldestFlow->first, (unsigned long long)oldestFlow->second->age(now), (unsigned long)(_flows.size() - 1));
  584. _paths[oldestFlow->second->assignedPath].assignedFlowCount--;
  585. _flows.erase(oldestFlow);
  586. }
  587. }
  588. }
  589. void Bond::processIncomingPathNegotiationRequest(uint64_t now, SharedPtr<Path>& path, int16_t remoteUtility)
  590. {
  591. char pathStr[64] = { 0 };
  592. if (_abLinkSelectMethod != ZT_BOND_RESELECTION_POLICY_OPTIMIZE) {
  593. return;
  594. }
  595. Mutex::Lock _l(_paths_m);
  596. int pathIdx = getNominatedPathIdx(path);
  597. if (pathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  598. return;
  599. }
  600. _paths[pathIdx].p->address().toString(pathStr);
  601. if (! _lastPathNegotiationCheck) {
  602. return;
  603. }
  604. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[pathIdx].p->localSocket());
  605. if (remoteUtility > _localUtility) {
  606. _paths[pathIdx].p->address().toString(pathStr);
  607. 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);
  608. _negotiatedPathIdx = pathIdx;
  609. }
  610. if (remoteUtility < _localUtility) {
  611. 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);
  612. }
  613. if (remoteUtility == _localUtility) {
  614. debug("peer suggests alternate link %s/%s, remote utility (%d) equal to local utility (%d)\n", link->ifname().c_str(), pathStr, remoteUtility, _localUtility);
  615. if (_peer->_id.address().toInt() > RR->node->identity().address().toInt()) {
  616. debug("agree with peer to use alternate link %s/%s\n", link->ifname().c_str(), pathStr);
  617. _negotiatedPathIdx = pathIdx;
  618. }
  619. else {
  620. debug("ignore petition from peer to use alternate link %s/%s\n", link->ifname().c_str(), pathStr);
  621. }
  622. }
  623. }
  624. void Bond::pathNegotiationCheck(void* tPtr, int64_t now)
  625. {
  626. int maxInPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  627. int maxOutPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  628. uint64_t maxInCount = 0;
  629. uint64_t maxOutCount = 0;
  630. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  631. if (! _paths[i].p) {
  632. continue;
  633. }
  634. if (_paths[i].packetsIn > maxInCount) {
  635. maxInCount = _paths[i].packetsIn;
  636. maxInPathIdx = i;
  637. }
  638. if (_paths[i].packetsOut > maxOutCount) {
  639. maxOutCount = _paths[i].packetsOut;
  640. maxOutPathIdx = i;
  641. }
  642. _paths[i].resetPacketCounts();
  643. }
  644. bool _peerLinksSynchronized = ((maxInPathIdx != ZT_MAX_PEER_NETWORK_PATHS) && (maxOutPathIdx != ZT_MAX_PEER_NETWORK_PATHS) && (maxInPathIdx != maxOutPathIdx)) ? false : true;
  645. /**
  646. * Determine utility and attempt to petition remote peer to switch to our chosen path
  647. */
  648. if (! _peerLinksSynchronized) {
  649. _localUtility = _paths[maxOutPathIdx].failoverScore - _paths[maxInPathIdx].failoverScore;
  650. if (_paths[maxOutPathIdx].negotiated) {
  651. _localUtility -= ZT_BOND_FAILOVER_HANDICAP_NEGOTIATED;
  652. }
  653. if ((now - _lastSentPathNegotiationRequest) > ZT_PATH_NEGOTIATION_CUTOFF_TIME) {
  654. // fprintf(stderr, "BT: (sync) it's been long enough, sending more requests.\n");
  655. _numSentPathNegotiationRequests = 0;
  656. }
  657. if (_numSentPathNegotiationRequests < ZT_PATH_NEGOTIATION_TRY_COUNT) {
  658. if (_localUtility >= 0) {
  659. // fprintf(stderr, "BT: (sync) paths appear to be out of sync (utility=%d)\n", _localUtility);
  660. sendPATH_NEGOTIATION_REQUEST(tPtr, _paths[maxOutPathIdx].p);
  661. ++_numSentPathNegotiationRequests;
  662. _lastSentPathNegotiationRequest = now;
  663. // fprintf(stderr, "sending request to use %s on %s, ls=%llx, utility=%d\n", pathStr, link->ifname().c_str(), _paths[maxOutPathIdx].p->localSocket(), _localUtility);
  664. }
  665. }
  666. /**
  667. * Give up negotiating and consider switching
  668. */
  669. else if ((now - _lastSentPathNegotiationRequest) > (2 * ZT_BOND_OPTIMIZE_INTERVAL)) {
  670. if (_localUtility == 0) {
  671. // There's no loss to us, just switch without sending a another request
  672. // fprintf(stderr, "BT: (sync) giving up, switching to remote peer's path.\n");
  673. _negotiatedPathIdx = maxInPathIdx;
  674. }
  675. }
  676. }
  677. }
  678. void Bond::sendPATH_NEGOTIATION_REQUEST(void* tPtr, int pathIdx)
  679. {
  680. debug("send link negotiation request to peer via link %s, local utility is %d", pathToStr(_paths[pathIdx].p).c_str(), _localUtility);
  681. if (_abLinkSelectMethod != ZT_BOND_RESELECTION_POLICY_OPTIMIZE) {
  682. return;
  683. }
  684. Packet outp(_peer->_id.address(), RR->identity.address(), Packet::VERB_PATH_NEGOTIATION_REQUEST);
  685. outp.append<int16_t>(_localUtility);
  686. if (_paths[pathIdx].p->address()) {
  687. outp.armor(_peer->key(), false, _peer->aesKeysIfSupported());
  688. RR->node->putPacket(tPtr, _paths[pathIdx].p->localSocket(), _paths[pathIdx].p->address(), outp.data(), outp.size());
  689. _overheadBytes += outp.size();
  690. }
  691. }
  692. void Bond::sendQOS_MEASUREMENT(void* tPtr, int pathIdx, int64_t localSocket, const InetAddress& atAddress, int64_t now)
  693. {
  694. int64_t _now = RR->node->now();
  695. Packet outp(_peer->_id.address(), RR->identity.address(), Packet::VERB_QOS_MEASUREMENT);
  696. char qosData[ZT_QOS_MAX_PACKET_SIZE];
  697. int16_t len = generateQoSPacket(pathIdx, _now, qosData);
  698. if (len) {
  699. outp.append(qosData, len);
  700. if (atAddress) {
  701. outp.armor(_peer->key(), false, _peer->aesKeysIfSupported());
  702. RR->node->putPacket(tPtr, localSocket, atAddress, outp.data(), outp.size());
  703. }
  704. else {
  705. RR->sw->send(tPtr, outp, false);
  706. }
  707. _paths[pathIdx].packetsReceivedSinceLastQoS = 0;
  708. _paths[pathIdx].lastQoSMeasurement = now;
  709. _overheadBytes += outp.size();
  710. }
  711. // debug("send QOS via link %s (len=%d)", pathToStr(_paths[pathIdx].p).c_str(), len);
  712. }
  713. void Bond::processBackgroundBondTasks(void* tPtr, int64_t now)
  714. {
  715. if (! _peer->_localMultipathSupported || (now - _lastBackgroundTaskCheck) < ZT_BOND_BACKGROUND_TASK_MIN_INTERVAL) {
  716. return;
  717. }
  718. _lastBackgroundTaskCheck = now;
  719. Mutex::Lock _l(_paths_m);
  720. curateBond(now, false);
  721. if ((now - _lastQualityEstimation) > _qualityEstimationInterval) {
  722. _lastQualityEstimation = now;
  723. estimatePathQuality(now);
  724. }
  725. dumpInfo(now, false);
  726. // Send ambient monitoring traffic
  727. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  728. if (_paths[i].p && _paths[i].allowed()) {
  729. if (_isLeaf) {
  730. if ((_monitorInterval > 0) && (((now - _paths[i].p->_lastIn) >= (_paths[i].alive ? _monitorInterval : _failoverInterval)))) {
  731. if ((_peer->remoteVersionProtocol() >= 5) && (! ((_peer->remoteVersionMajor() == 1) && (_peer->remoteVersionMinor() == 1) && (_peer->remoteVersionRevision() == 0)))) {
  732. Packet outp(_peer->address(), RR->identity.address(), Packet::VERB_ECHO); // ECHO (this is our bond's heartbeat)
  733. outp.armor(_peer->key(), true, _peer->aesKeysIfSupported());
  734. RR->node->expectReplyTo(outp.packetId());
  735. RR->node->putPacket(tPtr, _paths[i].p->localSocket(), _paths[i].p->address(), outp.data(), outp.size());
  736. _paths[i].p->_lastOut = now;
  737. _overheadBytes += outp.size();
  738. debug("tx: verb 0x%-2x of len %4d via %s (ECHO)", Packet::VERB_ECHO, outp.size(), pathToStr(_paths[i].p).c_str());
  739. }
  740. }
  741. // QOS
  742. if (_paths[i].needsToSendQoS(now, _qosSendInterval)) {
  743. sendQOS_MEASUREMENT(tPtr, i, _paths[i].p->localSocket(), _paths[i].p->address(), now);
  744. }
  745. }
  746. }
  747. }
  748. // Perform periodic background tasks unique to each bonding policy
  749. switch (_policy) {
  750. case ZT_BOND_POLICY_ACTIVE_BACKUP:
  751. processActiveBackupTasks(tPtr, now);
  752. break;
  753. case ZT_BOND_POLICY_BROADCAST:
  754. break;
  755. case ZT_BOND_POLICY_BALANCE_RR:
  756. case ZT_BOND_POLICY_BALANCE_XOR:
  757. case ZT_BOND_POLICY_BALANCE_AWARE:
  758. processBalanceTasks(now);
  759. break;
  760. default:
  761. break;
  762. }
  763. // Check whether or not a path negotiation needs to be performed
  764. if (((now - _lastPathNegotiationCheck) > ZT_BOND_OPTIMIZE_INTERVAL) && _allowPathNegotiation) {
  765. _lastPathNegotiationCheck = now;
  766. pathNegotiationCheck(tPtr, now);
  767. }
  768. }
  769. void Bond::curateBond(int64_t now, bool rebuildBond)
  770. {
  771. uint8_t tmpNumAliveLinks = 0;
  772. uint8_t tmpNumTotalLinks = 0;
  773. /**
  774. * Update path state variables. State variables are used so that critical
  775. * blocks that perform fast packet processing won't need to make as many
  776. * function calls or computations.
  777. */
  778. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  779. if (! _paths[i].p) {
  780. continue;
  781. }
  782. /**
  783. * Remove expired links from bond
  784. */
  785. if ((now - _paths[i].p->_lastIn) > (ZT_PEER_EXPIRED_PATH_TRIAL_PERIOD)) {
  786. log("link %s has expired, removing from bond", pathToStr(_paths[i].p).c_str());
  787. _paths[i] = NominatedPath();
  788. _paths[i].p = SharedPtr<Path>();
  789. continue;
  790. }
  791. tmpNumTotalLinks++;
  792. if (_paths[i].eligible) {
  793. tmpNumAliveLinks++;
  794. }
  795. /**
  796. * Determine aliveness
  797. */
  798. _paths[i].alive = _isLeaf ? (now - _paths[i].p->_lastIn) < _failoverInterval : (now - _paths[i].p->_lastIn) < ZT_PEER_PATH_EXPIRATION;
  799. /**
  800. * Determine current eligibility
  801. */
  802. bool currEligibility = false;
  803. // Simple RX age (driven by packets of any type and gratuitous VERB_HELLOs)
  804. bool acceptableAge = _isLeaf ? (_paths[i].p->age(now) < (_failoverInterval + _downDelay)) : _paths[i].alive;
  805. // Whether we've waited long enough since the link last came online
  806. bool satisfiedUpDelay = (now - _paths[i].lastAliveToggle) >= _upDelay;
  807. // Whether this path is still in its trial period
  808. bool inTrial = (now - _paths[i].whenNominated) < ZT_BOND_OPTIMIZE_INTERVAL;
  809. // if (includeRefractoryPeriod && _paths[i].refractoryPeriod) {
  810. // As long as the refractory period value has not fully drained this path is not eligible
  811. // currEligibility = false;
  812. //}
  813. currEligibility = _paths[i].allowed() && ((acceptableAge && satisfiedUpDelay) || inTrial);
  814. // debug("[%d] allowed=%d, acceptableAge=%d, satisfiedUpDelay=%d, inTrial=%d ==== %d", i, _paths[i].allowed(), acceptableAge, satisfiedUpDelay, inTrial, currEligibility);
  815. /**
  816. * Note eligibility state change (if any) and take appropriate action
  817. */
  818. if (currEligibility != _paths[i].eligible) {
  819. if (currEligibility == 0) {
  820. log("link %s is no longer eligible", pathToStr(_paths[i].p).c_str());
  821. }
  822. if (currEligibility == 1) {
  823. log("link %s is eligible", pathToStr(_paths[i].p).c_str());
  824. }
  825. dumpPathStatus(now, i);
  826. if (currEligibility) {
  827. rebuildBond = true;
  828. }
  829. if (! currEligibility) {
  830. _paths[i].adjustRefractoryPeriod(now, _defaultPathRefractoryPeriod, ! currEligibility);
  831. if (_paths[i].bonded) {
  832. if (_allowFlowHashing) {
  833. debug("link %s was bonded, flow reallocation will occur soon", pathToStr(_paths[i].p).c_str());
  834. rebuildBond = true;
  835. _paths[i].shouldReallocateFlows = _paths[i].bonded;
  836. }
  837. _paths[i].bonded = false;
  838. }
  839. }
  840. }
  841. if (currEligibility) {
  842. _paths[i].adjustRefractoryPeriod(now, _defaultPathRefractoryPeriod, false);
  843. }
  844. _paths[i].eligible = currEligibility;
  845. }
  846. /**
  847. * Trigger status report if number of links change
  848. */
  849. _numAliveLinks = tmpNumAliveLinks;
  850. _numTotalLinks = tmpNumTotalLinks;
  851. if ((_numAliveLinks != tmpNumAliveLinks) || (_numTotalLinks != tmpNumTotalLinks)) {
  852. dumpInfo(now, true);
  853. }
  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. debug("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. debug("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. debug("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. debug("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. debug("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. debug("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. debug("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. if (_paths[i].p && _paths[i].allowed()) {
  954. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  955. totUserSpecifiedLinkSpeed += link->speed();
  956. }
  957. }
  958. for (unsigned int i = 0; i < _numBondedPaths; ++i) {
  959. if (_paths[i].p && _paths[i].allowed()) {
  960. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  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. if (_abPathIdx != ZT_MAX_PEER_NETWORK_PATHS && !_paths[_abPathIdx].p) {
  1145. _abPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1146. log("main active-backup path has been removed");
  1147. }
  1148. /**
  1149. * Generate periodic status report
  1150. */
  1151. if ((now - _lastBondStatusLog) > ZT_BOND_STATUS_INTERVAL) {
  1152. _lastBondStatusLog = now;
  1153. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1154. log("no active link");
  1155. }
  1156. else if (_paths[_abPathIdx].p) {
  1157. log("active link is %s, failover queue size is %zu", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
  1158. }
  1159. if (_abFailoverQueue.empty()) {
  1160. log("failover queue is empty, bond is no longer fault-tolerant");
  1161. }
  1162. }
  1163. /**
  1164. * Select initial "active" active-backup link
  1165. */
  1166. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1167. /**
  1168. * [Automatic mode]
  1169. * The user has not explicitly specified links or their failover schedule,
  1170. * the bonding policy will now select the first eligible path and set it as
  1171. * its active backup path, if a substantially better path is detected the bonding
  1172. * policy will assign it as the new active backup path. If the path fails it will
  1173. * simply find the next eligible path.
  1174. */
  1175. if (! userHasSpecifiedLinks()) {
  1176. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1177. if (_paths[i].p && _paths[i].eligible) {
  1178. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1179. if (link) {
  1180. log("found eligible link %s", pathToStr(_paths[i].p).c_str());
  1181. _abPathIdx = i;
  1182. break;
  1183. }
  1184. }
  1185. }
  1186. }
  1187. /**
  1188. * [Manual mode]
  1189. * The user has specified links or failover rules that the bonding policy should adhere to.
  1190. */
  1191. else if (userHasSpecifiedLinks()) {
  1192. if (userHasSpecifiedPrimaryLink()) {
  1193. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1194. if (! _paths[i].p) {
  1195. continue;
  1196. }
  1197. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1198. if (_paths[i].eligible && link->primary()) {
  1199. if (! _paths[i].preferred()) {
  1200. // Found path on primary link, take note in case we don't find a preferred path
  1201. nonPreferredPathIdx = i;
  1202. bFoundPrimaryLink = true;
  1203. }
  1204. if (_paths[i].preferred()) {
  1205. _abPathIdx = i;
  1206. bFoundPrimaryLink = true;
  1207. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[_abPathIdx].p->localSocket());
  1208. if (link) {
  1209. log("found preferred primary link %s", pathToStr(_paths[_abPathIdx].p).c_str());
  1210. }
  1211. break; // Found preferred path on primary link
  1212. }
  1213. }
  1214. }
  1215. if (bFoundPrimaryLink && nonPreferredPathIdx) {
  1216. log("found non-preferred primary link");
  1217. _abPathIdx = nonPreferredPathIdx;
  1218. }
  1219. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1220. log("user-designated primary link is not yet ready");
  1221. // TODO: Should wait for some time (failover interval?) and then switch to spare link
  1222. }
  1223. }
  1224. else if (! userHasSpecifiedPrimaryLink()) {
  1225. log("user did not specify a primary link, select first available link");
  1226. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1227. if (_paths[i].p && _paths[i].eligible) {
  1228. _abPathIdx = i;
  1229. break;
  1230. }
  1231. }
  1232. if (_abPathIdx != ZT_MAX_PEER_NETWORK_PATHS) {
  1233. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[_abPathIdx].p->localSocket());
  1234. if (link) {
  1235. log("select non-primary link %s", pathToStr(_paths[_abPathIdx].p).c_str());
  1236. }
  1237. }
  1238. }
  1239. }
  1240. }
  1241. // Short-circuit if we don't have an active link yet
  1242. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1243. return;
  1244. }
  1245. // Remove ineligible paths from the failover link queue
  1246. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end();) {
  1247. if (_paths[(*it)].p && ! _paths[(*it)].eligible) {
  1248. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[(*it)].p->localSocket());
  1249. it = _abFailoverQueue.erase(it);
  1250. if (link) {
  1251. log("link %s is ineligible, removing from failover queue (%zu links in queue)", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
  1252. }
  1253. }
  1254. else {
  1255. ++it;
  1256. }
  1257. }
  1258. /**
  1259. * Failover instructions were provided by user, build queue according those as well as IPv
  1260. * preference, disregarding performance.
  1261. */
  1262. if (userHasSpecifiedFailoverInstructions()) {
  1263. /**
  1264. * Clear failover scores
  1265. */
  1266. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1267. if (_paths[i].p) {
  1268. _paths[i].failoverScore = 0;
  1269. }
  1270. }
  1271. // Follow user-specified failover instructions
  1272. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1273. if (! _paths[i].p || ! _paths[i].allowed() || ! _paths[i].eligible) {
  1274. continue;
  1275. }
  1276. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1277. int failoverScoreHandicap = _paths[i].failoverScore;
  1278. if (_paths[i].preferred()) {
  1279. failoverScoreHandicap += ZT_BOND_FAILOVER_HANDICAP_PREFERRED;
  1280. }
  1281. if (link->primary()) {
  1282. // If using "optimize" primary re-select mode, ignore user link designations
  1283. failoverScoreHandicap += ZT_BOND_FAILOVER_HANDICAP_PRIMARY;
  1284. }
  1285. if (! _paths[i].failoverScore) {
  1286. // If we didn't inherit a failover score from a "parent" that wants to use this path as a failover
  1287. int newHandicap = failoverScoreHandicap ? failoverScoreHandicap : _paths[i].allocation;
  1288. _paths[i].failoverScore = newHandicap;
  1289. }
  1290. SharedPtr<Link> failoverLink;
  1291. if (link->failoverToLink().length()) {
  1292. failoverLink = RR->bc->getLinkByName(_policyAlias, link->failoverToLink());
  1293. }
  1294. if (failoverLink) {
  1295. for (int j = 0; j < ZT_MAX_PEER_NETWORK_PATHS; j++) {
  1296. if (_paths[j].p && getLink(_paths[j].p) == failoverLink.ptr()) {
  1297. int inheritedHandicap = failoverScoreHandicap - 10;
  1298. int newHandicap = _paths[j].failoverScore > inheritedHandicap ? _paths[j].failoverScore : inheritedHandicap;
  1299. if (! _paths[j].preferred()) {
  1300. newHandicap--;
  1301. }
  1302. _paths[j].failoverScore = newHandicap;
  1303. }
  1304. }
  1305. }
  1306. if (_paths[i].p.ptr() != _paths[_abPathIdx].p.ptr()) {
  1307. bool bFoundPathInQueue = false;
  1308. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end(); ++it) {
  1309. if (_paths[i].p.ptr() == _paths[(*it)].p.ptr()) {
  1310. bFoundPathInQueue = true;
  1311. }
  1312. }
  1313. if (! bFoundPathInQueue) {
  1314. _abFailoverQueue.push_front(i);
  1315. log("add link %s to failover queue (%zu links in queue)", pathToStr(_paths[i].p).c_str(), _abFailoverQueue.size());
  1316. addPathToBond(0, i);
  1317. }
  1318. }
  1319. }
  1320. }
  1321. /**
  1322. * No failover instructions provided by user, build queue according to performance
  1323. * and IPv preference.
  1324. */
  1325. else if (! userHasSpecifiedFailoverInstructions()) {
  1326. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1327. if (! _paths[i].p || ! _paths[i].allowed() || ! _paths[i].eligible) {
  1328. continue;
  1329. }
  1330. int failoverScoreHandicap = 0;
  1331. if (_paths[i].preferred()) {
  1332. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_PREFERRED;
  1333. }
  1334. if (! _paths[i].eligible) {
  1335. failoverScoreHandicap = -10000;
  1336. }
  1337. if (getLink(_paths[i].p)->primary() && _abLinkSelectMethod != ZT_BOND_RESELECTION_POLICY_OPTIMIZE) {
  1338. // If using "optimize" primary re-select mode, ignore user link designations
  1339. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_PRIMARY;
  1340. }
  1341. /*
  1342. if (_paths[i].p.ptr() == _paths[_negotiatedPathIdx].p.ptr()) {
  1343. _paths[i].negotiated = true;
  1344. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_NEGOTIATED;
  1345. }
  1346. else {
  1347. _paths[i].negotiated = false;
  1348. }
  1349. */
  1350. _paths[i].failoverScore = _paths[i].allocation + failoverScoreHandicap;
  1351. if (_paths[i].p.ptr() != _paths[_abPathIdx].p.ptr()) {
  1352. bool bFoundPathInQueue = false;
  1353. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end(); ++it) {
  1354. if (_paths[i].p.ptr() == _paths[(*it)].p.ptr()) {
  1355. bFoundPathInQueue = true;
  1356. }
  1357. }
  1358. if (! bFoundPathInQueue) {
  1359. _abFailoverQueue.push_front(i);
  1360. log("add link %s to failover queue (%zu links in queue)", pathToStr(_paths[i].p).c_str(), _abFailoverQueue.size());
  1361. addPathToBond(0, i);
  1362. }
  1363. }
  1364. }
  1365. }
  1366. // Sort queue based on performance
  1367. if (! _abFailoverQueue.empty()) {
  1368. for (int i = 0; i < _abFailoverQueue.size(); i++) {
  1369. int value_to_insert = _abFailoverQueue[i];
  1370. int hole_position = i;
  1371. while (hole_position > 0 && (_abFailoverQueue[hole_position - 1] > value_to_insert)) {
  1372. _abFailoverQueue[hole_position] = _abFailoverQueue[hole_position - 1];
  1373. hole_position = hole_position - 1;
  1374. }
  1375. _abFailoverQueue[hole_position] = value_to_insert;
  1376. }
  1377. }
  1378. /**
  1379. * Short-circuit if we have no queued paths
  1380. */
  1381. if (_abFailoverQueue.empty()) {
  1382. return;
  1383. }
  1384. /**
  1385. * Fulfill primary re-select obligations
  1386. */
  1387. if (_paths[_abPathIdx].p && ! _paths[_abPathIdx].eligible) { // Implicit ZT_BOND_RESELECTION_POLICY_FAILURE
  1388. log("link %s has failed, select link from failover queue (%zu links in queue)", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
  1389. if (! _abFailoverQueue.empty()) {
  1390. dequeueNextActiveBackupPath(now);
  1391. log("active link switched to %s", pathToStr(_paths[_abPathIdx].p).c_str());
  1392. }
  1393. else {
  1394. log("failover queue is empty, no links to choose from");
  1395. }
  1396. }
  1397. /**
  1398. * Detect change to prevent flopping during later optimization step.
  1399. */
  1400. if (prevActiveBackupPathIdx != _abPathIdx) {
  1401. _lastActiveBackupPathChange = now;
  1402. }
  1403. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_ALWAYS) {
  1404. if (_paths[_abPathIdx].p && ! getLink(_paths[_abPathIdx].p)->primary() && getLink(_paths[_abFailoverQueue.front()].p)->primary()) {
  1405. dequeueNextActiveBackupPath(now);
  1406. log("switch back to available primary link %s (select mode: always)", pathToStr(_paths[_abPathIdx].p).c_str());
  1407. }
  1408. }
  1409. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_BETTER) {
  1410. if (_paths[_abPathIdx].p && ! getLink(_paths[_abPathIdx].p)->primary()) {
  1411. // Active backup has switched to "better" primary link according to re-select policy.
  1412. if (getLink(_paths[_abFailoverQueue.front()].p)->primary() && (_paths[_abFailoverQueue.front()].failoverScore > _paths[_abPathIdx].failoverScore)) {
  1413. dequeueNextActiveBackupPath(now);
  1414. log("switch back to user-defined primary link %s (select mode: better)", pathToStr(_paths[_abPathIdx].p).c_str());
  1415. }
  1416. }
  1417. }
  1418. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_OPTIMIZE && ! _abFailoverQueue.empty()) {
  1419. /**
  1420. * Implement link negotiation that was previously-decided
  1421. */
  1422. if (_paths[_abFailoverQueue.front()].negotiated) {
  1423. dequeueNextActiveBackupPath(now);
  1424. _lastPathNegotiationCheck = now;
  1425. log("switch negotiated link %s (select mode: optimize)", pathToStr(_paths[_abPathIdx].p).c_str());
  1426. }
  1427. else {
  1428. // Try to find a better path and automatically switch to it -- not too often, though.
  1429. if ((now - _lastActiveBackupPathChange) > ZT_BOND_OPTIMIZE_INTERVAL) {
  1430. if (! _abFailoverQueue.empty()) {
  1431. int newFScore = _paths[_abFailoverQueue.front()].failoverScore;
  1432. int prevFScore = _paths[_abPathIdx].failoverScore;
  1433. // Establish a minimum switch threshold to prevent flapping
  1434. int failoverScoreDifference = _paths[_abFailoverQueue.front()].failoverScore - _paths[_abPathIdx].failoverScore;
  1435. int thresholdQuantity = (int)(ZT_BOND_ACTIVE_BACKUP_OPTIMIZE_MIN_THRESHOLD * (float)_paths[_abPathIdx].allocation);
  1436. if ((failoverScoreDifference > 0) && (failoverScoreDifference > thresholdQuantity)) {
  1437. SharedPtr<Path> oldPath = _paths[_abPathIdx].p;
  1438. dequeueNextActiveBackupPath(now);
  1439. log("switch from %s (score: %d) to better link %s (score: %d) (select mode: optimize)",
  1440. pathToStr(oldPath).c_str(),
  1441. prevFScore,
  1442. pathToStr(_paths[_abPathIdx].p).c_str(),
  1443. newFScore);
  1444. }
  1445. }
  1446. }
  1447. }
  1448. }
  1449. }
  1450. void Bond::initTimers()
  1451. {
  1452. _lastFlowExpirationCheck = 0;
  1453. _lastFlowRebalance = 0;
  1454. _lastSentPathNegotiationRequest = 0;
  1455. _lastPathNegotiationCheck = 0;
  1456. _lastPathNegotiationReceived = 0;
  1457. _lastQoSRateCheck = 0;
  1458. _lastQualityEstimation = 0;
  1459. _lastBondStatusLog = 0;
  1460. _lastSummaryDump = 0;
  1461. _lastActiveBackupPathChange = 0;
  1462. _lastFrame = 0;
  1463. _lastBackgroundTaskCheck = 0;
  1464. }
  1465. void Bond::setBondParameters(int policy, SharedPtr<Bond> templateBond, bool useTemplate)
  1466. {
  1467. // Sanity check for policy
  1468. _defaultPolicy = (_defaultPolicy <= ZT_BOND_POLICY_NONE || _defaultPolicy > ZT_BOND_POLICY_BALANCE_AWARE) ? ZT_BOND_POLICY_NONE : _defaultPolicy;
  1469. _policy = (policy <= ZT_BOND_POLICY_NONE || policy > ZT_BOND_POLICY_BALANCE_AWARE) ? ZT_BOND_POLICY_NONE : _defaultPolicy;
  1470. // Check if non-leaf to prevent spamming infrastructure
  1471. if (_peer) {
  1472. ZT_PeerRole role = RR->topology->role(_peer->address());
  1473. _isLeaf = (role != ZT_PEER_ROLE_PLANET && role != ZT_PEER_ROLE_MOON);
  1474. }
  1475. // Flows
  1476. _allowFlowHashing = false;
  1477. // Path negotiation
  1478. _allowPathNegotiation = false;
  1479. _pathNegotiationCutoffCount = 0;
  1480. _localUtility = 0;
  1481. _negotiatedPathIdx = 0;
  1482. // QOS Verb (and related checks)
  1483. _qosCutoffCount = 0;
  1484. // User preferences which may override the default bonding algorithm's behavior
  1485. _userHasSpecifiedPrimaryLink = false;
  1486. _userHasSpecifiedFailoverInstructions = false;
  1487. _userHasSpecifiedLinkSpeeds = 0;
  1488. // Bond status
  1489. _numAliveLinks = 0;
  1490. _numTotalLinks = 0;
  1491. _numBondedPaths = 0;
  1492. // active-backup
  1493. _abPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1494. // rr
  1495. _rrPacketsSentOnCurrLink = 0;
  1496. _rrIdx = 0;
  1497. // General parameters
  1498. _downDelay = 0;
  1499. _upDelay = 0;
  1500. _monitorInterval = 0;
  1501. // (Sane?) limits
  1502. _maxAcceptableLatency = 100;
  1503. _maxAcceptablePacketDelayVariance = 50;
  1504. _maxAcceptablePacketLossRatio = 0.10f;
  1505. _maxAcceptablePacketErrorRatio = 0.10f;
  1506. // balance-aware
  1507. _totalBondUnderload = 0;
  1508. _overheadBytes = 0;
  1509. /**
  1510. * Policy-specific defaults
  1511. */
  1512. switch (_policy) {
  1513. case ZT_BOND_POLICY_ACTIVE_BACKUP:
  1514. _abLinkSelectMethod = ZT_BOND_RESELECTION_POLICY_OPTIMIZE;
  1515. break;
  1516. case ZT_BOND_POLICY_BROADCAST:
  1517. _downDelay = 30000;
  1518. _upDelay = 0;
  1519. break;
  1520. case ZT_BOND_POLICY_BALANCE_RR:
  1521. _packetsPerLink = 64;
  1522. break;
  1523. case ZT_BOND_POLICY_BALANCE_XOR:
  1524. _allowFlowHashing = true;
  1525. break;
  1526. case ZT_BOND_POLICY_BALANCE_AWARE:
  1527. _allowFlowHashing = true;
  1528. break;
  1529. default:
  1530. break;
  1531. }
  1532. _qw[ZT_QOS_LAT_IDX] = 0.3f;
  1533. _qw[ZT_QOS_LTM_IDX] = 0.1f;
  1534. _qw[ZT_QOS_PDV_IDX] = 0.3f;
  1535. _qw[ZT_QOS_PLR_IDX] = 0.1f;
  1536. _qw[ZT_QOS_PER_IDX] = 0.1f;
  1537. _qw[ZT_QOS_SCP_IDX] = 0.1f;
  1538. _failoverInterval = ZT_BOND_FAILOVER_DEFAULT_INTERVAL;
  1539. /* If a user has specified custom parameters for this bonding policy, overlay them onto the defaults */
  1540. if (useTemplate) {
  1541. _policyAlias = templateBond->_policyAlias;
  1542. _policy = templateBond->policy();
  1543. _failoverInterval = templateBond->_failoverInterval >= ZT_BOND_FAILOVER_MIN_INTERVAL ? templateBond->_failoverInterval : ZT_BOND_FAILOVER_MIN_INTERVAL;
  1544. _downDelay = templateBond->_downDelay;
  1545. _upDelay = templateBond->_upDelay;
  1546. _abLinkSelectMethod = templateBond->_abLinkSelectMethod;
  1547. memcpy(_qw, templateBond->_qw, ZT_QOS_WEIGHT_SIZE * sizeof(float));
  1548. }
  1549. if (!_isLeaf) {
  1550. _policy = ZT_BOND_POLICY_ACTIVE_BACKUP;
  1551. }
  1552. // Timer geometry
  1553. _monitorInterval = _failoverInterval / ZT_BOND_ECHOS_PER_FAILOVER_INTERVAL;
  1554. _qualityEstimationInterval = _failoverInterval * 2;
  1555. _qosSendInterval = _failoverInterval * 2;
  1556. _qosCutoffCount = 0;
  1557. _defaultPathRefractoryPeriod = 8000;
  1558. }
  1559. void Bond::setUserQualityWeights(float weights[], int len)
  1560. {
  1561. if (len == ZT_QOS_WEIGHT_SIZE) {
  1562. float weightTotal = 0.0;
  1563. for (unsigned int i = 0; i < ZT_QOS_WEIGHT_SIZE; ++i) {
  1564. weightTotal += weights[i];
  1565. }
  1566. if (weightTotal > 0.99 && weightTotal < 1.01) {
  1567. memcpy(_qw, weights, len * sizeof(float));
  1568. }
  1569. }
  1570. }
  1571. SharedPtr<Link> Bond::getLink(const SharedPtr<Path>& path)
  1572. {
  1573. return RR->bc->getLinkBySocket(_policyAlias, path->localSocket());
  1574. }
  1575. std::string Bond::pathToStr(const SharedPtr<Path>& path)
  1576. {
  1577. #ifdef ZT_TRACE
  1578. if (path) {
  1579. char pathStr[64] = { 0 };
  1580. char fullPathStr[384] = { 0 };
  1581. path->address().toString(pathStr);
  1582. snprintf(fullPathStr, 384, "%.16llx-%s/%s", (unsigned long long)(path->localSocket()), getLink(path)->ifname().c_str(), pathStr);
  1583. return std::string(fullPathStr);
  1584. }
  1585. return "";
  1586. #else
  1587. return "";
  1588. #endif
  1589. }
  1590. void Bond::dumpPathStatus(int64_t now, int pathIdx)
  1591. {
  1592. #ifdef ZT_TRACE
  1593. std::string aliveOrDead = _paths[pathIdx].alive ? std::string("alive") : std::string("dead");
  1594. std::string eligibleOrNot = _paths[pathIdx].eligible ? std::string("eligible") : std::string("ineligible");
  1595. std::string bondedOrNot = _paths[pathIdx].bonded ? std::string("bonded") : std::string("unbonded");
  1596. log("path[%2d] --- %5s (in %7d, out: %7d), %10s, %8s, flows=%-6d lat=%-8.3f pdv=%-7.3f err=%-6.4f loss=%-6.4f alloc=%-3d --- (%s)",
  1597. pathIdx,
  1598. aliveOrDead.c_str(),
  1599. _paths[pathIdx].p->age(now),
  1600. (now - _paths[pathIdx].p->_lastOut),
  1601. eligibleOrNot.c_str(),
  1602. bondedOrNot.c_str(),
  1603. _paths[pathIdx].assignedFlowCount,
  1604. _paths[pathIdx].latencyMean,
  1605. _paths[pathIdx].latencyVariance,
  1606. _paths[pathIdx].packetErrorRatio,
  1607. _paths[pathIdx].packetLossRatio,
  1608. _paths[pathIdx].allocation,
  1609. pathToStr(_paths[pathIdx].p).c_str());
  1610. #endif
  1611. }
  1612. void Bond::dumpInfo(int64_t now, bool force)
  1613. {
  1614. #ifdef ZT_TRACE
  1615. uint64_t timeSinceLastDump = now - _lastSummaryDump;
  1616. if (! force && timeSinceLastDump < ZT_BOND_STATUS_INTERVAL) {
  1617. return;
  1618. }
  1619. _lastSummaryDump = now;
  1620. float overhead = (_overheadBytes / (timeSinceLastDump / 1000.0f) / 1000.0f);
  1621. _overheadBytes = 0;
  1622. log("bond: bp=%d, fi=%d, mi=%d, ud=%d, dd=%d, flows=%lu, leaf=%d, overhead=%f KB/s, links=(%d/%d)",
  1623. _policy,
  1624. _failoverInterval,
  1625. _monitorInterval,
  1626. _upDelay,
  1627. _downDelay,
  1628. (unsigned long)_flows.size(),
  1629. _isLeaf,
  1630. overhead,
  1631. _numAliveLinks,
  1632. _numTotalLinks);
  1633. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1634. if (_paths[i].p) {
  1635. dumpPathStatus(now, i);
  1636. }
  1637. }
  1638. log("");
  1639. #endif
  1640. }
  1641. } // namespace ZeroTier