Bond.cpp 64 KB

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