Bond.cpp 63 KB

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