Bond.cpp 59 KB

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