Bond.cpp 61 KB

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