Bond.cpp 64 KB

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