Bond.cpp 69 KB

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