Bond.cpp 71 KB

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