Bond.cpp 69 KB

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