Bond.cpp 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  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. _paths[i].bonded = false;
  854. if (_allowFlowHashing) {
  855. _paths[i].p->address().toString(pathStr);
  856. log("link %s/%s was bonded, flow reallocation will occur soon", getLink(_paths[i].p)->ifname().c_str(), pathStr);
  857. rebuildBond = true;
  858. _paths[i].shouldReallocateFlows = _paths[i].bonded;
  859. }
  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].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) {
  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. if (! _paths[idx].eligible) {
  954. continue;
  955. }
  956. addPathToBond(idx, updatedBondedPathCount);
  957. ++updatedBondedPathCount;
  958. _paths[idx].p->address().toString(pathStr);
  959. log("add path %s/%s (user addr preference %d)", link->ifname().c_str(), pathStr, ipvPref);
  960. }
  961. }
  962. // If the users prefers one address type to another, try to find at least
  963. // one path of that type before considering others.
  964. if (ipvPref == 46 || ipvPref == 64) {
  965. bool foundPreferredPath = false;
  966. // Search for preferred paths
  967. for (int j = 0; j < it->second.size(); j++) {
  968. int idx = it->second.at(j);
  969. if (! _paths[idx].p || ! _paths[idx].eligible) {
  970. continue;
  971. }
  972. if (_paths[idx].preferred() && _paths[idx].allowed()) {
  973. addPathToBond(idx, updatedBondedPathCount);
  974. ++updatedBondedPathCount;
  975. _paths[idx].p->address().toString(pathStr);
  976. log("add %s/%s (user addr preference %d)", link->ifname().c_str(), pathStr, ipvPref);
  977. foundPreferredPath = true;
  978. }
  979. }
  980. // Unable to find a path that matches user preference, settle for another address type
  981. if (! foundPreferredPath) {
  982. log("did not find first-choice path type on link %s (user preference %d)", link->ifname().c_str(), ipvPref);
  983. for (int j = 0; j < it->second.size(); j++) {
  984. int idx = it->second.at(j);
  985. if (! _paths[idx].p || ! _paths[idx].eligible) {
  986. continue;
  987. }
  988. addPathToBond(idx, updatedBondedPathCount);
  989. ++updatedBondedPathCount;
  990. _paths[idx].p->address().toString(pathStr);
  991. log("add %s/%s (user addr preference %d)", link->ifname().c_str(), pathStr, ipvPref);
  992. foundPreferredPath = true;
  993. }
  994. }
  995. }
  996. ++it; // Next link
  997. }
  998. _numBondedPaths = updatedBondedPathCount;
  999. if (_policy == ZT_BOND_POLICY_BALANCE_RR) {
  1000. // Cause a RR reset since the current index might no longer be valid
  1001. _rrPacketsSentOnCurrLink = _packetsPerLink;
  1002. }
  1003. }
  1004. }
  1005. }
  1006. void Bond::estimatePathQuality(int64_t now)
  1007. {
  1008. uint32_t totUserSpecifiedLinkSpeed = 0;
  1009. if (_numBondedPaths) { // Compute relative user-specified speeds of links
  1010. for (unsigned int i = 0; i < _numBondedPaths; ++i) {
  1011. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1012. if (_paths[i].p && _paths[i].allowed()) {
  1013. totUserSpecifiedLinkSpeed += link->speed();
  1014. }
  1015. }
  1016. for (unsigned int i = 0; i < _numBondedPaths; ++i) {
  1017. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1018. if (_paths[i].p && _paths[i].allowed()) {
  1019. link->setRelativeSpeed((uint8_t)round(((float)link->speed() / (float)totUserSpecifiedLinkSpeed) * 255));
  1020. }
  1021. }
  1022. }
  1023. float lat[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  1024. float pdv[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  1025. float plr[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  1026. float per[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  1027. float maxLAT = 0;
  1028. float maxPDV = 0;
  1029. float maxPLR = 0;
  1030. float maxPER = 0;
  1031. float quality[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  1032. uint8_t alloc[ZT_MAX_PEER_NETWORK_PATHS] = { 0 };
  1033. float totQuality = 0.0f;
  1034. // Compute initial summary statistics
  1035. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1036. if (! _paths[i].p || ! _paths[i].allowed()) {
  1037. continue;
  1038. }
  1039. // Compute/Smooth average of real-world observations
  1040. _paths[i].latencyMean = _paths[i].latencySamples.mean();
  1041. _paths[i].latencyVariance = _paths[i].latencySamples.stddev();
  1042. _paths[i].packetErrorRatio = 1.0 - (_paths[i].packetValiditySamples.count() ? _paths[i].packetValiditySamples.mean() : 1.0);
  1043. if (userHasSpecifiedLinkSpeeds()) {
  1044. // Use user-reported metrics
  1045. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1046. if (link) {
  1047. _paths[i].throughputMean = link->speed();
  1048. _paths[i].throughputVariance = 0;
  1049. }
  1050. }
  1051. // Drain unacknowledged QoS records
  1052. std::map<uint64_t, uint64_t>::iterator it = _paths[i].qosStatsOut.begin();
  1053. uint64_t currentLostRecords = 0;
  1054. while (it != _paths[i].qosStatsOut.end()) {
  1055. int qosRecordTimeout = 5000; //_paths[i].p->monitorInterval() * ZT_BOND_QOS_ACK_INTERVAL_MULTIPLIER * 8;
  1056. if ((now - it->second) >= qosRecordTimeout) {
  1057. // Packet was lost
  1058. it = _paths[i].qosStatsOut.erase(it);
  1059. ++currentLostRecords;
  1060. }
  1061. else {
  1062. ++it;
  1063. }
  1064. }
  1065. quality[i] = 0;
  1066. totQuality = 0;
  1067. // Normalize raw observations according to sane limits and/or user specified values
  1068. lat[i] = 1.0 / expf(4 * Utils::normalize(_paths[i].latencyMean, 0, _maxAcceptableLatency, 0, 1));
  1069. pdv[i] = 1.0 / expf(4 * Utils::normalize(_paths[i].latencyVariance, 0, _maxAcceptablePacketDelayVariance, 0, 1));
  1070. plr[i] = 1.0 / expf(4 * Utils::normalize(_paths[i].packetLossRatio, 0, _maxAcceptablePacketLossRatio, 0, 1));
  1071. per[i] = 1.0 / expf(4 * Utils::normalize(_paths[i].packetErrorRatio, 0, _maxAcceptablePacketErrorRatio, 0, 1));
  1072. // Record bond-wide maximums to determine relative values
  1073. maxLAT = lat[i] > maxLAT ? lat[i] : maxLAT;
  1074. maxPDV = pdv[i] > maxPDV ? pdv[i] : maxPDV;
  1075. maxPLR = plr[i] > maxPLR ? plr[i] : maxPLR;
  1076. maxPER = per[i] > maxPER ? per[i] : maxPER;
  1077. }
  1078. // Convert metrics to relative quantities and apply contribution weights
  1079. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1080. if (_paths[i].p && _paths[i].bonded) {
  1081. quality[i] += ((maxLAT > 0.0f ? lat[i] / maxLAT : 0.0f) * _qw[ZT_QOS_LAT_IDX]);
  1082. quality[i] += ((maxPDV > 0.0f ? pdv[i] / maxPDV : 0.0f) * _qw[ZT_QOS_PDV_IDX]);
  1083. quality[i] += ((maxPLR > 0.0f ? plr[i] / maxPLR : 0.0f) * _qw[ZT_QOS_PLR_IDX]);
  1084. quality[i] += ((maxPER > 0.0f ? per[i] / maxPER : 0.0f) * _qw[ZT_QOS_PER_IDX]);
  1085. totQuality += quality[i];
  1086. }
  1087. }
  1088. // Normalize to 8-bit allocation values
  1089. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1090. if (_paths[i].p && _paths[i].bonded) {
  1091. alloc[i] = (uint8_t)(std::ceil((quality[i] / totQuality) * (float)255));
  1092. _paths[i].allocation = alloc[i];
  1093. }
  1094. }
  1095. }
  1096. void Bond::processBalanceTasks(int64_t now)
  1097. {
  1098. char pathStr[64] = { 0 };
  1099. if (_allowFlowHashing) {
  1100. /**
  1101. * Clean up and reset flows if necessary
  1102. */
  1103. if ((now - _lastFlowExpirationCheck) > ZT_PEER_PATH_EXPIRATION) {
  1104. Mutex::Lock _l(_flows_m);
  1105. forgetFlowsWhenNecessary(ZT_PEER_PATH_EXPIRATION, false, now);
  1106. std::map<int32_t, SharedPtr<Flow> >::iterator it = _flows.begin();
  1107. while (it != _flows.end()) {
  1108. it->second->resetByteCounts();
  1109. ++it;
  1110. }
  1111. _lastFlowExpirationCheck = now;
  1112. }
  1113. /**
  1114. * Re-allocate flows from dead paths
  1115. */
  1116. if (_policy == ZT_BOND_POLICY_BALANCE_XOR || _policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  1117. Mutex::Lock _l(_flows_m);
  1118. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1119. if (! _paths[i].p) {
  1120. continue;
  1121. }
  1122. if (! _paths[i].eligible && _paths[i].shouldReallocateFlows) {
  1123. _paths[i].p->address().toString(pathStr);
  1124. log("reallocate flows from dead link %s/%s", getLink(_paths[i].p)->ifname().c_str(), pathStr);
  1125. std::map<int32_t, SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1126. while (flow_it != _flows.end()) {
  1127. if (_paths[flow_it->second->assignedPath].p == _paths[i].p) {
  1128. if (assignFlowToBondedPath(flow_it->second, now)) {
  1129. _paths[i].assignedFlowCount--;
  1130. }
  1131. }
  1132. ++flow_it;
  1133. }
  1134. _paths[i].shouldReallocateFlows = false;
  1135. }
  1136. }
  1137. }
  1138. /**
  1139. * Re-allocate flows from under-performing
  1140. * NOTE: This could be part of the above block but was kept separate for clarity.
  1141. */
  1142. if (_policy == ZT_BOND_POLICY_BALANCE_AWARE) {
  1143. int totalAllocation = 0;
  1144. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1145. if (! _paths[i].p) {
  1146. continue;
  1147. }
  1148. if (_paths[i].p && _paths[i].bonded && _paths[i].eligible) {
  1149. totalAllocation += _paths[i].allocation;
  1150. }
  1151. }
  1152. unsigned char minimumAllocationValue = (uint8_t)(0.33 * ((float)totalAllocation / (float)_numBondedPaths));
  1153. Mutex::Lock _l(_flows_m);
  1154. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1155. if (! _paths[i].p) {
  1156. continue;
  1157. }
  1158. if (_paths[i].p && _paths[i].bonded && _paths[i].eligible && (_paths[i].allocation < minimumAllocationValue) && _paths[i].assignedFlowCount) {
  1159. _paths[i].p->address().toString(pathStr);
  1160. log("reallocate flows from under-performing link %s/%s\n", getLink(_paths[i].p)->ifname().c_str(), pathStr);
  1161. std::map<int32_t, SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1162. while (flow_it != _flows.end()) {
  1163. if (flow_it->second->assignedPath == _paths[i].p) {
  1164. if (assignFlowToBondedPath(flow_it->second, now)) {
  1165. _paths[i].assignedFlowCount--;
  1166. }
  1167. }
  1168. ++flow_it;
  1169. }
  1170. _paths[i].shouldReallocateFlows = false;
  1171. }
  1172. }
  1173. }
  1174. }
  1175. }
  1176. void Bond::dequeueNextActiveBackupPath(uint64_t now)
  1177. {
  1178. if (_abFailoverQueue.empty()) {
  1179. return;
  1180. }
  1181. _abPathIdx = _abFailoverQueue.front();
  1182. _abFailoverQueue.pop_front();
  1183. _lastActiveBackupPathChange = now;
  1184. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1185. if (_paths[i].p) {
  1186. _paths[i].resetPacketCounts();
  1187. }
  1188. }
  1189. }
  1190. bool Bond::abForciblyRotateLink()
  1191. {
  1192. char prevPathStr[64];
  1193. char curPathStr[64];
  1194. if (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP) {
  1195. int prevPathIdx = _abPathIdx;
  1196. _paths[_abPathIdx].p->address().toString(prevPathStr);
  1197. dequeueNextActiveBackupPath(RR->node->now());
  1198. _paths[_abPathIdx].p->address().toString(curPathStr);
  1199. 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);
  1200. return true;
  1201. }
  1202. return false;
  1203. }
  1204. void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
  1205. {
  1206. char pathStr[64] = { 0 };
  1207. char prevPathStr[64];
  1208. char curPathStr[64];
  1209. int prevActiveBackupPathIdx = _abPathIdx;
  1210. int nonPreferredPathIdx;
  1211. bool bFoundPrimaryLink = false;
  1212. /**
  1213. * Generate periodic status report
  1214. */
  1215. if ((now - _lastBondStatusLog) > ZT_BOND_STATUS_INTERVAL) {
  1216. _lastBondStatusLog = now;
  1217. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1218. log("no active link");
  1219. }
  1220. else if (_paths[_abPathIdx].p) {
  1221. _paths[_abPathIdx].p->address().toString(curPathStr);
  1222. log("active link is %s/%s, failover queue size is %zu", getLink(_paths[_abPathIdx].p)->ifname().c_str(), curPathStr, _abFailoverQueue.size());
  1223. }
  1224. if (_abFailoverQueue.empty()) {
  1225. log("failover queue is empty, no longer fault-tolerant");
  1226. }
  1227. }
  1228. /**
  1229. * Select initial "active" active-backup link
  1230. */
  1231. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1232. /**
  1233. * [Automatic mode]
  1234. * The user has not explicitly specified links or their failover schedule,
  1235. * the bonding policy will now select the first eligible path and set it as
  1236. * its active backup path, if a substantially better path is detected the bonding
  1237. * policy will assign it as the new active backup path. If the path fails it will
  1238. * simply find the next eligible path.
  1239. */
  1240. if (! userHasSpecifiedLinks()) {
  1241. log("no user-specified links");
  1242. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1243. if (_paths[i].p && _paths[i].eligible) {
  1244. _paths[i].p->address().toString(curPathStr);
  1245. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1246. if (link) {
  1247. log("found eligible link %s/%s", getLink(_paths[i].p)->ifname().c_str(), curPathStr);
  1248. _abPathIdx = i;
  1249. break;
  1250. }
  1251. }
  1252. }
  1253. }
  1254. /**
  1255. * [Manual mode]
  1256. * The user has specified links or failover rules that the bonding policy should adhere to.
  1257. */
  1258. else if (userHasSpecifiedLinks()) {
  1259. if (userHasSpecifiedPrimaryLink()) {
  1260. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1261. if (! _paths[i].p) {
  1262. continue;
  1263. }
  1264. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1265. if (_paths[i].eligible && link->primary()) {
  1266. if (! _paths[i].preferred()) {
  1267. _paths[i].p->address().toString(curPathStr);
  1268. // Found path on primary link, take note in case we don't find a preferred path
  1269. nonPreferredPathIdx = i;
  1270. bFoundPrimaryLink = true;
  1271. }
  1272. if (_paths[i].preferred()) {
  1273. _abPathIdx = i;
  1274. _paths[_abPathIdx].p->address().toString(curPathStr);
  1275. bFoundPrimaryLink = true;
  1276. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[_abPathIdx].p->localSocket());
  1277. if (link) {
  1278. log("found preferred primary link %s/%s", getLink(_paths[_abPathIdx].p)->ifname().c_str(), curPathStr);
  1279. }
  1280. break; // Found preferred path on primary link
  1281. }
  1282. }
  1283. }
  1284. if (bFoundPrimaryLink && nonPreferredPathIdx) {
  1285. log("found non-preferred primary link");
  1286. _abPathIdx = nonPreferredPathIdx;
  1287. }
  1288. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1289. log("user-designated primary link is not yet ready");
  1290. // TODO: Should wait for some time (failover interval?) and then switch to spare link
  1291. }
  1292. }
  1293. else if (! userHasSpecifiedPrimaryLink()) {
  1294. log("user did not specify a primary link, select first available link");
  1295. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1296. if (_paths[i].p && _paths[i].eligible) {
  1297. _abPathIdx = i;
  1298. break;
  1299. }
  1300. }
  1301. if (_abPathIdx != ZT_MAX_PEER_NETWORK_PATHS) {
  1302. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[_abPathIdx].p->localSocket());
  1303. if (link) {
  1304. _paths[_abPathIdx].p->address().toString(curPathStr);
  1305. log("select non-primary link %s/%s", getLink(_paths[_abPathIdx].p)->ifname().c_str(), curPathStr);
  1306. }
  1307. }
  1308. }
  1309. }
  1310. }
  1311. // Short-circuit if we don't have an active link yet
  1312. if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1313. return;
  1314. }
  1315. // Remove ineligible paths from the failover link queue
  1316. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end();) {
  1317. if (_paths[(*it)].p && ! _paths[(*it)].eligible) {
  1318. _paths[(*it)].p->address().toString(curPathStr);
  1319. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[(*it)].p->localSocket());
  1320. it = _abFailoverQueue.erase(it);
  1321. if (link) {
  1322. 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());
  1323. }
  1324. }
  1325. else {
  1326. ++it;
  1327. }
  1328. }
  1329. /**
  1330. * Failover instructions were provided by user, build queue according those as well as IPv
  1331. * preference, disregarding performance.
  1332. */
  1333. if (userHasSpecifiedFailoverInstructions()) {
  1334. /**
  1335. * Clear failover scores
  1336. */
  1337. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1338. if (_paths[i].p) {
  1339. _paths[i].failoverScore = 0;
  1340. }
  1341. }
  1342. // Follow user-specified failover instructions
  1343. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1344. if (! _paths[i].p || ! _paths[i].allowed() || ! _paths[i].eligible) {
  1345. continue;
  1346. }
  1347. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i].p->localSocket());
  1348. _paths[i].p->address().toString(pathStr);
  1349. int failoverScoreHandicap = _paths[i].failoverScore;
  1350. if (_paths[i].preferred()) {
  1351. failoverScoreHandicap += ZT_BOND_FAILOVER_HANDICAP_PREFERRED;
  1352. }
  1353. if (link->primary()) {
  1354. // If using "optimize" primary re-select mode, ignore user link designations
  1355. failoverScoreHandicap += ZT_BOND_FAILOVER_HANDICAP_PRIMARY;
  1356. }
  1357. if (! _paths[i].failoverScore) {
  1358. // If we didn't inherit a failover score from a "parent" that wants to use this path as a failover
  1359. int newHandicap = failoverScoreHandicap ? failoverScoreHandicap : _paths[i].allocation;
  1360. _paths[i].failoverScore = newHandicap;
  1361. }
  1362. SharedPtr<Link> failoverLink;
  1363. if (link->failoverToLink().length()) {
  1364. failoverLink = RR->bc->getLinkByName(_policyAlias, link->failoverToLink());
  1365. }
  1366. if (failoverLink) {
  1367. for (int j = 0; j < ZT_MAX_PEER_NETWORK_PATHS; j++) {
  1368. if (_paths[j].p && getLink(_paths[j].p) == failoverLink.ptr()) {
  1369. _paths[j].p->address().toString(pathStr);
  1370. int inheritedHandicap = failoverScoreHandicap - 10;
  1371. int newHandicap = _paths[j].failoverScore > inheritedHandicap ? _paths[j].failoverScore : inheritedHandicap;
  1372. if (! _paths[j].preferred()) {
  1373. newHandicap--;
  1374. }
  1375. _paths[j].failoverScore = newHandicap;
  1376. }
  1377. }
  1378. }
  1379. if (_paths[i].p.ptr() != _paths[_abPathIdx].p.ptr()) {
  1380. bool bFoundPathInQueue = false;
  1381. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end(); ++it) {
  1382. if (_paths[i].p.ptr() == _paths[(*it)].p.ptr()) {
  1383. bFoundPathInQueue = true;
  1384. }
  1385. }
  1386. if (! bFoundPathInQueue) {
  1387. _abFailoverQueue.push_front(i);
  1388. _paths[i].p->address().toString(curPathStr);
  1389. log("add link %s/%s to failover queue (%zu links in queue)", getLink(_paths[_abPathIdx].p)->ifname().c_str(), curPathStr, _abFailoverQueue.size());
  1390. addPathToBond(0, i);
  1391. }
  1392. }
  1393. }
  1394. }
  1395. /**
  1396. * No failover instructions provided by user, build queue according to performance
  1397. * and IPv preference.
  1398. */
  1399. else if (! userHasSpecifiedFailoverInstructions()) {
  1400. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1401. if (! _paths[i].p || ! _paths[i].allowed() || ! _paths[i].eligible) {
  1402. continue;
  1403. }
  1404. int failoverScoreHandicap = 0;
  1405. if (_paths[i].preferred()) {
  1406. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_PREFERRED;
  1407. }
  1408. if (! _paths[i].eligible) {
  1409. failoverScoreHandicap = -10000;
  1410. }
  1411. if (getLink(_paths[i].p)->primary() && _abLinkSelectMethod != ZT_BOND_RESELECTION_POLICY_OPTIMIZE) {
  1412. // If using "optimize" primary re-select mode, ignore user link designations
  1413. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_PRIMARY;
  1414. }
  1415. if (_paths[i].p.ptr() == _paths[negotiatedPathIdx].p.ptr()) {
  1416. _paths[i].negotiated = true;
  1417. failoverScoreHandicap = ZT_BOND_FAILOVER_HANDICAP_NEGOTIATED;
  1418. }
  1419. else {
  1420. _paths[i].negotiated = false;
  1421. }
  1422. _paths[i].failoverScore = _paths[i].allocation + failoverScoreHandicap;
  1423. if (_paths[i].p.ptr() != _paths[_abPathIdx].p.ptr()) {
  1424. bool bFoundPathInQueue = false;
  1425. for (std::deque<int>::iterator it(_abFailoverQueue.begin()); it != _abFailoverQueue.end(); ++it) {
  1426. if (_paths[i].p.ptr() == _paths[(*it)].p.ptr()) {
  1427. bFoundPathInQueue = true;
  1428. }
  1429. }
  1430. if (! bFoundPathInQueue) {
  1431. _abFailoverQueue.push_front(i);
  1432. _paths[i].p->address().toString(curPathStr);
  1433. log("add link %s/%s to failover queue (%zu links in queue)", getLink(_paths[i].p)->ifname().c_str(), curPathStr, _abFailoverQueue.size());
  1434. addPathToBond(0, i);
  1435. }
  1436. }
  1437. }
  1438. }
  1439. // Sort queue based on performance
  1440. if (! _abFailoverQueue.empty()) {
  1441. for (int i = 0; i < _abFailoverQueue.size(); i++) {
  1442. int value_to_insert = _abFailoverQueue[i];
  1443. int hole_position = i;
  1444. while (hole_position > 0 && (_abFailoverQueue[hole_position - 1] > value_to_insert)) {
  1445. _abFailoverQueue[hole_position] = _abFailoverQueue[hole_position - 1];
  1446. hole_position = hole_position - 1;
  1447. }
  1448. _abFailoverQueue[hole_position] = value_to_insert;
  1449. }
  1450. }
  1451. /**
  1452. * Short-circuit if we have no queued paths
  1453. */
  1454. if (_abFailoverQueue.empty()) {
  1455. return;
  1456. }
  1457. /**
  1458. * Fulfill primary re-select obligations
  1459. */
  1460. if (_paths[_abPathIdx].p && ! _paths[_abPathIdx].eligible) { // Implicit ZT_BOND_RESELECTION_POLICY_FAILURE
  1461. _paths[_abPathIdx].p->address().toString(curPathStr);
  1462. 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());
  1463. if (! _abFailoverQueue.empty()) {
  1464. dequeueNextActiveBackupPath(now);
  1465. _paths[_abPathIdx].p->address().toString(curPathStr);
  1466. log("active link switched to %s/%s", getLink(_paths[_abPathIdx].p)->ifname().c_str(), curPathStr);
  1467. }
  1468. else {
  1469. log("failover queue is empty, no links to choose from");
  1470. }
  1471. }
  1472. /**
  1473. * Detect change to prevent flopping during later optimization step.
  1474. */
  1475. if (prevActiveBackupPathIdx != _abPathIdx) {
  1476. _lastActiveBackupPathChange = now;
  1477. }
  1478. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_ALWAYS) {
  1479. if (_paths[_abPathIdx].p && ! getLink(_paths[_abPathIdx].p)->primary() && getLink(_paths[_abFailoverQueue.front()].p)->primary()) {
  1480. dequeueNextActiveBackupPath(now);
  1481. _paths[_abPathIdx].p->address().toString(curPathStr);
  1482. log("switch back to available primary link %s/%s (select: always)", getLink(_paths[_abPathIdx].p)->ifname().c_str(), curPathStr);
  1483. }
  1484. }
  1485. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_BETTER) {
  1486. if (_paths[_abPathIdx].p && ! getLink(_paths[_abPathIdx].p)->primary()) {
  1487. // Active backup has switched to "better" primary link according to re-select policy.
  1488. if (getLink(_paths[_abFailoverQueue.front()].p)->primary() && (_paths[_abFailoverQueue.front()].failoverScore > _paths[_abPathIdx].failoverScore)) {
  1489. dequeueNextActiveBackupPath(now);
  1490. _paths[_abPathIdx].p->address().toString(curPathStr);
  1491. log("switch back to user-defined primary link %s/%s (select: better)", getLink(_paths[_abPathIdx].p)->ifname().c_str(), curPathStr);
  1492. }
  1493. }
  1494. }
  1495. if (_abLinkSelectMethod == ZT_BOND_RESELECTION_POLICY_OPTIMIZE && ! _abFailoverQueue.empty()) {
  1496. /**
  1497. * Implement link negotiation that was previously-decided
  1498. */
  1499. if (_paths[_abFailoverQueue.front()].negotiated) {
  1500. dequeueNextActiveBackupPath(now);
  1501. _paths[_abPathIdx].p->address().toString(prevPathStr);
  1502. _lastPathNegotiationCheck = now;
  1503. _paths[_abPathIdx].p->address().toString(curPathStr);
  1504. log("switch negotiated link %s/%s (select: optimize)", getLink(_paths[_abPathIdx].p)->ifname().c_str(), curPathStr);
  1505. }
  1506. else {
  1507. // Try to find a better path and automatically switch to it -- not too often, though.
  1508. if ((now - _lastActiveBackupPathChange) > ZT_BOND_OPTIMIZE_INTERVAL) {
  1509. if (! _abFailoverQueue.empty()) {
  1510. int newFScore = _paths[_abFailoverQueue.front()].failoverScore;
  1511. int prevFScore = _paths[_abPathIdx].failoverScore;
  1512. // Establish a minimum switch threshold to prevent flapping
  1513. int failoverScoreDifference = _paths[_abFailoverQueue.front()].failoverScore - _paths[_abPathIdx].failoverScore;
  1514. int thresholdQuantity = (int)(ZT_BOND_ACTIVE_BACKUP_OPTIMIZE_MIN_THRESHOLD * (float)_paths[_abPathIdx].allocation);
  1515. if ((failoverScoreDifference > 0) && (failoverScoreDifference > thresholdQuantity)) {
  1516. SharedPtr<Path> oldPath = _paths[_abPathIdx].p;
  1517. _paths[_abPathIdx].p->address().toString(prevPathStr);
  1518. dequeueNextActiveBackupPath(now);
  1519. _paths[_abPathIdx].p->address().toString(curPathStr);
  1520. log("ab",
  1521. "switch from %s/%s (score: %d) to better link %s/%s (score: %d) for peer %llx (select: optimize)",
  1522. getLink(oldPath)->ifname().c_str(),
  1523. prevPathStr,
  1524. prevFScore,
  1525. getLink(_paths[_abPathIdx].p)->ifname().c_str(),
  1526. curPathStr,
  1527. newFScore,
  1528. _peerId);
  1529. }
  1530. }
  1531. }
  1532. }
  1533. }
  1534. }
  1535. void Bond::setBondParameters(int policy, SharedPtr<Bond> templateBond, bool useTemplate)
  1536. {
  1537. // Sanity check for policy
  1538. _defaultPolicy = (_defaultPolicy <= ZT_BOND_POLICY_NONE || _defaultPolicy > ZT_BOND_POLICY_BALANCE_AWARE) ? ZT_BOND_POLICY_NONE : _defaultPolicy;
  1539. _policy = (policy <= ZT_BOND_POLICY_NONE || policy > ZT_BOND_POLICY_BALANCE_AWARE) ? ZT_BOND_POLICY_NONE : _defaultPolicy;
  1540. // Flows
  1541. _lastFlowExpirationCheck = 0;
  1542. _lastFlowRebalance = 0;
  1543. _allowFlowHashing = false;
  1544. // Path negotiation
  1545. _lastSentPathNegotiationRequest = 0;
  1546. _lastPathNegotiationCheck = 0;
  1547. _allowPathNegotiation = false;
  1548. _pathNegotiationCutoffCount = 0;
  1549. _lastPathNegotiationReceived = 0;
  1550. _localUtility = 0;
  1551. // QOS Verb (and related checks)
  1552. _qosCutoffCount = 0;
  1553. _lastQoSRateCheck = 0;
  1554. _lastQualityEstimation = 0;
  1555. // User preferences which may override the default bonding algorithm's behavior
  1556. _userHasSpecifiedPrimaryLink = false;
  1557. _userHasSpecifiedFailoverInstructions = false;
  1558. _userHasSpecifiedLinkSpeeds = 0;
  1559. // Bond status
  1560. _lastBondStatusLog = 0;
  1561. _lastSummaryDump = 0;
  1562. _isHealthy = false;
  1563. _numAliveLinks = 0;
  1564. _numTotalLinks = 0;
  1565. _numBondedPaths = 0;
  1566. // active-backup
  1567. _lastActiveBackupPathChange = 0;
  1568. _abPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1569. // rr
  1570. _rrPacketsSentOnCurrLink = 0;
  1571. _rrIdx = 0;
  1572. // General parameters
  1573. _downDelay = 0;
  1574. _upDelay = 0;
  1575. _monitorInterval = 0;
  1576. // (Sane?) limits
  1577. _maxAcceptableLatency = 100;
  1578. _maxAcceptablePacketDelayVariance = 50;
  1579. _maxAcceptablePacketLossRatio = 0.10f;
  1580. _maxAcceptablePacketErrorRatio = 0.10f;
  1581. // General timers
  1582. _lastFrame = 0;
  1583. _lastBackgroundTaskCheck = 0;
  1584. // balance-aware
  1585. _totalBondUnderload = 0;
  1586. _overheadBytes = 0;
  1587. /**
  1588. * Policy-specific defaults
  1589. */
  1590. switch (_policy) {
  1591. case ZT_BOND_POLICY_ACTIVE_BACKUP:
  1592. _abLinkSelectMethod = ZT_BOND_RESELECTION_POLICY_OPTIMIZE;
  1593. break;
  1594. case ZT_BOND_POLICY_BROADCAST:
  1595. _downDelay = 30000;
  1596. _upDelay = 0;
  1597. break;
  1598. case ZT_BOND_POLICY_BALANCE_RR:
  1599. _packetsPerLink = 64;
  1600. break;
  1601. case ZT_BOND_POLICY_BALANCE_XOR:
  1602. _allowFlowHashing = true;
  1603. break;
  1604. case ZT_BOND_POLICY_BALANCE_AWARE:
  1605. _allowFlowHashing = true;
  1606. break;
  1607. default:
  1608. break;
  1609. }
  1610. _qw[ZT_QOS_LAT_IDX] = 0.3f;
  1611. _qw[ZT_QOS_LTM_IDX] = 0.1f;
  1612. _qw[ZT_QOS_PDV_IDX] = 0.3f;
  1613. _qw[ZT_QOS_PLR_IDX] = 0.1f;
  1614. _qw[ZT_QOS_PER_IDX] = 0.1f;
  1615. _qw[ZT_QOS_SCP_IDX] = 0.1f;
  1616. _failoverInterval = ZT_BOND_FAILOVER_DEFAULT_INTERVAL;
  1617. /* If a user has specified custom parameters for this bonding policy, overlay them onto the defaults */
  1618. if (useTemplate) {
  1619. _policyAlias = templateBond->_policyAlias;
  1620. _failoverInterval = templateBond->_failoverInterval >= ZT_BOND_FAILOVER_MIN_INTERVAL ? templateBond->_failoverInterval : ZT_BOND_FAILOVER_MIN_INTERVAL;
  1621. _downDelay = templateBond->_downDelay;
  1622. _upDelay = templateBond->_upDelay;
  1623. _abLinkSelectMethod = templateBond->_abLinkSelectMethod;
  1624. memcpy(_qw, templateBond->_qw, ZT_QOS_WEIGHT_SIZE * sizeof(float));
  1625. }
  1626. // Timer geometry
  1627. _monitorInterval = _failoverInterval / ZT_BOND_ECHOS_PER_FAILOVER_INTERVAL;
  1628. _qualityEstimationInterval = _failoverInterval * 2;
  1629. _qosSendInterval = _failoverInterval * 2;
  1630. _qosCutoffCount = 0;
  1631. _defaultPathRefractoryPeriod = 8000;
  1632. }
  1633. void Bond::setUserQualityWeights(float weights[], int len)
  1634. {
  1635. if (len == ZT_QOS_WEIGHT_SIZE) {
  1636. float weightTotal = 0.0;
  1637. for (unsigned int i = 0; i < ZT_QOS_WEIGHT_SIZE; ++i) {
  1638. weightTotal += weights[i];
  1639. }
  1640. if (weightTotal > 0.99 && weightTotal < 1.01) {
  1641. memcpy(_qw, weights, len * sizeof(float));
  1642. }
  1643. }
  1644. }
  1645. SharedPtr<Link> Bond::getLink(const SharedPtr<Path>& path)
  1646. {
  1647. return RR->bc->getLinkBySocket(_policyAlias, path->localSocket());
  1648. }
  1649. void Bond::dumpPathStatus(int64_t now, int pathIdx)
  1650. {
  1651. char pathStr[64] = { 0 };
  1652. _paths[pathIdx].p->address().toString(pathStr);
  1653. 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)",
  1654. pathIdx,
  1655. _paths[pathIdx].alive,
  1656. _paths[pathIdx].eligible,
  1657. _paths[pathIdx].bonded,
  1658. _paths[pathIdx].assignedFlowCount,
  1659. _paths[pathIdx].latencyMean,
  1660. _paths[pathIdx].latencyVariance,
  1661. _paths[pathIdx].packetErrorRatio,
  1662. _paths[pathIdx].packetLossRatio,
  1663. _paths[pathIdx].p->age(now),
  1664. _paths[pathIdx].allocation,
  1665. getLink(_paths[pathIdx].p)->ifname().c_str(),
  1666. pathStr);
  1667. }
  1668. void Bond::dumpInfo(int64_t now, bool force)
  1669. {
  1670. uint64_t timeSinceLastDump = now - _lastSummaryDump;
  1671. if (! force && timeSinceLastDump < ZT_BOND_STATUS_INTERVAL) {
  1672. return;
  1673. }
  1674. _lastSummaryDump = now;
  1675. float overhead = (_overheadBytes / (timeSinceLastDump / 1000.0f) / 1000.0f);
  1676. _overheadBytes = 0;
  1677. 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);
  1678. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1679. if (_paths[i].p) {
  1680. dumpPathStatus(now, i);
  1681. }
  1682. }
  1683. }
  1684. } // namespace ZeroTier