Bond.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774
  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. 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_PENDING_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. if (_paths[pathIdx].qosStatsIn.size() < ZT_QOS_MAX_PENDING_RECORDS) {
  405. _paths[pathIdx].qosStatsIn[packetId] = now;
  406. ++(_paths[pathIdx].packetsReceivedSinceLastQoS);
  407. //_paths[pathIdx].packetValiditySamples.push(true);
  408. }
  409. }
  410. }
  411. }
  412. /**
  413. * Learn new flows and pro-actively create entries for them in the bond so
  414. * that the next time we send a packet out that is part of a flow we know
  415. * which path to use.
  416. */
  417. if ((flowId != ZT_QOS_NO_FLOW) && (_policy == ZT_BOND_POLICY_BALANCE_RR || _policy == ZT_BOND_POLICY_BALANCE_XOR || _policy == ZT_BOND_POLICY_BALANCE_AWARE)) {
  418. Mutex::Lock _l(_flows_m);
  419. SharedPtr<Flow> flow;
  420. if (! _flows.count(flowId)) {
  421. flow = createFlow(pathIdx, flowId, 0, now);
  422. }
  423. else {
  424. flow = _flows[flowId];
  425. }
  426. if (flow) {
  427. flow->bytesIn += payloadLength;
  428. }
  429. }
  430. }
  431. void Bond::receivedQoS(const SharedPtr<Path>& path, int64_t now, int count, uint64_t* rx_id, uint16_t* rx_ts)
  432. {
  433. Mutex::Lock _l(_paths_m);
  434. int pathIdx = getNominatedPathIdx(path);
  435. if (pathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  436. return;
  437. }
  438. // debug("received QoS packet (sampling %d frames) via %s", count, pathToStr(path).c_str());
  439. // Look up egress times and compute latency values for each record
  440. std::map<uint64_t, uint64_t>::iterator it;
  441. for (int j = 0; j < count; j++) {
  442. it = _paths[pathIdx].qosStatsOut.find(rx_id[j]);
  443. if (it != _paths[pathIdx].qosStatsOut.end()) {
  444. _paths[pathIdx].latencySamples.push(((uint16_t)(now - it->second) - rx_ts[j]) / 2);
  445. _paths[pathIdx].qosStatsOut.erase(it);
  446. }
  447. }
  448. _paths[pathIdx].qosRecordSize.push(count);
  449. }
  450. int32_t Bond::generateQoSPacket(int pathIdx, int64_t now, char* qosBuffer)
  451. {
  452. int32_t len = 0;
  453. std::map<uint64_t, uint64_t>::iterator it = _paths[pathIdx].qosStatsIn.begin();
  454. int i = 0;
  455. int numRecords = std::min(_paths[pathIdx].packetsReceivedSinceLastQoS, ZT_QOS_TABLE_SIZE);
  456. while (i < numRecords && it != _paths[pathIdx].qosStatsIn.end()) {
  457. uint64_t id = it->first;
  458. memcpy(qosBuffer, &id, sizeof(uint64_t));
  459. qosBuffer += sizeof(uint64_t);
  460. uint16_t holdingTime = (uint16_t)(now - it->second);
  461. memcpy(qosBuffer, &holdingTime, sizeof(uint16_t));
  462. qosBuffer += sizeof(uint16_t);
  463. len += sizeof(uint64_t) + sizeof(uint16_t);
  464. _paths[pathIdx].qosStatsIn.erase(it++);
  465. ++i;
  466. }
  467. return len;
  468. }
  469. bool Bond::assignFlowToBondedPath(SharedPtr<Flow>& flow, int64_t now)
  470. {
  471. if (! _numBondedPaths) {
  472. debug("unable to assign flow %x (bond has no links)\n", flow->id);
  473. return false;
  474. }
  475. unsigned int idx = ZT_MAX_PEER_NETWORK_PATHS;
  476. if (_policy == ZT_BOND_POLICY_BALANCE_XOR) {
  477. idx = abs((int)(flow->id % (_numBondedPaths)));
  478. flow->assignPath(_bondIdxMap[idx], now);
  479. ++(_paths[_bondIdxMap[idx]].assignedFlowCount);
  480. }
  481. if (_policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  482. unsigned char entropy;
  483. Utils::getSecureRandom(&entropy, 1);
  484. if (_totalBondUnderload) {
  485. entropy %= _totalBondUnderload;
  486. }
  487. /* Since there may be scenarios where a path is removed before we can re-estimate
  488. relative qualities (and thus allocations) we need to down-modulate the entropy
  489. value that we use to randomly assign among the surviving paths, otherwise we risk
  490. not being able to find a path to assign this flow to. */
  491. int totalIncompleteAllocation = 0;
  492. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  493. if (_paths[i].p && _paths[i].bonded) {
  494. totalIncompleteAllocation += _paths[i].allocation;
  495. }
  496. }
  497. entropy %= totalIncompleteAllocation;
  498. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  499. if (_paths[i].p && _paths[i].bonded) {
  500. uint8_t probabilitySegment = (_totalBondUnderload > 0) ? _paths[i].affinity : _paths[i].allocation;
  501. if (entropy <= probabilitySegment) {
  502. idx = i;
  503. break;
  504. }
  505. entropy -= probabilitySegment;
  506. }
  507. }
  508. if (idx < ZT_MAX_PEER_NETWORK_PATHS) {
  509. flow->assignPath(idx, now);
  510. ++(_paths[idx].assignedFlowCount);
  511. }
  512. else {
  513. debug("unable to assign out-flow %x (unknown reason)", flow->id);
  514. return false;
  515. }
  516. }
  517. if (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP) {
  518. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  519. debug("unable to assign out-flow %x (no active backup link)", flow->id);
  520. }
  521. flow->assignPath(_abPathIdx, now);
  522. }
  523. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[flow->assignedPath].p->localSocket());
  524. 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());
  525. return true;
  526. }
  527. SharedPtr<Bond::Flow> Bond::createFlow(int pathIdx, int32_t flowId, unsigned char entropy, int64_t now)
  528. {
  529. if (! _numBondedPaths) {
  530. debug("unable to assign flow %x (bond has no links)\n", flowId);
  531. return SharedPtr<Flow>();
  532. }
  533. if (_flows.size() >= ZT_FLOW_MAX_COUNT) {
  534. debug("forget oldest flow (max flows reached: %d)\n", ZT_FLOW_MAX_COUNT);
  535. forgetFlowsWhenNecessary(0, true, now);
  536. }
  537. SharedPtr<Flow> flow = new Flow(flowId, now);
  538. _flows[flowId] = flow;
  539. /**
  540. * Add a flow with a given Path already provided. This is the case when a packet
  541. * is received on a path but no flow exists, in this case we simply assign the path
  542. * that the remote peer chose for us.
  543. */
  544. if (pathIdx != ZT_MAX_PEER_NETWORK_PATHS) {
  545. flow->assignPath(pathIdx, now);
  546. _paths[pathIdx].assignedFlowCount++;
  547. 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());
  548. }
  549. /**
  550. * Add a flow when no path was provided. This means that it is an outgoing packet
  551. * and that it is up to the local peer to decide how to load-balance its transmission.
  552. */
  553. else {
  554. assignFlowToBondedPath(flow, now);
  555. }
  556. return flow;
  557. }
  558. void Bond::forgetFlowsWhenNecessary(uint64_t age, bool oldest, int64_t now)
  559. {
  560. std::map<int32_t, SharedPtr<Flow> >::iterator it = _flows.begin();
  561. std::map<int32_t, SharedPtr<Flow> >::iterator oldestFlow = _flows.end();
  562. SharedPtr<Flow> expiredFlow;
  563. if (age) { // Remove by specific age
  564. while (it != _flows.end()) {
  565. if (it->second->age(now) > age) {
  566. 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));
  567. _paths[it->second->assignedPath].assignedFlowCount--;
  568. it = _flows.erase(it);
  569. }
  570. else {
  571. ++it;
  572. }
  573. }
  574. }
  575. else if (oldest) { // Remove single oldest by natural expiration
  576. uint64_t maxAge = 0;
  577. while (it != _flows.end()) {
  578. if (it->second->age(now) > maxAge) {
  579. maxAge = (now - it->second->age(now));
  580. oldestFlow = it;
  581. }
  582. ++it;
  583. }
  584. if (oldestFlow != _flows.end()) {
  585. debug("forget oldest flow %x (age %llu) (total flows: %lu)", oldestFlow->first, (unsigned long long)oldestFlow->second->age(now), (unsigned long)(_flows.size() - 1));
  586. _paths[oldestFlow->second->assignedPath].assignedFlowCount--;
  587. _flows.erase(oldestFlow);
  588. }
  589. }
  590. }
  591. void Bond::processIncomingPathNegotiationRequest(uint64_t now, SharedPtr<Path>& path, int16_t remoteUtility)
  592. {
  593. char pathStr[64] = { 0 };
  594. if (_abLinkSelectMethod != ZT_BOND_RESELECTION_POLICY_OPTIMIZE) {
  595. return;
  596. }
  597. Mutex::Lock _l(_paths_m);
  598. int pathIdx = getNominatedPathIdx(path);
  599. if (pathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  600. return;
  601. }
  602. _paths[pathIdx].p->address().toString(pathStr);
  603. if (! _lastPathNegotiationCheck) {
  604. return;
  605. }
  606. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[pathIdx].p->localSocket());
  607. if (remoteUtility > _localUtility) {
  608. _paths[pathIdx].p->address().toString(pathStr);
  609. 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);
  610. _negotiatedPathIdx = pathIdx;
  611. }
  612. if (remoteUtility < _localUtility) {
  613. 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);
  614. }
  615. if (remoteUtility == _localUtility) {
  616. debug("peer suggests alternate link %s/%s, remote utility (%d) equal to local utility (%d)\n", link->ifname().c_str(), pathStr, remoteUtility, _localUtility);
  617. if (_peer->_id.address().toInt() > RR->node->identity().address().toInt()) {
  618. debug("agree with peer to use alternate link %s/%s\n", link->ifname().c_str(), pathStr);
  619. _negotiatedPathIdx = pathIdx;
  620. }
  621. else {
  622. debug("ignore petition from peer to use alternate link %s/%s\n", link->ifname().c_str(), pathStr);
  623. }
  624. }
  625. }
  626. void Bond::pathNegotiationCheck(void* tPtr, int64_t now)
  627. {
  628. int maxInPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  629. int maxOutPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  630. uint64_t maxInCount = 0;
  631. uint64_t maxOutCount = 0;
  632. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  633. if (! _paths[i].p) {
  634. continue;
  635. }
  636. if (_paths[i].packetsIn > maxInCount) {
  637. maxInCount = _paths[i].packetsIn;
  638. maxInPathIdx = i;
  639. }
  640. if (_paths[i].packetsOut > maxOutCount) {
  641. maxOutCount = _paths[i].packetsOut;
  642. maxOutPathIdx = i;
  643. }
  644. _paths[i].resetPacketCounts();
  645. }
  646. bool _peerLinksSynchronized = ((maxInPathIdx != ZT_MAX_PEER_NETWORK_PATHS) && (maxOutPathIdx != ZT_MAX_PEER_NETWORK_PATHS) && (maxInPathIdx != maxOutPathIdx)) ? false : true;
  647. /**
  648. * Determine utility and attempt to petition remote peer to switch to our chosen path
  649. */
  650. if (! _peerLinksSynchronized) {
  651. _localUtility = _paths[maxOutPathIdx].failoverScore - _paths[maxInPathIdx].failoverScore;
  652. if (_paths[maxOutPathIdx].negotiated) {
  653. _localUtility -= ZT_BOND_FAILOVER_HANDICAP_NEGOTIATED;
  654. }
  655. if ((now - _lastSentPathNegotiationRequest) > ZT_PATH_NEGOTIATION_CUTOFF_TIME) {
  656. // fprintf(stderr, "BT: (sync) it's been long enough, sending more requests.\n");
  657. _numSentPathNegotiationRequests = 0;
  658. }
  659. if (_numSentPathNegotiationRequests < ZT_PATH_NEGOTIATION_TRY_COUNT) {
  660. if (_localUtility >= 0) {
  661. // fprintf(stderr, "BT: (sync) paths appear to be out of sync (utility=%d)\n", _localUtility);
  662. sendPATH_NEGOTIATION_REQUEST(tPtr, _paths[maxOutPathIdx].p);
  663. ++_numSentPathNegotiationRequests;
  664. _lastSentPathNegotiationRequest = now;
  665. // fprintf(stderr, "sending request to use %s on %s, ls=%llx, utility=%d\n", pathStr, link->ifname().c_str(), _paths[maxOutPathIdx].p->localSocket(), _localUtility);
  666. }
  667. }
  668. /**
  669. * Give up negotiating and consider switching
  670. */
  671. else if ((now - _lastSentPathNegotiationRequest) > (2 * ZT_BOND_OPTIMIZE_INTERVAL)) {
  672. if (_localUtility == 0) {
  673. // There's no loss to us, just switch without sending a another request
  674. // fprintf(stderr, "BT: (sync) giving up, switching to remote peer's path.\n");
  675. _negotiatedPathIdx = maxInPathIdx;
  676. }
  677. }
  678. }
  679. }
  680. void Bond::sendPATH_NEGOTIATION_REQUEST(void* tPtr, int pathIdx)
  681. {
  682. debug("send link negotiation request to peer via link %s, local utility is %d", pathToStr(_paths[pathIdx].p).c_str(), _localUtility);
  683. if (_abLinkSelectMethod != ZT_BOND_RESELECTION_POLICY_OPTIMIZE) {
  684. return;
  685. }
  686. Packet outp(_peer->_id.address(), RR->identity.address(), Packet::VERB_PATH_NEGOTIATION_REQUEST);
  687. outp.append<int16_t>(_localUtility);
  688. if (_paths[pathIdx].p->address()) {
  689. outp.armor(_peer->key(), false, _peer->aesKeysIfSupported());
  690. RR->node->putPacket(tPtr, _paths[pathIdx].p->localSocket(), _paths[pathIdx].p->address(), outp.data(), outp.size());
  691. _overheadBytes += outp.size();
  692. }
  693. }
  694. void Bond::sendQOS_MEASUREMENT(void* tPtr, int pathIdx, int64_t localSocket, const InetAddress& atAddress, int64_t now)
  695. {
  696. int64_t _now = RR->node->now();
  697. Packet outp(_peer->_id.address(), RR->identity.address(), Packet::VERB_QOS_MEASUREMENT);
  698. char qosData[ZT_QOS_MAX_PACKET_SIZE];
  699. int16_t len = generateQoSPacket(pathIdx, _now, qosData);
  700. if (len) {
  701. outp.append(qosData, len);
  702. if (atAddress) {
  703. outp.armor(_peer->key(), false, _peer->aesKeysIfSupported());
  704. RR->node->putPacket(tPtr, localSocket, atAddress, outp.data(), outp.size());
  705. }
  706. else {
  707. RR->sw->send(tPtr, outp, false);
  708. }
  709. _paths[pathIdx].packetsReceivedSinceLastQoS = 0;
  710. _paths[pathIdx].lastQoSMeasurement = now;
  711. _overheadBytes += outp.size();
  712. }
  713. // debug("send QOS via link %s (len=%d)", pathToStr(_paths[pathIdx].p).c_str(), len);
  714. }
  715. void Bond::processBackgroundBondTasks(void* tPtr, int64_t now)
  716. {
  717. if (! _peer->_localMultipathSupported || (now - _lastBackgroundTaskCheck) < ZT_BOND_BACKGROUND_TASK_MIN_INTERVAL) {
  718. return;
  719. }
  720. _lastBackgroundTaskCheck = now;
  721. Mutex::Lock _l(_paths_m);
  722. curateBond(now, false);
  723. if ((now - _lastQualityEstimation) > _qualityEstimationInterval) {
  724. _lastQualityEstimation = now;
  725. estimatePathQuality(now);
  726. }
  727. dumpInfo(now, false);
  728. // Send ambient monitoring traffic
  729. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  730. if (_paths[i].p && _paths[i].allowed()) {
  731. if (_isLeaf) {
  732. if ((_monitorInterval > 0) && (((now - _paths[i].p->_lastIn) >= (_paths[i].alive ? _monitorInterval : _failoverInterval)))) {
  733. if ((_peer->remoteVersionProtocol() >= 5) && (! ((_peer->remoteVersionMajor() == 1) && (_peer->remoteVersionMinor() == 1) && (_peer->remoteVersionRevision() == 0)))) {
  734. Packet outp(_peer->address(), RR->identity.address(), Packet::VERB_ECHO); // ECHO (this is our bond's heartbeat)
  735. outp.armor(_peer->key(), true, _peer->aesKeysIfSupported());
  736. RR->node->expectReplyTo(outp.packetId());
  737. RR->node->putPacket(tPtr, _paths[i].p->localSocket(), _paths[i].p->address(), outp.data(), outp.size());
  738. _paths[i].p->_lastOut = now;
  739. _overheadBytes += outp.size();
  740. debug("tx: verb 0x%-2x of len %4d via %s (ECHO)", Packet::VERB_ECHO, outp.size(), pathToStr(_paths[i].p).c_str());
  741. }
  742. }
  743. // QOS
  744. if (_paths[i].needsToSendQoS(now, _qosSendInterval)) {
  745. sendQOS_MEASUREMENT(tPtr, i, _paths[i].p->localSocket(), _paths[i].p->address(), now);
  746. }
  747. }
  748. }
  749. }
  750. // Perform periodic background tasks unique to each bonding policy
  751. switch (_policy) {
  752. case ZT_BOND_POLICY_ACTIVE_BACKUP:
  753. processActiveBackupTasks(tPtr, now);
  754. break;
  755. case ZT_BOND_POLICY_BROADCAST:
  756. break;
  757. case ZT_BOND_POLICY_BALANCE_RR:
  758. case ZT_BOND_POLICY_BALANCE_XOR:
  759. case ZT_BOND_POLICY_BALANCE_AWARE:
  760. processBalanceTasks(now);
  761. break;
  762. default:
  763. break;
  764. }
  765. // Check whether or not a path negotiation needs to be performed
  766. if (((now - _lastPathNegotiationCheck) > ZT_BOND_OPTIMIZE_INTERVAL) && _allowPathNegotiation) {
  767. _lastPathNegotiationCheck = now;
  768. pathNegotiationCheck(tPtr, now);
  769. }
  770. }
  771. void Bond::curateBond(int64_t now, bool rebuildBond)
  772. {
  773. uint8_t tmpNumAliveLinks = 0;
  774. uint8_t tmpNumTotalLinks = 0;
  775. /**
  776. * Update path state variables. State variables are used so that critical
  777. * blocks that perform fast packet processing won't need to make as many
  778. * function calls or computations.
  779. */
  780. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  781. if (! _paths[i].p) {
  782. continue;
  783. }
  784. /**
  785. * Remove expired links from bond
  786. */
  787. if ((now - _paths[i].p->_lastIn) > (ZT_PEER_EXPIRED_PATH_TRIAL_PERIOD)) {
  788. log("link %s has expired, removing from bond", pathToStr(_paths[i].p).c_str());
  789. _paths[i] = NominatedPath();
  790. _paths[i].p = SharedPtr<Path>();
  791. continue;
  792. }
  793. tmpNumTotalLinks++;
  794. if (_paths[i].eligible) {
  795. tmpNumAliveLinks++;
  796. }
  797. /**
  798. * Determine aliveness
  799. */
  800. _paths[i].alive = _isLeaf ? (now - _paths[i].p->_lastIn) < _failoverInterval : (now - _paths[i].p->_lastIn) < ZT_PEER_PATH_EXPIRATION;
  801. /**
  802. * Determine current eligibility
  803. */
  804. bool currEligibility = false;
  805. // Simple RX age (driven by packets of any type and gratuitous VERB_HELLOs)
  806. bool acceptableAge = _isLeaf ? (_paths[i].p->age(now) < (_failoverInterval + _downDelay)) : _paths[i].alive;
  807. // Whether we've waited long enough since the link last came online
  808. bool satisfiedUpDelay = (now - _paths[i].lastAliveToggle) >= _upDelay;
  809. // Whether this path is still in its trial period
  810. bool inTrial = (now - _paths[i].whenNominated) < ZT_BOND_OPTIMIZE_INTERVAL;
  811. // if (includeRefractoryPeriod && _paths[i].refractoryPeriod) {
  812. // As long as the refractory period value has not fully drained this path is not eligible
  813. // currEligibility = false;
  814. //}
  815. currEligibility = _paths[i].allowed() && ((acceptableAge && satisfiedUpDelay) || inTrial);
  816. // debug("[%d] allowed=%d, acceptableAge=%d, satisfiedUpDelay=%d, inTrial=%d ==== %d", i, _paths[i].allowed(), acceptableAge, satisfiedUpDelay, inTrial, currEligibility);
  817. /**
  818. * Note eligibility state change (if any) and take appropriate action
  819. */
  820. if (currEligibility != _paths[i].eligible) {
  821. if (currEligibility == 0) {
  822. log("link %s is no longer eligible", pathToStr(_paths[i].p).c_str());
  823. }
  824. if (currEligibility == 1) {
  825. log("link %s is eligible", pathToStr(_paths[i].p).c_str());
  826. }
  827. dumpPathStatus(now, i);
  828. if (currEligibility) {
  829. rebuildBond = true;
  830. }
  831. if (! currEligibility) {
  832. _paths[i].adjustRefractoryPeriod(now, _defaultPathRefractoryPeriod, ! currEligibility);
  833. if (_paths[i].bonded) {
  834. if (_allowFlowHashing) {
  835. debug("link %s was bonded, flow reallocation will occur soon", pathToStr(_paths[i].p).c_str());
  836. rebuildBond = true;
  837. _paths[i].shouldReallocateFlows = _paths[i].bonded;
  838. }
  839. _paths[i].bonded = false;
  840. }
  841. }
  842. }
  843. if (currEligibility) {
  844. _paths[i].adjustRefractoryPeriod(now, _defaultPathRefractoryPeriod, false);
  845. }
  846. _paths[i].eligible = currEligibility;
  847. }
  848. /**
  849. * Trigger status report if number of links change
  850. */
  851. _numAliveLinks = tmpNumAliveLinks;
  852. _numTotalLinks = tmpNumTotalLinks;
  853. if ((_numAliveLinks != tmpNumAliveLinks) || (_numTotalLinks != tmpNumTotalLinks)) {
  854. dumpInfo(now, true);
  855. }
  856. /**
  857. * Curate the set of paths that are part of the bond proper. Select a set of paths
  858. * per logical link according to eligibility and user-specified constraints.
  859. */
  860. if ((_policy == ZT_BOND_POLICY_BALANCE_RR) || (_policy == ZT_BOND_POLICY_BALANCE_XOR) || (_policy == ZT_BOND_POLICY_BALANCE_AWARE)) {
  861. if (! _numBondedPaths) {
  862. rebuildBond = true;
  863. }
  864. if (rebuildBond) {
  865. debug("rebuilding bond");
  866. int updatedBondedPathCount = 0;
  867. // Build map associating paths with local physical links. Will be selected from in next step
  868. std::map<SharedPtr<Link>, std::vector<int> > linkMap;
  869. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  870. if (_paths[i].p) {
  871. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  872. linkMap[link].push_back(i);
  873. }
  874. }
  875. // Re-form bond from link<->path map
  876. std::map<SharedPtr<Link>, std::vector<int> >::iterator it = linkMap.begin();
  877. while (it != linkMap.end()) {
  878. SharedPtr<Link> link = it->first;
  879. int ipvPref = link->ipvPref();
  880. // If user has no address type preference, then use every path we find on a link
  881. if (ipvPref == 0) {
  882. for (int j = 0; j < it->second.size(); j++) {
  883. int idx = it->second.at(j);
  884. if (! _paths[idx].p || ! _paths[idx].eligible || ! _paths[idx].allowed()) {
  885. continue;
  886. }
  887. addPathToBond(idx, updatedBondedPathCount);
  888. ++updatedBondedPathCount;
  889. debug("add %s (no user addr preference)", pathToStr(_paths[idx].p).c_str());
  890. }
  891. }
  892. // If the user prefers to only use one address type (IPv4 or IPv6)
  893. if (ipvPref == 4 || ipvPref == 6) {
  894. for (int j = 0; j < it->second.size(); j++) {
  895. int idx = it->second.at(j);
  896. if (! _paths[idx].p || ! _paths[idx].eligible) {
  897. continue;
  898. }
  899. if (! _paths[idx].allowed()) {
  900. debug("did not add %s (user addr preference %d)", pathToStr(_paths[idx].p).c_str(), ipvPref);
  901. continue;
  902. }
  903. addPathToBond(idx, updatedBondedPathCount);
  904. ++updatedBondedPathCount;
  905. debug("add path %s (user addr preference %d)", pathToStr(_paths[idx].p).c_str(), ipvPref);
  906. }
  907. }
  908. // If the users prefers one address type to another, try to find at least
  909. // one path of that type before considering others.
  910. if (ipvPref == 46 || ipvPref == 64) {
  911. bool foundPreferredPath = false;
  912. // Search for preferred paths
  913. for (int j = 0; j < it->second.size(); j++) {
  914. int idx = it->second.at(j);
  915. if (! _paths[idx].p || ! _paths[idx].eligible || ! _paths[idx].allowed()) {
  916. continue;
  917. }
  918. if (_paths[idx].preferred()) {
  919. addPathToBond(idx, updatedBondedPathCount);
  920. ++updatedBondedPathCount;
  921. debug("add %s (user addr preference %d)", pathToStr(_paths[idx].p).c_str(), ipvPref);
  922. foundPreferredPath = true;
  923. }
  924. }
  925. // Unable to find a path that matches user preference, settle for another address type
  926. if (! foundPreferredPath) {
  927. debug("did not find first-choice path type on link %s (user preference %d)", link->ifname().c_str(), ipvPref);
  928. for (int j = 0; j < it->second.size(); j++) {
  929. int idx = it->second.at(j);
  930. if (! _paths[idx].p || ! _paths[idx].eligible) {
  931. continue;
  932. }
  933. addPathToBond(idx, updatedBondedPathCount);
  934. ++updatedBondedPathCount;
  935. debug("add %s (user addr preference %d)", pathToStr(_paths[idx].p).c_str(), ipvPref);
  936. foundPreferredPath = true;
  937. }
  938. }
  939. }
  940. ++it; // Next link
  941. }
  942. _numBondedPaths = updatedBondedPathCount;
  943. if (_policy == ZT_BOND_POLICY_BALANCE_RR) {
  944. // Cause a RR reset since the current index might no longer be valid
  945. _rrPacketsSentOnCurrLink = _packetsPerLink;
  946. }
  947. }
  948. }
  949. }
  950. void Bond::estimatePathQuality(int64_t now)
  951. {
  952. uint32_t totUserSpecifiedLinkSpeed = 0;
  953. if (_numBondedPaths) { // Compute relative user-specified speeds of links
  954. for (unsigned int i = 0; i < _numBondedPaths; ++i) {
  955. if (_paths[i].p && _paths[i].allowed()) {
  956. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  957. totUserSpecifiedLinkSpeed += link->speed();
  958. }
  959. }
  960. for (unsigned int i = 0; i < _numBondedPaths; ++i) {
  961. if (_paths[i].p && _paths[i].allowed()) {
  962. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  963. link->setRelativeSpeed((uint8_t)round(((float)link->speed() / (float)totUserSpecifiedLinkSpeed) * 255));
  964. }
  965. }
  966. }
  967. float lat[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  968. float pdv[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  969. float plr[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  970. float per[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  971. float maxLAT = 0;
  972. float maxPDV = 0;
  973. float maxPLR = 0;
  974. float maxPER = 0;
  975. float quality[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  976. uint8_t alloc[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  977. float totQuality = 0.0f;
  978. // Compute initial summary statistics
  979. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  980. if (! _paths[i].p || ! _paths[i].allowed()) {
  981. continue;
  982. }
  983. // Compute/Smooth average of real-world observations
  984. _paths[i].latencyMean = _paths[i].latencySamples.mean();
  985. _paths[i].latencyVariance = _paths[i].latencySamples.stddev();
  986. //_paths[i].packetErrorRatio = 1.0 - (_paths[i].packetValiditySamples.count() ? _paths[i].packetValiditySamples.mean() : 1.0);
  987. if (userHasSpecifiedLinkSpeeds()) {
  988. // Use user-reported metrics
  989. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  990. if (link) {
  991. _paths[i].throughputMean = link->speed();
  992. _paths[i].throughputVariance = 0;
  993. }
  994. }
  995. // Drain unacknowledged QoS records
  996. int qosRecordTimeout = (_qosSendInterval * 3);
  997. std::map<uint64_t, uint64_t>::iterator it = _paths[i].qosStatsOut.begin();
  998. int numDroppedQosOutRecords = 0;
  999. while (it != _paths[i].qosStatsOut.end()) {
  1000. if ((now - it->second) >= qosRecordTimeout) {
  1001. it = _paths[i].qosStatsOut.erase(it);
  1002. ++numDroppedQosOutRecords;
  1003. }
  1004. else {
  1005. ++it;
  1006. }
  1007. }
  1008. if (numDroppedQosOutRecords) {
  1009. log("Dropped %d QOS out-records", numDroppedQosOutRecords);
  1010. }
  1011. it = _paths[i].qosStatsIn.begin();
  1012. int numDroppedQosInRecords = 0;
  1013. while (it != _paths[i].qosStatsIn.end()) {
  1014. if ((now - it->second) >= qosRecordTimeout) {
  1015. it = _paths[i].qosStatsIn.erase(it);
  1016. ++numDroppedQosInRecords;
  1017. }
  1018. else {
  1019. ++it;
  1020. }
  1021. }
  1022. if (numDroppedQosInRecords) {
  1023. log("Dropped %d QOS in-records", numDroppedQosInRecords);
  1024. }
  1025. quality[i] = 0;
  1026. totQuality = 0;
  1027. // Normalize raw observations according to sane limits and/or user specified values
  1028. lat[i] = 1.0 / expf(4 * Utils::normalize(_paths[i].latencyMean, 0, _maxAcceptableLatency, 0, 1));
  1029. pdv[i] = 1.0 / expf(4 * Utils::normalize(_paths[i].latencyVariance, 0, _maxAcceptablePacketDelayVariance, 0, 1));
  1030. plr[i] = 1.0 / expf(4 * Utils::normalize(_paths[i].packetLossRatio, 0, _maxAcceptablePacketLossRatio, 0, 1));
  1031. per[i] = 1.0 / expf(4 * Utils::normalize(_paths[i].packetErrorRatio, 0, _maxAcceptablePacketErrorRatio, 0, 1));
  1032. // Record bond-wide maximums to determine relative values
  1033. maxLAT = lat[i] > maxLAT ? lat[i] : maxLAT;
  1034. maxPDV = pdv[i] > maxPDV ? pdv[i] : maxPDV;
  1035. maxPLR = plr[i] > maxPLR ? plr[i] : maxPLR;
  1036. maxPER = per[i] > maxPER ? per[i] : maxPER;
  1037. }
  1038. // Convert metrics to relative quantities and apply contribution weights
  1039. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1040. if (_paths[i].p && _paths[i].bonded) {
  1041. quality[i] += ((maxLAT > 0.0f ? lat[i] / maxLAT : 0.0f) * _qw[ZT_QOS_LAT_IDX]);
  1042. quality[i] += ((maxPDV > 0.0f ? pdv[i] / maxPDV : 0.0f) * _qw[ZT_QOS_PDV_IDX]);
  1043. quality[i] += ((maxPLR > 0.0f ? plr[i] / maxPLR : 0.0f) * _qw[ZT_QOS_PLR_IDX]);
  1044. quality[i] += ((maxPER > 0.0f ? per[i] / maxPER : 0.0f) * _qw[ZT_QOS_PER_IDX]);
  1045. totQuality += quality[i];
  1046. }
  1047. }
  1048. // Normalize to 8-bit allocation values
  1049. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1050. if (_paths[i].p && _paths[i].bonded) {
  1051. alloc[i] = (uint8_t)(std::ceil((quality[i] / totQuality) * (float)255));
  1052. _paths[i].allocation = alloc[i];
  1053. }
  1054. }
  1055. }
  1056. void Bond::processBalanceTasks(int64_t now)
  1057. {
  1058. if (_allowFlowHashing) {
  1059. /**
  1060. * Clean up and reset flows if necessary
  1061. */
  1062. if ((now - _lastFlowExpirationCheck) > ZT_PEER_PATH_EXPIRATION) {
  1063. Mutex::Lock _l(_flows_m);
  1064. forgetFlowsWhenNecessary(ZT_PEER_PATH_EXPIRATION, false, now);
  1065. std::map<int32_t, SharedPtr<Flow> >::iterator it = _flows.begin();
  1066. while (it != _flows.end()) {
  1067. it->second->resetByteCounts();
  1068. ++it;
  1069. }
  1070. _lastFlowExpirationCheck = now;
  1071. }
  1072. /**
  1073. * Re-allocate flows from dead paths
  1074. */
  1075. if (_policy == ZT_BOND_POLICY_BALANCE_XOR || _policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  1076. Mutex::Lock _l(_flows_m);
  1077. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1078. if (! _paths[i].p) {
  1079. continue;
  1080. }
  1081. if (! _paths[i].eligible && _paths[i].shouldReallocateFlows) {
  1082. log("reallocate flows from dead link %s", pathToStr(_paths[i].p).c_str());
  1083. std::map<int32_t, SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1084. while (flow_it != _flows.end()) {
  1085. if (_paths[flow_it->second->assignedPath].p == _paths[i].p) {
  1086. if (assignFlowToBondedPath(flow_it->second, now)) {
  1087. _paths[i].assignedFlowCount--;
  1088. }
  1089. }
  1090. ++flow_it;
  1091. }
  1092. _paths[i].shouldReallocateFlows = false;
  1093. }
  1094. }
  1095. }
  1096. /**
  1097. * Re-allocate flows from under-performing
  1098. * NOTE: This could be part of the above block but was kept separate for clarity.
  1099. */
  1100. if (_policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  1101. int totalAllocation = 0;
  1102. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1103. if (! _paths[i].p) {
  1104. continue;
  1105. }
  1106. if (_paths[i].p && _paths[i].bonded && _paths[i].eligible) {
  1107. totalAllocation += _paths[i].allocation;
  1108. }
  1109. }
  1110. unsigned char minimumAllocationValue = (uint8_t)(0.33 * ((float)totalAllocation / (float)_numBondedPaths));
  1111. Mutex::Lock _l(_flows_m);
  1112. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1113. if (! _paths[i].p) {
  1114. continue;
  1115. }
  1116. if (_paths[i].p && _paths[i].bonded && _paths[i].eligible && (_paths[i].allocation < minimumAllocationValue) && _paths[i].assignedFlowCount) {
  1117. log("reallocate flows from under-performing link %s\n", pathToStr(_paths[i].p).c_str());
  1118. std::map<int32_t, SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1119. while (flow_it != _flows.end()) {
  1120. if (flow_it->second->assignedPath == _paths[i].p) {
  1121. if (assignFlowToBondedPath(flow_it->second, now)) {
  1122. _paths[i].assignedFlowCount--;
  1123. }
  1124. }
  1125. ++flow_it;
  1126. }
  1127. _paths[i].shouldReallocateFlows = false;
  1128. }
  1129. }
  1130. }
  1131. }
  1132. }
  1133. void Bond::dequeueNextActiveBackupPath(uint64_t now)
  1134. {
  1135. if (_abFailoverQueue.empty()) {
  1136. return;
  1137. }
  1138. _abPathIdx = _abFailoverQueue.front();
  1139. _abFailoverQueue.pop_front();
  1140. _lastActiveBackupPathChange = now;
  1141. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1142. if (_paths[i].p) {
  1143. _paths[i].resetPacketCounts();
  1144. }
  1145. }
  1146. }
  1147. bool Bond::abForciblyRotateLink()
  1148. {
  1149. if (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP) {
  1150. int prevPathIdx = _abPathIdx;
  1151. dequeueNextActiveBackupPath(RR->node->now());
  1152. log("active link rotated from %s to %s", pathToStr(_paths[prevPathIdx].p).c_str(), pathToStr(_paths[_abPathIdx].p).c_str());
  1153. return true;
  1154. }
  1155. return false;
  1156. }
  1157. void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
  1158. {
  1159. int prevActiveBackupPathIdx = _abPathIdx;
  1160. int nonPreferredPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1161. bool bFoundPrimaryLink = false;
  1162. if (_abPathIdx != ZT_MAX_PEER_NETWORK_PATHS && ! _paths[_abPathIdx].p) {
  1163. _abPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1164. log("main active-backup path has been removed");
  1165. }
  1166. /**
  1167. * Generate periodic status report
  1168. */
  1169. if ((now - _lastBondStatusLog) > ZT_BOND_STATUS_INTERVAL) {
  1170. _lastBondStatusLog = now;
  1171. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1172. log("no active link");
  1173. }
  1174. else if (_paths[_abPathIdx].p) {
  1175. log("active link is %s, failover queue size is %zu", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
  1176. }
  1177. if (_abFailoverQueue.empty()) {
  1178. log("failover queue is empty, bond is no longer fault-tolerant");
  1179. }
  1180. }
  1181. /**
  1182. * Select initial "active" active-backup link
  1183. */
  1184. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1185. /**
  1186. * [Automatic mode]
  1187. * The user has not explicitly specified links or their failover schedule,
  1188. * the bonding policy will now select the first eligible path and set it as
  1189. * its active backup path, if a substantially better path is detected the bonding
  1190. * policy will assign it as the new active backup path. If the path fails it will
  1191. * simply find the next eligible path.
  1192. */
  1193. if (! userHasSpecifiedLinks()) {
  1194. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1195. if (_paths[i].p && _paths[i].eligible) {
  1196. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1197. if (link) {
  1198. log("found eligible link %s", pathToStr(_paths[i].p).c_str());
  1199. _abPathIdx = i;
  1200. break;
  1201. }
  1202. }
  1203. }
  1204. }
  1205. /**
  1206. * [Manual mode]
  1207. * The user has specified links or failover rules that the bonding policy should adhere to.
  1208. */
  1209. else if (userHasSpecifiedLinks()) {
  1210. if (userHasSpecifiedPrimaryLink()) {
  1211. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1212. if (! _paths[i].p) {
  1213. continue;
  1214. }
  1215. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1216. if (_paths[i].eligible && link->primary()) {
  1217. if (! _paths[i].preferred()) {
  1218. // Found path on primary link, take note in case we don't find a preferred path
  1219. nonPreferredPathIdx = i;
  1220. bFoundPrimaryLink = true;
  1221. }
  1222. if (_paths[i].preferred()) {
  1223. _abPathIdx = i;
  1224. bFoundPrimaryLink = true;
  1225. if (_paths[_abPathIdx].p) {
  1226. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[_abPathIdx].p->localSocket());
  1227. if (link) {
  1228. log("found preferred primary link %s", pathToStr(_paths[_abPathIdx].p).c_str());
  1229. }
  1230. break; // Found preferred path on primary link
  1231. }
  1232. }
  1233. }
  1234. }
  1235. if (bFoundPrimaryLink && (nonPreferredPathIdx != ZT_MAX_PEER_NETWORK_PATHS)) {
  1236. log("found non-preferred primary link");
  1237. _abPathIdx = nonPreferredPathIdx;
  1238. }
  1239. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1240. log("user-designated primary link is not yet ready");
  1241. // TODO: Should wait for some time (failover interval?) and then switch to spare link
  1242. }
  1243. }
  1244. else if (! userHasSpecifiedPrimaryLink()) {
  1245. log("user did not specify a primary link, select first available link");
  1246. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1247. if (_paths[i].p && _paths[i].eligible) {
  1248. _abPathIdx = i;
  1249. break;
  1250. }
  1251. }
  1252. if (_abPathIdx != ZT_MAX_PEER_NETWORK_PATHS) {
  1253. if (_paths[_abPathIdx].p) {
  1254. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[_abPathIdx].p->localSocket());
  1255. if (link) {
  1256. log("select non-primary link %s", pathToStr(_paths[_abPathIdx].p).c_str());
  1257. }
  1258. }
  1259. }
  1260. }
  1261. }
  1262. }
  1263. // Short-circuit if we don't have an active link yet. Everything below is optimization from the base case
  1264. if (_abPathIdx < 0 || _abPathIdx == ZT_MAX_PEER_NETWORK_PATHS || (! _paths[_abPathIdx].p)) {
  1265. return;
  1266. }
  1267. // Remove ineligible paths from the failover link queue
  1268. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end();) {
  1269. if (_paths[(*it)].p && ! _paths[(*it)].eligible) {
  1270. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[(*it)].p->localSocket());
  1271. it = _abFailoverQueue.erase(it);
  1272. if (link) {
  1273. log("link %s is ineligible, removing from failover queue (%zu links in queue)", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
  1274. }
  1275. }
  1276. else {
  1277. ++it;
  1278. }
  1279. }
  1280. /**
  1281. * Failover instructions were provided by user, build queue according those as well as IPv
  1282. * preference, disregarding performance.
  1283. */
  1284. if (userHasSpecifiedFailoverInstructions()) {
  1285. /**
  1286. * Clear failover scores
  1287. */
  1288. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1289. if (_paths[i].p) {
  1290. _paths[i].failoverScore = 0;
  1291. }
  1292. }
  1293. // Follow user-specified failover instructions
  1294. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1295. if (! _paths[i].p || ! _paths[i].allowed() || ! _paths[i].eligible) {
  1296. continue;
  1297. }
  1298. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1299. int failoverScoreHandicap = _paths[i].failoverScore;
  1300. if (_paths[i].preferred()) {
  1301. failoverScoreHandicap += ZT_BOND_FAILOVER_HANDICAP_PREFERRED;
  1302. }
  1303. if (link->primary()) {
  1304. // If using "optimize" primary re-select mode, ignore user link designations
  1305. failoverScoreHandicap += ZT_BOND_FAILOVER_HANDICAP_PRIMARY;
  1306. }
  1307. if (! _paths[i].failoverScore) {
  1308. // If we didn't inherit a failover score from a "parent" that wants to use this path as a failover
  1309. int newHandicap = failoverScoreHandicap ? failoverScoreHandicap : _paths[i].allocation;
  1310. _paths[i].failoverScore = newHandicap;
  1311. }
  1312. SharedPtr<Link> failoverLink;
  1313. if (link->failoverToLink().length()) {
  1314. failoverLink = RR->bc->getLinkByName(_policyAlias, link->failoverToLink());
  1315. }
  1316. if (failoverLink) {
  1317. for (int j = 0; j < ZT_MAX_PEER_NETWORK_PATHS; j++) {
  1318. if (_paths[j].p && getLink(_paths[j].p) == failoverLink.ptr()) {
  1319. int inheritedHandicap = failoverScoreHandicap - 10;
  1320. int newHandicap = _paths[j].failoverScore > inheritedHandicap ? _paths[j].failoverScore : inheritedHandicap;
  1321. if (! _paths[j].preferred()) {
  1322. newHandicap--;
  1323. }
  1324. _paths[j].failoverScore = newHandicap;
  1325. }
  1326. }
  1327. }
  1328. if (_paths[i].p) {
  1329. if (_paths[i].p.ptr() != _paths[_abPathIdx].p.ptr()) {
  1330. bool bFoundPathInQueue = false;
  1331. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end(); ++it) {
  1332. if (_paths[(*it)].p && (_paths[i].p.ptr() == _paths[(*it)].p.ptr())) {
  1333. bFoundPathInQueue = true;
  1334. }
  1335. }
  1336. if (! bFoundPathInQueue) {
  1337. _abFailoverQueue.push_front(i);
  1338. log("add link %s to failover queue (%zu links in queue)", pathToStr(_paths[i].p).c_str(), _abFailoverQueue.size());
  1339. addPathToBond(0, i);
  1340. }
  1341. }
  1342. }
  1343. }
  1344. }
  1345. /**
  1346. * No failover instructions provided by user, build queue according to performance
  1347. * and IPv preference.
  1348. */
  1349. else if (! userHasSpecifiedFailoverInstructions()) {
  1350. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1351. if (! _paths[i].p || ! _paths[i].allowed() || ! _paths[i].eligible) {
  1352. continue;
  1353. }
  1354. int failoverScoreHandicap = 0;
  1355. if (_paths[i].preferred()) {
  1356. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_PREFERRED;
  1357. }
  1358. if (! _paths[i].eligible) {
  1359. failoverScoreHandicap = -10000;
  1360. }
  1361. if (getLink(_paths[i].p)->primary() && _abLinkSelectMethod != ZT_BOND_RESELECTION_POLICY_OPTIMIZE) {
  1362. // If using "optimize" primary re-select mode, ignore user link designations
  1363. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_PRIMARY;
  1364. }
  1365. /*
  1366. if (_paths[i].p.ptr() == _paths[_negotiatedPathIdx].p.ptr()) {
  1367. _paths[i].negotiated = true;
  1368. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_NEGOTIATED;
  1369. }
  1370. else {
  1371. _paths[i].negotiated = false;
  1372. }
  1373. */
  1374. _paths[i].failoverScore = _paths[i].allocation + failoverScoreHandicap;
  1375. if (_paths[i].p.ptr() != _paths[_abPathIdx].p.ptr()) {
  1376. bool bFoundPathInQueue = false;
  1377. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end(); ++it) {
  1378. if (_paths[i].p.ptr() == _paths[(*it)].p.ptr()) {
  1379. bFoundPathInQueue = true;
  1380. }
  1381. }
  1382. if (! bFoundPathInQueue) {
  1383. _abFailoverQueue.push_front(i);
  1384. log("add link %s to failover queue (%zu links in queue)", pathToStr(_paths[i].p).c_str(), _abFailoverQueue.size());
  1385. addPathToBond(0, i);
  1386. }
  1387. }
  1388. }
  1389. }
  1390. // Sort queue based on performance
  1391. if (! _abFailoverQueue.empty()) {
  1392. for (int i = 0; i < _abFailoverQueue.size(); i++) {
  1393. int value_to_insert = _abFailoverQueue[i];
  1394. int hole_position = i;
  1395. while (hole_position > 0 && (_abFailoverQueue[hole_position - 1] > value_to_insert)) {
  1396. _abFailoverQueue[hole_position] = _abFailoverQueue[hole_position - 1];
  1397. hole_position = hole_position - 1;
  1398. }
  1399. _abFailoverQueue[hole_position] = value_to_insert;
  1400. }
  1401. }
  1402. /**
  1403. * Short-circuit if we have no queued paths
  1404. */
  1405. if (_abFailoverQueue.empty()) {
  1406. return;
  1407. }
  1408. /**
  1409. * Fulfill primary re-select obligations
  1410. */
  1411. if (! _paths[_abPathIdx].eligible) { // Implicit ZT_BOND_RESELECTION_POLICY_FAILURE
  1412. log("link %s has failed, select link from failover queue (%zu links in queue)", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
  1413. if (! _abFailoverQueue.empty()) {
  1414. dequeueNextActiveBackupPath(now);
  1415. log("active link switched to %s", pathToStr(_paths[_abPathIdx].p).c_str());
  1416. }
  1417. else {
  1418. log("failover queue is empty, no links to choose from");
  1419. }
  1420. }
  1421. /**
  1422. * Detect change to prevent flopping during later optimization step.
  1423. */
  1424. if (prevActiveBackupPathIdx != _abPathIdx) {
  1425. _lastActiveBackupPathChange = now;
  1426. }
  1427. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_ALWAYS) {
  1428. if (! getLink(_paths[_abPathIdx].p)->primary() && _paths[_abFailoverQueue.front()].p && getLink(_paths[_abFailoverQueue.front()].p)->primary()) {
  1429. dequeueNextActiveBackupPath(now);
  1430. log("switch back to available primary link %s (select mode: always)", pathToStr(_paths[_abPathIdx].p).c_str());
  1431. }
  1432. }
  1433. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_BETTER) {
  1434. if (! getLink(_paths[_abPathIdx].p)->primary()) {
  1435. // Active backup has switched to "better" primary link according to re-select policy.
  1436. if (_paths[_abFailoverQueue.front()].p && getLink(_paths[_abFailoverQueue.front()].p)->primary() && (_paths[_abFailoverQueue.front()].failoverScore > _paths[_abPathIdx].failoverScore)) {
  1437. dequeueNextActiveBackupPath(now);
  1438. log("switch back to user-defined primary link %s (select mode: better)", pathToStr(_paths[_abPathIdx].p).c_str());
  1439. }
  1440. }
  1441. }
  1442. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_OPTIMIZE && ! _abFailoverQueue.empty()) {
  1443. /**
  1444. * Implement link negotiation that was previously-decided
  1445. */
  1446. if (_paths[_abFailoverQueue.front()].negotiated) {
  1447. dequeueNextActiveBackupPath(now);
  1448. _lastPathNegotiationCheck = now;
  1449. log("switch negotiated link %s (select mode: optimize)", pathToStr(_paths[_abPathIdx].p).c_str());
  1450. }
  1451. else {
  1452. // Try to find a better path and automatically switch to it -- not too often, though.
  1453. if ((now - _lastActiveBackupPathChange) > ZT_BOND_OPTIMIZE_INTERVAL) {
  1454. if (! _abFailoverQueue.empty()) {
  1455. int newFScore = _paths[_abFailoverQueue.front()].failoverScore;
  1456. int prevFScore = _paths[_abPathIdx].failoverScore;
  1457. // Establish a minimum switch threshold to prevent flapping
  1458. int failoverScoreDifference = _paths[_abFailoverQueue.front()].failoverScore - _paths[_abPathIdx].failoverScore;
  1459. int thresholdQuantity = (int)(ZT_BOND_ACTIVE_BACKUP_OPTIMIZE_MIN_THRESHOLD * (float)_paths[_abPathIdx].allocation);
  1460. if ((failoverScoreDifference > 0) && (failoverScoreDifference > thresholdQuantity)) {
  1461. SharedPtr<Path> oldPath = _paths[_abPathIdx].p;
  1462. dequeueNextActiveBackupPath(now);
  1463. 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);
  1464. }
  1465. }
  1466. }
  1467. }
  1468. }
  1469. }
  1470. void Bond::initTimers()
  1471. {
  1472. _lastFlowExpirationCheck = 0;
  1473. _lastFlowRebalance = 0;
  1474. _lastSentPathNegotiationRequest = 0;
  1475. _lastPathNegotiationCheck = 0;
  1476. _lastPathNegotiationReceived = 0;
  1477. _lastQoSRateCheck = 0;
  1478. _lastQualityEstimation = 0;
  1479. _lastBondStatusLog = 0;
  1480. _lastSummaryDump = 0;
  1481. _lastActiveBackupPathChange = 0;
  1482. _lastFrame = 0;
  1483. _lastBackgroundTaskCheck = 0;
  1484. }
  1485. void Bond::setBondParameters(int policy, SharedPtr<Bond> templateBond, bool useTemplate)
  1486. {
  1487. // Sanity check for policy
  1488. _defaultPolicy = (_defaultPolicy <= ZT_BOND_POLICY_NONE || _defaultPolicy > ZT_BOND_POLICY_BALANCE_AWARE) ? ZT_BOND_POLICY_NONE : _defaultPolicy;
  1489. _policy = (policy <= ZT_BOND_POLICY_NONE || policy > ZT_BOND_POLICY_BALANCE_AWARE) ? ZT_BOND_POLICY_NONE : _defaultPolicy;
  1490. // Check if non-leaf to prevent spamming infrastructure
  1491. if (_peer) {
  1492. ZT_PeerRole role = RR->topology->role(_peer->address());
  1493. _isLeaf = (role != ZT_PEER_ROLE_PLANET && role != ZT_PEER_ROLE_MOON);
  1494. }
  1495. // Flows
  1496. _allowFlowHashing = false;
  1497. // Path negotiation
  1498. _allowPathNegotiation = false;
  1499. _pathNegotiationCutoffCount = 0;
  1500. _localUtility = 0;
  1501. _negotiatedPathIdx = 0;
  1502. // QOS Verb (and related checks)
  1503. _qosCutoffCount = 0;
  1504. // User preferences which may override the default bonding algorithm's behavior
  1505. _userHasSpecifiedPrimaryLink = false;
  1506. _userHasSpecifiedFailoverInstructions = false;
  1507. _userHasSpecifiedLinkSpeeds = 0;
  1508. // Bond status
  1509. _numAliveLinks = 0;
  1510. _numTotalLinks = 0;
  1511. _numBondedPaths = 0;
  1512. // active-backup
  1513. _abPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1514. // rr
  1515. _rrPacketsSentOnCurrLink = 0;
  1516. _rrIdx = 0;
  1517. // General parameters
  1518. _downDelay = 0;
  1519. _upDelay = 0;
  1520. _monitorInterval = 0;
  1521. // (Sane?) limits
  1522. _maxAcceptableLatency = 100;
  1523. _maxAcceptablePacketDelayVariance = 50;
  1524. _maxAcceptablePacketLossRatio = 0.10f;
  1525. _maxAcceptablePacketErrorRatio = 0.10f;
  1526. // balance-aware
  1527. _totalBondUnderload = 0;
  1528. _overheadBytes = 0;
  1529. /**
  1530. * Policy-specific defaults
  1531. */
  1532. switch (_policy) {
  1533. case ZT_BOND_POLICY_ACTIVE_BACKUP:
  1534. _abLinkSelectMethod = ZT_BOND_RESELECTION_POLICY_OPTIMIZE;
  1535. break;
  1536. case ZT_BOND_POLICY_BROADCAST:
  1537. _downDelay = 30000;
  1538. _upDelay = 0;
  1539. break;
  1540. case ZT_BOND_POLICY_BALANCE_RR:
  1541. _packetsPerLink = 64;
  1542. break;
  1543. case ZT_BOND_POLICY_BALANCE_XOR:
  1544. _allowFlowHashing = true;
  1545. break;
  1546. case ZT_BOND_POLICY_BALANCE_AWARE:
  1547. _allowFlowHashing = true;
  1548. break;
  1549. default:
  1550. break;
  1551. }
  1552. _qw[ZT_QOS_LAT_IDX] = 0.3f;
  1553. _qw[ZT_QOS_LTM_IDX] = 0.1f;
  1554. _qw[ZT_QOS_PDV_IDX] = 0.3f;
  1555. _qw[ZT_QOS_PLR_IDX] = 0.1f;
  1556. _qw[ZT_QOS_PER_IDX] = 0.1f;
  1557. _qw[ZT_QOS_SCP_IDX] = 0.1f;
  1558. _failoverInterval = ZT_BOND_FAILOVER_DEFAULT_INTERVAL;
  1559. /* If a user has specified custom parameters for this bonding policy, overlay them onto the defaults */
  1560. if (useTemplate) {
  1561. _policyAlias = templateBond->_policyAlias;
  1562. _policy = templateBond->policy();
  1563. _failoverInterval = templateBond->_failoverInterval >= ZT_BOND_FAILOVER_MIN_INTERVAL ? templateBond->_failoverInterval : ZT_BOND_FAILOVER_MIN_INTERVAL;
  1564. _downDelay = templateBond->_downDelay;
  1565. _upDelay = templateBond->_upDelay;
  1566. _abLinkSelectMethod = templateBond->_abLinkSelectMethod;
  1567. memcpy(_qw, templateBond->_qw, ZT_QOS_WEIGHT_SIZE * sizeof(float));
  1568. }
  1569. if (! _isLeaf) {
  1570. _policy = ZT_BOND_POLICY_ACTIVE_BACKUP;
  1571. }
  1572. // Timer geometry
  1573. _monitorInterval = _failoverInterval / ZT_BOND_ECHOS_PER_FAILOVER_INTERVAL;
  1574. _qualityEstimationInterval = _failoverInterval * 2;
  1575. _qosSendInterval = _failoverInterval * 2;
  1576. _qosCutoffCount = 0;
  1577. _defaultPathRefractoryPeriod = 8000;
  1578. }
  1579. void Bond::setUserQualityWeights(float weights[], int len)
  1580. {
  1581. if (len == ZT_QOS_WEIGHT_SIZE) {
  1582. float weightTotal = 0.0;
  1583. for (unsigned int i = 0; i < ZT_QOS_WEIGHT_SIZE; ++i) {
  1584. weightTotal += weights[i];
  1585. }
  1586. if (weightTotal > 0.99 && weightTotal < 1.01) {
  1587. memcpy(_qw, weights, len * sizeof(float));
  1588. }
  1589. }
  1590. }
  1591. SharedPtr<Link> Bond::getLink(const SharedPtr<Path>& path)
  1592. {
  1593. return RR->bc->getLinkBySocket(_policyAlias, path->localSocket());
  1594. }
  1595. std::string Bond::pathToStr(const SharedPtr<Path>& path)
  1596. {
  1597. #ifdef ZT_TRACE
  1598. if (path) {
  1599. char pathStr[64] = { 0 };
  1600. char fullPathStr[384] = { 0 };
  1601. path->address().toString(pathStr);
  1602. snprintf(fullPathStr, 384, "%.16llx-%s/%s", (unsigned long long)(path->localSocket()), getLink(path)->ifname().c_str(), pathStr);
  1603. return std::string(fullPathStr);
  1604. }
  1605. return "";
  1606. #else
  1607. return "";
  1608. #endif
  1609. }
  1610. void Bond::dumpPathStatus(int64_t now, int pathIdx)
  1611. {
  1612. #ifdef ZT_TRACE
  1613. std::string aliveOrDead = _paths[pathIdx].alive ? std::string("alive") : std::string("dead");
  1614. std::string eligibleOrNot = _paths[pathIdx].eligible ? std::string("eligible") : std::string("ineligible");
  1615. std::string bondedOrNot = _paths[pathIdx].bonded ? std::string("bonded") : std::string("unbonded");
  1616. 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)",
  1617. pathIdx,
  1618. aliveOrDead.c_str(),
  1619. _paths[pathIdx].p->age(now),
  1620. (now - _paths[pathIdx].p->_lastOut),
  1621. eligibleOrNot.c_str(),
  1622. bondedOrNot.c_str(),
  1623. _paths[pathIdx].assignedFlowCount,
  1624. _paths[pathIdx].latencyMean,
  1625. _paths[pathIdx].latencyVariance,
  1626. _paths[pathIdx].packetErrorRatio,
  1627. _paths[pathIdx].packetLossRatio,
  1628. _paths[pathIdx].allocation,
  1629. pathToStr(_paths[pathIdx].p).c_str());
  1630. #endif
  1631. }
  1632. void Bond::dumpInfo(int64_t now, bool force)
  1633. {
  1634. #ifdef ZT_TRACE
  1635. uint64_t timeSinceLastDump = now - _lastSummaryDump;
  1636. if (! force && timeSinceLastDump < ZT_BOND_STATUS_INTERVAL) {
  1637. return;
  1638. }
  1639. _lastSummaryDump = now;
  1640. float overhead = (_overheadBytes / (timeSinceLastDump / 1000.0f) / 1000.0f);
  1641. _overheadBytes = 0;
  1642. log("bond: bp=%d, fi=%d, mi=%d, ud=%d, dd=%d, flows=%lu, leaf=%d, overhead=%f KB/s, links=(%d/%d)",
  1643. _policy,
  1644. _failoverInterval,
  1645. _monitorInterval,
  1646. _upDelay,
  1647. _downDelay,
  1648. (unsigned long)_flows.size(),
  1649. _isLeaf,
  1650. overhead,
  1651. _numAliveLinks,
  1652. _numTotalLinks);
  1653. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1654. if (_paths[i].p) {
  1655. dumpPathStatus(now, i);
  1656. }
  1657. }
  1658. log("");
  1659. #endif
  1660. }
  1661. } // namespace ZeroTier