Bond.cpp 71 KB

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