Bond.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833
  1. /*
  2. * Copyright (c)2013-2020 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: 2025-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 <cmath>
  14. #include "../osdep/OSUtils.hpp"
  15. #include "Peer.hpp"
  16. #include "Bond.hpp"
  17. #include "Switch.hpp"
  18. #include "Flow.hpp"
  19. #include "Path.hpp"
  20. namespace ZeroTier {
  21. Bond::Bond(const RuntimeEnvironment *renv, int policy, const SharedPtr<Peer>& peer) :
  22. RR(renv),
  23. _peer(peer),
  24. _qosCutoffCount(0),
  25. _ackCutoffCount(0),
  26. _lastAckRateCheck(0),
  27. _lastQoSRateCheck(0),
  28. _lastQualityEstimation(0),
  29. _lastCheckUserPreferences(0),
  30. _lastBackgroundTaskCheck(0),
  31. _lastBondStatusLog(0),
  32. _lastPathNegotiationReceived(0),
  33. _lastPathNegotiationCheck(0),
  34. _lastSentPathNegotiationRequest(0),
  35. _lastFlowStatReset(0),
  36. _lastFlowExpirationCheck(0),
  37. _lastFlowRebalance(0),
  38. _lastFrame(0),
  39. _lastActiveBackupPathChange(0)
  40. {
  41. setReasonableDefaults(policy, SharedPtr<Bond>(), false);
  42. _policyAlias = BondController::getPolicyStrByCode(policy);
  43. }
  44. Bond::Bond(const RuntimeEnvironment *renv, std::string& basePolicy, std::string& policyAlias, const SharedPtr<Peer>& peer) :
  45. RR(renv),
  46. _policyAlias(policyAlias),
  47. _peer(peer)
  48. {
  49. setReasonableDefaults(BondController::getPolicyCodeByStr(basePolicy), SharedPtr<Bond>(), false);
  50. }
  51. Bond::Bond(const RuntimeEnvironment *renv, SharedPtr<Bond> originalBond, const SharedPtr<Peer>& peer) :
  52. RR(renv),
  53. _peer(peer),
  54. _lastAckRateCheck(0),
  55. _lastQoSRateCheck(0),
  56. _lastQualityEstimation(0),
  57. _lastCheckUserPreferences(0),
  58. _lastBackgroundTaskCheck(0),
  59. _lastBondStatusLog(0),
  60. _lastPathNegotiationReceived(0),
  61. _lastPathNegotiationCheck(0),
  62. _lastFlowStatReset(0),
  63. _lastFlowExpirationCheck(0),
  64. _lastFlowRebalance(0),
  65. _lastFrame(0)
  66. {
  67. setReasonableDefaults(originalBond->_bondingPolicy, originalBond, true);
  68. }
  69. void Bond::nominatePath(const SharedPtr<Path>& path, int64_t now)
  70. {
  71. char traceMsg[256]; char pathStr[128]; path->address().toString(pathStr);
  72. Mutex::Lock _l(_paths_m);
  73. if (!RR->bc->linkAllowed(_policyAlias, getLink(path))) {
  74. return;
  75. }
  76. bool alreadyPresent = false;
  77. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  78. if (path.ptr() == _paths[i].ptr()) {
  79. // Previously encountered path, not notifying bond
  80. alreadyPresent = true;
  81. break;
  82. }
  83. }
  84. if (!alreadyPresent) {
  85. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  86. if (!_paths[i]) {
  87. _paths[i] = path;
  88. sprintf(traceMsg, "%s (bond) Nominating link %s/%s to peer %llx. It has now entered its trial period",
  89. OSUtils::humanReadableTimestamp().c_str(), getLink(path)->ifname().c_str(), pathStr, _peer->_id.address().toInt());
  90. RR->t->bondStateMessage(NULL, traceMsg);
  91. _paths[i]->startTrial(now);
  92. break;
  93. }
  94. }
  95. }
  96. curateBond(now, true);
  97. estimatePathQuality(now);
  98. }
  99. SharedPtr<Path> Bond::getAppropriatePath(int64_t now, int32_t flowId)
  100. {
  101. Mutex::Lock _l(_paths_m);
  102. /**
  103. * active-backup
  104. */
  105. if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  106. if (_abPath) {
  107. return _abPath;
  108. }
  109. }
  110. /**
  111. * broadcast
  112. */
  113. if (_bondingPolicy == ZT_BONDING_POLICY_BROADCAST) {
  114. return SharedPtr<Path>(); // Handled in Switch::_trySend()
  115. }
  116. if (!_numBondedPaths) {
  117. return SharedPtr<Path>(); // No paths assigned to bond yet, cannot balance traffic
  118. }
  119. /**
  120. * balance-rr
  121. */
  122. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR) {
  123. if (!_allowFlowHashing) {
  124. if (_packetsPerLink == 0) {
  125. // Randomly select a path
  126. return _paths[_bondedIdx[_freeRandomByte % _numBondedPaths]]; // TODO: Optimize
  127. }
  128. if (_rrPacketsSentOnCurrLink < _packetsPerLink) {
  129. // Continue to use this link
  130. ++_rrPacketsSentOnCurrLink;
  131. return _paths[_bondedIdx[_rrIdx]];
  132. }
  133. // Reset striping counter
  134. _rrPacketsSentOnCurrLink = 0;
  135. if (_numBondedPaths == 1) {
  136. _rrIdx = 0;
  137. }
  138. else {
  139. int _tempIdx = _rrIdx;
  140. for (int searchCount = 0; searchCount < (_numBondedPaths-1); searchCount++) {
  141. _tempIdx = (_tempIdx == (_numBondedPaths-1)) ? 0 : _tempIdx+1;
  142. if (_bondedIdx[_tempIdx] != ZT_MAX_PEER_NETWORK_PATHS) {
  143. if (_paths[_bondedIdx[_tempIdx]] && _paths[_bondedIdx[_tempIdx]]->eligible(now,_ackSendInterval)) {
  144. _rrIdx = _tempIdx;
  145. break;
  146. }
  147. }
  148. }
  149. }
  150. if (_paths[_bondedIdx[_rrIdx]]) {
  151. return _paths[_bondedIdx[_rrIdx]];
  152. }
  153. }
  154. }
  155. /**
  156. * balance-xor
  157. */
  158. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  159. if (!_allowFlowHashing || flowId == -1) {
  160. // No specific path required for unclassified traffic, send on anything
  161. return _paths[_bondedIdx[_freeRandomByte % _numBondedPaths]]; // TODO: Optimize
  162. }
  163. else if (_allowFlowHashing) {
  164. // TODO: Optimize
  165. Mutex::Lock _l(_flows_m);
  166. SharedPtr<Flow> flow;
  167. if (_flows.count(flowId)) {
  168. flow = _flows[flowId];
  169. flow->updateActivity(now);
  170. }
  171. else {
  172. unsigned char entropy;
  173. Utils::getSecureRandom(&entropy, 1);
  174. flow = createFlow(SharedPtr<Path>(), flowId, entropy, now);
  175. }
  176. if (flow) {
  177. return flow->assignedPath();
  178. }
  179. }
  180. }
  181. return SharedPtr<Path>();
  182. }
  183. void Bond::recordIncomingInvalidPacket(const SharedPtr<Path>& path)
  184. {
  185. //char traceMsg[256]; char pathStr[128]; path->address().toString(pathStr);
  186. //sprintf(traceMsg, "%s (qos) Invalid packet on link %s/%s from peer %llx",
  187. // OSUtils::humanReadableTimestamp().c_str(), getLink(path)->ifname().c_str(), pathStr, _peer->_id.address().toInt());
  188. //RR->t->bondStateMessage(NULL, traceMsg);
  189. Mutex::Lock _l(_paths_m);
  190. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  191. if (_paths[i] == path) {
  192. _paths[i]->packetValiditySamples.push(false);
  193. }
  194. }
  195. }
  196. void Bond::recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  197. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  198. {
  199. //char traceMsg[256]; char pathStr[128]; path->address().toString(pathStr);
  200. //sprintf(traceMsg, "%s (bond) Outgoing packet on link %s/%s to peer %llx",
  201. // OSUtils::humanReadableTimestamp().c_str(), getLink(path)->ifname().c_str(), pathStr, _peer->_id.address().toInt());
  202. //RR->t->bondStateMessage(NULL, traceMsg);
  203. _freeRandomByte += (unsigned char)(packetId >> 8); // Grab entropy to use in path selection logic
  204. if (!_shouldCollectPathStatistics) {
  205. return;
  206. }
  207. bool isFrame = (verb == Packet::VERB_FRAME || verb == Packet::VERB_EXT_FRAME);
  208. bool shouldRecord = (packetId & (ZT_QOS_ACK_DIVISOR - 1)
  209. && (verb != Packet::VERB_ACK)
  210. && (verb != Packet::VERB_QOS_MEASUREMENT));
  211. if (isFrame || shouldRecord) {
  212. Mutex::Lock _l(_paths_m);
  213. if (isFrame) {
  214. ++(path->_packetsOut);
  215. _lastFrame=now;
  216. }
  217. if (shouldRecord) {
  218. path->_unackedBytes += payloadLength;
  219. // Take note that we're expecting a VERB_ACK on this path as of a specific time
  220. if (path->qosStatsOut.size() < ZT_QOS_MAX_OUTSTANDING_RECORDS) {
  221. path->qosStatsOut[packetId] = now;
  222. }
  223. }
  224. }
  225. if (_allowFlowHashing && (flowId != ZT_QOS_NO_FLOW)) {
  226. Mutex::Lock _l(_flows_m);
  227. if (_flows.count(flowId)) {
  228. _flows[flowId]->recordOutgoingBytes(payloadLength);
  229. }
  230. }
  231. }
  232. void Bond::recordIncomingPacket(const SharedPtr<Path>& path, uint64_t packetId, uint16_t payloadLength,
  233. Packet::Verb verb, int32_t flowId, int64_t now)
  234. {
  235. //char traceMsg[256]; char pathStr[128]; path->address().toString(pathStr);
  236. //sprintf(traceMsg, "%s (bond) Incoming packet on link %s/%s from peer %llx [id=%llx, len=%d, verb=%d, flowId=%x]",
  237. // OSUtils::humanReadableTimestamp().c_str(), getLink(path)->ifname().c_str(), pathStr, _peer->_id.address().toInt(), packetId, payloadLength, verb, flowId);
  238. //RR->t->bondStateMessage(NULL, traceMsg);
  239. bool isFrame = (verb == Packet::VERB_FRAME || verb == Packet::VERB_EXT_FRAME);
  240. bool shouldRecord = (packetId & (ZT_QOS_ACK_DIVISOR - 1)
  241. && (verb != Packet::VERB_ACK)
  242. && (verb != Packet::VERB_QOS_MEASUREMENT));
  243. if (isFrame || shouldRecord) {
  244. Mutex::Lock _l(_paths_m);
  245. if (isFrame) {
  246. ++(path->_packetsIn);
  247. _lastFrame=now;
  248. }
  249. if (shouldRecord) {
  250. path->ackStatsIn[packetId] = payloadLength;
  251. ++(path->_packetsReceivedSinceLastAck);
  252. path->qosStatsIn[packetId] = now;
  253. ++(path->_packetsReceivedSinceLastQoS);
  254. path->packetValiditySamples.push(true);
  255. }
  256. }
  257. /**
  258. * Learn new flows and pro-actively create entries for them in the bond so
  259. * that the next time we send a packet out that is part of a flow we know
  260. * which path to use.
  261. */
  262. if ((flowId != ZT_QOS_NO_FLOW)
  263. && (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR
  264. || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR
  265. || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE)) {
  266. Mutex::Lock _l(_flows_m);
  267. SharedPtr<Flow> flow;
  268. if (!_flows.count(flowId)) {
  269. flow = createFlow(path, flowId, 0, now);
  270. } else {
  271. flow = _flows[flowId];
  272. }
  273. if (flow) {
  274. flow->recordIncomingBytes(payloadLength);
  275. }
  276. }
  277. }
  278. void Bond::receivedQoS(const SharedPtr<Path>& path, int64_t now, int count, uint64_t *rx_id, uint16_t *rx_ts)
  279. {
  280. Mutex::Lock _l(_paths_m);
  281. //char traceMsg[256]; char pathStr[128]; path->address().toString(pathStr);
  282. //sprintf(traceMsg, "%s (qos) Received QoS packet sampling %d frames from peer %llx via %s/%s",
  283. // OSUtils::humanReadableTimestamp().c_str(), count, _peer->_id.address().toInt(), getLink(path)->ifname().c_str(), pathStr);
  284. //RR->t->bondStateMessage(NULL, traceMsg);
  285. // Look up egress times and compute latency values for each record
  286. std::map<uint64_t,uint64_t>::iterator it;
  287. for (int j=0; j<count; j++) {
  288. it = path->qosStatsOut.find(rx_id[j]);
  289. if (it != path->qosStatsOut.end()) {
  290. path->latencySamples.push(((uint16_t)(now - it->second) - rx_ts[j]) / 2);
  291. path->qosStatsOut.erase(it);
  292. }
  293. }
  294. path->qosRecordSize.push(count);
  295. }
  296. void Bond::receivedAck(const SharedPtr<Path>& path, int64_t now, int32_t ackedBytes)
  297. {
  298. Mutex::Lock _l(_paths_m);
  299. //char traceMsg[256]; char pathStr[128]; path->address().toString(pathStr);
  300. //sprintf(traceMsg, "%s (qos) Received ACK packet for %d bytes from peer %llx via %s/%s",
  301. // OSUtils::humanReadableTimestamp().c_str(), ackedBytes, _peer->_id.address().toInt(), getLink(path)->ifname().c_str(), pathStr);
  302. //RR->t->bondStateMessage(NULL, traceMsg);
  303. path->_lastAckReceived = now;
  304. path->_unackedBytes = (ackedBytes > path->_unackedBytes) ? 0 : path->_unackedBytes - ackedBytes;
  305. int64_t timeSinceThroughputEstimate = (now - path->_lastThroughputEstimation);
  306. if (timeSinceThroughputEstimate >= throughputMeasurementInterval) {
  307. // TODO: See if this floating point math can be reduced
  308. uint64_t throughput = (uint64_t)((float)(path->_bytesAckedSinceLastThroughputEstimation) / ((float)timeSinceThroughputEstimate / (float)1000));
  309. throughput /= 1000;
  310. if (throughput > 0.0) {
  311. path->throughputSamples.push(throughput);
  312. path->_throughputMax = throughput > path->_throughputMax ? throughput : path->_throughputMax;
  313. }
  314. path->_lastThroughputEstimation = now;
  315. path->_bytesAckedSinceLastThroughputEstimation = 0;
  316. } else {
  317. path->_bytesAckedSinceLastThroughputEstimation += ackedBytes;
  318. }
  319. }
  320. int32_t Bond::generateQoSPacket(const SharedPtr<Path>& path, int64_t now, char *qosBuffer)
  321. {
  322. int32_t len = 0;
  323. std::map<uint64_t,uint64_t>::iterator it = path->qosStatsIn.begin();
  324. int i=0;
  325. int numRecords = std::min(path->_packetsReceivedSinceLastQoS,ZT_QOS_TABLE_SIZE);
  326. while (i<numRecords && it != path->qosStatsIn.end()) {
  327. uint64_t id = it->first;
  328. memcpy(qosBuffer, &id, sizeof(uint64_t));
  329. qosBuffer+=sizeof(uint64_t);
  330. uint16_t holdingTime = (uint16_t)(now - it->second);
  331. memcpy(qosBuffer, &holdingTime, sizeof(uint16_t));
  332. qosBuffer+=sizeof(uint16_t);
  333. len+=sizeof(uint64_t)+sizeof(uint16_t);
  334. path->qosStatsIn.erase(it++);
  335. ++i;
  336. }
  337. return len;
  338. }
  339. bool Bond::assignFlowToBondedPath(SharedPtr<Flow> &flow, int64_t now)
  340. {
  341. char traceMsg[256];
  342. char curPathStr[128];
  343. unsigned int idx = ZT_MAX_PEER_NETWORK_PATHS;
  344. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR) {
  345. idx = abs((int)(flow->id() % (_numBondedPaths)));
  346. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[_bondedIdx[idx]]->localSocket());
  347. _paths[_bondedIdx[idx]]->address().toString(curPathStr);
  348. sprintf(traceMsg, "%s (balance-xor) Assigned outgoing flow %x to peer %llx to link %s/%s, %lu active flow(s)",
  349. OSUtils::humanReadableTimestamp().c_str(), flow->id(), _peer->_id.address().toInt(), link->ifname().c_str(), curPathStr, _flows.size());
  350. RR->t->bondStateMessage(NULL, traceMsg);
  351. flow->assignPath(_paths[_bondedIdx[idx]],now);
  352. ++(_paths[_bondedIdx[idx]]->_assignedFlowCount);
  353. }
  354. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  355. unsigned char entropy;
  356. Utils::getSecureRandom(&entropy, 1);
  357. if (_totalBondUnderload) {
  358. entropy %= _totalBondUnderload;
  359. }
  360. if (!_numBondedPaths) {
  361. sprintf(traceMsg, "%s (balance-aware) There are no bonded paths, cannot assign flow %x\n",
  362. OSUtils::humanReadableTimestamp().c_str(), flow->id());
  363. RR->t->bondStateMessage(NULL, traceMsg);
  364. return false;
  365. }
  366. /* Since there may be scenarios where a path is removed before we can re-estimate
  367. relative qualities (and thus allocations) we need to down-modulate the entropy
  368. value that we use to randomly assign among the surviving paths, otherwise we risk
  369. not being able to find a path to assign this flow to. */
  370. int totalIncompleteAllocation = 0;
  371. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  372. if (_paths[i] && _paths[i]->bonded()) {
  373. totalIncompleteAllocation += _paths[i]->_allocation;
  374. }
  375. }
  376. entropy %= totalIncompleteAllocation;
  377. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  378. if (_paths[i] && _paths[i]->bonded()) {
  379. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  380. _paths[i]->address().toString(curPathStr);
  381. uint8_t probabilitySegment = (_totalBondUnderload > 0) ? _paths[i]->_affinity : _paths[i]->_allocation;
  382. if (entropy <= probabilitySegment) {
  383. idx = i;
  384. break;
  385. }
  386. entropy -= probabilitySegment;
  387. }
  388. }
  389. if (idx < ZT_MAX_PEER_NETWORK_PATHS) {
  390. if (flow->_assignedPath) {
  391. flow->_previouslyAssignedPath = flow->_assignedPath;
  392. }
  393. flow->assignPath(_paths[idx],now);
  394. ++(_paths[idx]->_assignedFlowCount);
  395. }
  396. else {
  397. fprintf(stderr, "could not assign flow?\n"); exit(0); // TODO: Remove for production
  398. return false;
  399. }
  400. }
  401. if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  402. if (_abOverflowEnabled) {
  403. flow->assignPath(_abPath, now);
  404. } else {
  405. sprintf(traceMsg, "%s (bond) Unable to assign outgoing flow %x to peer %llx, no active overflow link",
  406. OSUtils::humanReadableTimestamp().c_str(), flow->id(), _peer->_id.address().toInt());
  407. RR->t->bondStateMessage(NULL, traceMsg);
  408. return false;
  409. }
  410. }
  411. flow->assignedPath()->address().toString(curPathStr);
  412. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, flow->assignedPath()->localSocket());
  413. sprintf(traceMsg, "%s (bond) Assigned outgoing flow %x to peer %llx to link %s/%s, %lu active flow(s)",
  414. OSUtils::humanReadableTimestamp().c_str(), flow->id(), _peer->_id.address().toInt(), link->ifname().c_str(), curPathStr, _flows.size());
  415. RR->t->bondStateMessage(NULL, traceMsg);
  416. return true;
  417. }
  418. SharedPtr<Flow> Bond::createFlow(const SharedPtr<Path> &path, int32_t flowId, unsigned char entropy, int64_t now)
  419. {
  420. char traceMsg[256];
  421. char curPathStr[128];
  422. // ---
  423. if (!_numBondedPaths) {
  424. sprintf(traceMsg, "%s (bond) There are no bonded paths to peer %llx, cannot assign flow %x\n",
  425. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), flowId);
  426. RR->t->bondStateMessage(NULL, traceMsg);
  427. return SharedPtr<Flow>();
  428. }
  429. if (_flows.size() >= ZT_FLOW_MAX_COUNT) {
  430. sprintf(traceMsg, "%s (bond) Maximum number of flows on bond to peer %llx reached (%d), forcibly forgetting oldest flow\n",
  431. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), ZT_FLOW_MAX_COUNT);
  432. RR->t->bondStateMessage(NULL, traceMsg);
  433. forgetFlowsWhenNecessary(0, true, now);
  434. }
  435. SharedPtr<Flow> flow = new Flow(flowId, now);
  436. _flows[flowId] = flow;
  437. /**
  438. * Add a flow with a given Path already provided. This is the case when a packet
  439. * is received on a path but no flow exists, in this case we simply assign the path
  440. * that the remote peer chose for us.
  441. */
  442. if (path) {
  443. flow->assignPath(path,now);
  444. path->address().toString(curPathStr);
  445. path->_assignedFlowCount++;
  446. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, flow->assignedPath()->localSocket());
  447. sprintf(traceMsg, "%s (bond) Assigned incoming flow %x from peer %llx to link %s/%s, %lu active flow(s)",
  448. OSUtils::humanReadableTimestamp().c_str(), flow->id(), _peer->_id.address().toInt(), link->ifname().c_str(), curPathStr, _flows.size());
  449. RR->t->bondStateMessage(NULL, traceMsg);
  450. }
  451. /**
  452. * Add a flow when no path was provided. This means that it is an outgoing packet
  453. * and that it is up to the local peer to decide how to load-balance its transmission.
  454. */
  455. else if (!path) {
  456. assignFlowToBondedPath(flow, now);
  457. }
  458. return flow;
  459. }
  460. void Bond::forgetFlowsWhenNecessary(uint64_t age, bool oldest, int64_t now)
  461. {
  462. char traceMsg[256];
  463. std::map<int32_t,SharedPtr<Flow> >::iterator it = _flows.begin();
  464. std::map<int32_t,SharedPtr<Flow> >::iterator oldestFlow = _flows.end();
  465. SharedPtr<Flow> expiredFlow;
  466. if (age) { // Remove by specific age
  467. while (it != _flows.end()) {
  468. if (it->second->age(now) > age) {
  469. sprintf(traceMsg, "%s (bond) Forgetting flow %x between this node and peer %llx, %lu active flow(s)",
  470. OSUtils::humanReadableTimestamp().c_str(), it->first, _peer->_id.address().toInt(), (_flows.size()-1));
  471. RR->t->bondStateMessage(NULL, traceMsg);
  472. it->second->assignedPath()->_assignedFlowCount--;
  473. it = _flows.erase(it);
  474. } else {
  475. ++it;
  476. }
  477. }
  478. }
  479. else if (oldest) { // Remove single oldest by natural expiration
  480. uint64_t maxAge = 0;
  481. while (it != _flows.end()) {
  482. if (it->second->age(now) > maxAge) {
  483. maxAge = (now - it->second->age(now));
  484. oldestFlow = it;
  485. }
  486. ++it;
  487. }
  488. if (oldestFlow != _flows.end()) {
  489. sprintf(traceMsg, "%s (bond) Forgetting oldest flow %x (of age %llu) between this node and peer %llx, %lu active flow(s)",
  490. OSUtils::humanReadableTimestamp().c_str(), oldestFlow->first, oldestFlow->second->age(now), _peer->_id.address().toInt(), (_flows.size()-1));
  491. RR->t->bondStateMessage(NULL, traceMsg);
  492. oldestFlow->second->assignedPath()->_assignedFlowCount--;
  493. _flows.erase(oldestFlow);
  494. }
  495. }
  496. }
  497. void Bond::processIncomingPathNegotiationRequest(uint64_t now, SharedPtr<Path> &path, int16_t remoteUtility)
  498. {
  499. char traceMsg[256];
  500. if (_abLinkSelectMethod != ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE) {
  501. return;
  502. }
  503. Mutex::Lock _l(_paths_m);
  504. char pathStr[128];
  505. path->address().toString(pathStr);
  506. if (!_lastPathNegotiationCheck) {
  507. return;
  508. }
  509. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, path->localSocket());
  510. if (remoteUtility > _localUtility) {
  511. char pathStr[128]; path->address().toString(pathStr);
  512. sprintf(traceMsg, "%s (bond) Peer %llx suggests using alternate link %s/%s. Remote utility (%d) is GREATER than local utility (%d), switching to said link\n",
  513. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), link->ifname().c_str(), pathStr, remoteUtility, _localUtility);
  514. RR->t->bondStateMessage(NULL, traceMsg);
  515. negotiatedPath = path;
  516. }
  517. if (remoteUtility < _localUtility) {
  518. sprintf(traceMsg, "%s (bond) Peer %llx suggests using alternate link %s/%s. Remote utility (%d) is LESS than local utility (%d), not switching\n",
  519. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), link->ifname().c_str(), pathStr, remoteUtility, _localUtility);
  520. RR->t->bondStateMessage(NULL, traceMsg);
  521. }
  522. if (remoteUtility == _localUtility) {
  523. sprintf(traceMsg, "%s (bond) Peer %llx suggests using alternate link %s/%s. Remote utility (%d) is equal to local utility (%d)\n",
  524. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), link->ifname().c_str(), pathStr, remoteUtility, _localUtility);
  525. RR->t->bondStateMessage(NULL, traceMsg);
  526. if (_peer->_id.address().toInt() > RR->node->identity().address().toInt()) {
  527. sprintf(traceMsg, "%s (bond) Agreeing with peer %llx to use alternate link %s/%s\n",
  528. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), link->ifname().c_str(), pathStr);
  529. RR->t->bondStateMessage(NULL, traceMsg);
  530. negotiatedPath = path;
  531. } else {
  532. sprintf(traceMsg, "%s (bond) Ignoring petition from peer %llx to use alternate link %s/%s\n",
  533. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), link->ifname().c_str(), pathStr);
  534. RR->t->bondStateMessage(NULL, traceMsg);
  535. }
  536. }
  537. }
  538. void Bond::pathNegotiationCheck(void *tPtr, const int64_t now)
  539. {
  540. char pathStr[128];
  541. int maxInPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  542. int maxOutPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  543. uint64_t maxInCount = 0;
  544. uint64_t maxOutCount = 0;
  545. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  546. if (!_paths[i]) {
  547. continue;
  548. }
  549. if (_paths[i]->_packetsIn > maxInCount) {
  550. maxInCount = _paths[i]->_packetsIn;
  551. maxInPathIdx = i;
  552. }
  553. if (_paths[i]->_packetsOut > maxOutCount) {
  554. maxOutCount = _paths[i]->_packetsOut;
  555. maxOutPathIdx = i;
  556. }
  557. _paths[i]->resetPacketCounts();
  558. }
  559. bool _peerLinksSynchronized = ((maxInPathIdx != ZT_MAX_PEER_NETWORK_PATHS)
  560. && (maxOutPathIdx != ZT_MAX_PEER_NETWORK_PATHS)
  561. && (maxInPathIdx != maxOutPathIdx)) ? false : true;
  562. /**
  563. * Determine utility and attempt to petition remote peer to switch to our chosen path
  564. */
  565. if (!_peerLinksSynchronized) {
  566. _localUtility = _paths[maxOutPathIdx]->_failoverScore - _paths[maxInPathIdx]->_failoverScore;
  567. if (_paths[maxOutPathIdx]->_negotiated) {
  568. _localUtility -= ZT_MULTIPATH_FAILOVER_HANDICAP_NEGOTIATED;
  569. }
  570. if ((now - _lastSentPathNegotiationRequest) > ZT_PATH_NEGOTIATION_CUTOFF_TIME) {
  571. //fprintf(stderr, "BT: (sync) it's been long enough, sending more requests.\n");
  572. _numSentPathNegotiationRequests = 0;
  573. }
  574. if (_numSentPathNegotiationRequests < ZT_PATH_NEGOTIATION_TRY_COUNT) {
  575. if (_localUtility >= 0) {
  576. //fprintf(stderr, "BT: (sync) paths appear to be out of sync (utility=%d)\n", _localUtility);
  577. sendPATH_NEGOTIATION_REQUEST(tPtr, _paths[maxOutPathIdx]);
  578. ++_numSentPathNegotiationRequests;
  579. _lastSentPathNegotiationRequest = now;
  580. _paths[maxOutPathIdx]->address().toString(pathStr);
  581. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[maxOutPathIdx]->localSocket());
  582. //fprintf(stderr, "sending request to use %s on %s, ls=%llx, utility=%d\n", pathStr, link->ifname().c_str(), _paths[maxOutPathIdx]->localSocket(), _localUtility);
  583. }
  584. }
  585. /**
  586. * Give up negotiating and consider switching
  587. */
  588. else if ((now - _lastSentPathNegotiationRequest) > (2 * ZT_PATH_NEGOTIATION_CHECK_INTERVAL)) {
  589. if (_localUtility == 0) {
  590. // There's no loss to us, just switch without sending a another request
  591. //fprintf(stderr, "BT: (sync) giving up, switching to remote peer's path.\n");
  592. negotiatedPath = _paths[maxInPathIdx];
  593. }
  594. }
  595. }
  596. }
  597. void Bond::sendPATH_NEGOTIATION_REQUEST(void *tPtr, const SharedPtr<Path> &path)
  598. {
  599. char traceMsg[256]; char pathStr[128]; path->address().toString(pathStr);
  600. sprintf(traceMsg, "%s (bond) Sending link negotiation request to peer %llx via link %s/%s, local utility is %d",
  601. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), getLink(path)->ifname().c_str(), pathStr, _localUtility);
  602. RR->t->bondStateMessage(NULL, traceMsg);
  603. if (_abLinkSelectMethod != ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE) {
  604. return;
  605. }
  606. Packet outp(_peer->_id.address(),RR->identity.address(),Packet::VERB_PATH_NEGOTIATION_REQUEST);
  607. outp.append<int16_t>(_localUtility);
  608. if (path->address()) {
  609. outp.armor(_peer->key(),false,_peer->aesKeysIfSupported());
  610. RR->node->putPacket(tPtr,path->localSocket(),path->address(),outp.data(),outp.size());
  611. }
  612. }
  613. void Bond::sendACK(void *tPtr, const SharedPtr<Path> &path,const int64_t localSocket,
  614. const InetAddress &atAddress,int64_t now)
  615. {
  616. Packet outp(_peer->_id.address(),RR->identity.address(),Packet::VERB_ACK);
  617. int32_t bytesToAck = 0;
  618. std::map<uint64_t,uint16_t>::iterator it = path->ackStatsIn.begin();
  619. while (it != path->ackStatsIn.end()) {
  620. bytesToAck += it->second;
  621. ++it;
  622. }
  623. //char traceMsg[256]; char pathStr[128]; path->address().toString(pathStr);
  624. //sprintf(traceMsg, "%s (qos) Sending ACK packet for %d bytes to peer %llx via link %s/%s",
  625. // OSUtils::humanReadableTimestamp().c_str(), bytesToAck, _peer->_id.address().toInt(), getLink(path)->ifname().c_str(), pathStr);
  626. //RR->t->bondStateMessage(NULL, traceMsg);
  627. outp.append<uint32_t>(bytesToAck);
  628. if (atAddress) {
  629. outp.armor(_peer->key(),false,_peer->aesKeysIfSupported());
  630. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  631. } else {
  632. RR->sw->send(tPtr,outp,false);
  633. }
  634. path->ackStatsIn.clear();
  635. path->_packetsReceivedSinceLastAck = 0;
  636. path->_lastAckSent = now;
  637. }
  638. void Bond::sendQOS_MEASUREMENT(void *tPtr,const SharedPtr<Path> &path,const int64_t localSocket,
  639. const InetAddress &atAddress,int64_t now)
  640. {
  641. //char traceMsg[256]; char pathStr[128]; path->address().toString(pathStr);
  642. //sprintf(traceMsg, "%s (qos) Sending QoS packet to peer %llx via link %s/%s",
  643. // OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), getLink(path)->ifname().c_str(), pathStr);
  644. //RR->t->bondStateMessage(NULL, traceMsg);
  645. const int64_t _now = RR->node->now();
  646. Packet outp(_peer->_id.address(),RR->identity.address(),Packet::VERB_QOS_MEASUREMENT);
  647. char qosData[ZT_QOS_MAX_PACKET_SIZE];
  648. int16_t len = generateQoSPacket(path, _now,qosData);
  649. outp.append(qosData,len);
  650. if (atAddress) {
  651. outp.armor(_peer->key(),false,_peer->aesKeysIfSupported());
  652. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  653. } else {
  654. RR->sw->send(tPtr,outp,false);
  655. }
  656. // Account for the fact that a VERB_QOS_MEASUREMENT was just sent. Reset timers.
  657. path->_packetsReceivedSinceLastQoS = 0;
  658. path->_lastQoSMeasurement = now;
  659. }
  660. void Bond::processBackgroundTasks(void *tPtr, const int64_t now)
  661. {
  662. Mutex::Lock _l(_paths_m);
  663. if (!_peer->_canUseMultipath || (now - _lastBackgroundTaskCheck) < ZT_BOND_BACKGROUND_TASK_MIN_INTERVAL) {
  664. return;
  665. }
  666. _lastBackgroundTaskCheck = now;
  667. // Compute dynamic path monitor timer interval
  668. if (_linkMonitorStrategy == ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC) {
  669. int suggestedMonitorInterval = (now - _lastFrame) / 100;
  670. _dynamicPathMonitorInterval = std::min(ZT_PATH_HEARTBEAT_PERIOD, ((suggestedMonitorInterval > _bondMonitorInterval) ? suggestedMonitorInterval : _bondMonitorInterval));
  671. }
  672. // TODO: Clarify and generalize this logic
  673. if (_linkMonitorStrategy == ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC) {
  674. _shouldCollectPathStatistics = true;
  675. }
  676. // Memoize oft-used properties in the packet ingress/egress logic path
  677. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  678. // Required for real-time balancing
  679. _shouldCollectPathStatistics = true;
  680. }
  681. if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  682. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_BETTER) {
  683. // Required for judging suitability of primary link after recovery
  684. _shouldCollectPathStatistics = true;
  685. }
  686. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE) {
  687. // Required for judging suitability of new candidate primary
  688. _shouldCollectPathStatistics = true;
  689. }
  690. }
  691. if ((now - _lastCheckUserPreferences) > 1000) {
  692. _lastCheckUserPreferences = now;
  693. applyUserPrefs();
  694. }
  695. curateBond(now,false);
  696. if ((now - _lastQualityEstimation) > _qualityEstimationInterval) {
  697. _lastQualityEstimation = now;
  698. estimatePathQuality(now);
  699. }
  700. dumpInfo(now);
  701. // Send QOS/ACK packets as needed
  702. if (_shouldCollectPathStatistics) {
  703. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  704. if (_paths[i] && _paths[i]->allowed()) {
  705. if (_paths[i]->needsToSendQoS(now,_qosSendInterval)) {
  706. sendQOS_MEASUREMENT(tPtr, _paths[i], _paths[i]->localSocket(), _paths[i]->address(), now);
  707. }
  708. if (_paths[i]->needsToSendAck(now,_ackSendInterval)) {
  709. sendACK(tPtr, _paths[i], _paths[i]->localSocket(), _paths[i]->address(), now);
  710. }
  711. }
  712. }
  713. }
  714. // Perform periodic background tasks unique to each bonding policy
  715. switch (_bondingPolicy)
  716. {
  717. case ZT_BONDING_POLICY_ACTIVE_BACKUP:
  718. processActiveBackupTasks(tPtr, now);
  719. break;
  720. case ZT_BONDING_POLICY_BROADCAST:
  721. break;
  722. case ZT_BONDING_POLICY_BALANCE_RR:
  723. case ZT_BONDING_POLICY_BALANCE_XOR:
  724. case ZT_BONDING_POLICY_BALANCE_AWARE:
  725. processBalanceTasks(now);
  726. break;
  727. default:
  728. break;
  729. }
  730. // Check whether or not a path negotiation needs to be performed
  731. if (((now - _lastPathNegotiationCheck) > ZT_PATH_NEGOTIATION_CHECK_INTERVAL) && _allowPathNegotiation) {
  732. _lastPathNegotiationCheck = now;
  733. pathNegotiationCheck(tPtr, now);
  734. }
  735. }
  736. void Bond::applyUserPrefs()
  737. {
  738. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  739. if (!_paths[i]) {
  740. continue;
  741. }
  742. SharedPtr<Link> sl = getLink(_paths[i]);
  743. if (sl) {
  744. if (sl->monitorInterval() == 0) { // If no interval was specified for this link, use more generic bond-wide interval
  745. sl->setMonitorInterval(_bondMonitorInterval);
  746. }
  747. RR->bc->setMinReqPathMonitorInterval((sl->monitorInterval() < RR->bc->minReqPathMonitorInterval()) ? sl->monitorInterval() : RR->bc->minReqPathMonitorInterval());
  748. bool bFoundCommonLink = false;
  749. SharedPtr<Link> commonLink =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  750. for(unsigned int j=0;j<ZT_MAX_PEER_NETWORK_PATHS;++j) {
  751. if (_paths[j] && _paths[j].ptr() != _paths[i].ptr()) {
  752. if (RR->bc->getLinkBySocket(_policyAlias, _paths[j]->localSocket()) == commonLink) {
  753. bFoundCommonLink = true;
  754. }
  755. }
  756. }
  757. _paths[i]->_monitorInterval = sl->monitorInterval();
  758. _paths[i]->_upDelay = sl->upDelay() ? sl->upDelay() : _upDelay;
  759. _paths[i]->_downDelay = sl->downDelay() ? sl->downDelay() : _downDelay;
  760. _paths[i]->_ipvPref = sl->ipvPref();
  761. _paths[i]->_mode = sl->mode();
  762. _paths[i]->_enabled = sl->enabled();
  763. _paths[i]->_onlyPathOnLink = !bFoundCommonLink;
  764. }
  765. }
  766. if (_peer) {
  767. _peer->_shouldCollectPathStatistics = _shouldCollectPathStatistics;
  768. _peer->_bondingPolicy = _bondingPolicy;
  769. }
  770. }
  771. void Bond::curateBond(const int64_t now, bool rebuildBond)
  772. {
  773. char traceMsg[256];
  774. char pathStr[128];
  775. uint8_t tmpNumAliveLinks = 0;
  776. uint8_t tmpNumTotalLinks = 0;
  777. /**
  778. * Update path states
  779. */
  780. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  781. if (!_paths[i]) {
  782. continue;
  783. }
  784. tmpNumTotalLinks++;
  785. if (_paths[i]->alive(now, true)) {
  786. tmpNumAliveLinks++;
  787. }
  788. bool currEligibility = _paths[i]->eligible(now,_ackSendInterval);
  789. if (currEligibility != _paths[i]->_lastEligibilityState) {
  790. _paths[i]->address().toString(pathStr);
  791. char traceMsg[256]; _paths[i]->address().toString(pathStr);
  792. sprintf(traceMsg, "%s (bond) Eligibility of link %s/%s to peer %llx has changed from %d to %d",
  793. OSUtils::humanReadableTimestamp().c_str(), getLink(_paths[i])->ifname().c_str(), pathStr, _peer->_id.address().toInt(), _paths[i]->_lastEligibilityState, currEligibility);
  794. RR->t->bondStateMessage(NULL, traceMsg);
  795. if (currEligibility) {
  796. rebuildBond = true;
  797. }
  798. if (!currEligibility) {
  799. _paths[i]->adjustRefractoryPeriod(now, _defaultPathRefractoryPeriod, !currEligibility);
  800. if (_paths[i]->bonded()) {
  801. char pathStr[128]; _paths[i]->address().toString(pathStr);
  802. sprintf(traceMsg, "%s (bond) Link %s/%s to peer %llx was bonded, reallocation of its flows will occur soon",
  803. OSUtils::humanReadableTimestamp().c_str(), getLink(_paths[i])->ifname().c_str(), pathStr, _peer->_id.address().toInt());
  804. RR->t->bondStateMessage(NULL, traceMsg);
  805. rebuildBond = true;
  806. _paths[i]->_shouldReallocateFlows = _paths[i]->bonded();
  807. _paths[i]->setBonded(false);
  808. } else {
  809. sprintf(traceMsg, "%s (bond) Link %s/%s to peer %llx was not bonded, no allocation consequences",
  810. OSUtils::humanReadableTimestamp().c_str(), getLink(_paths[i])->ifname().c_str(), pathStr, _peer->_id.address().toInt());
  811. RR->t->bondStateMessage(NULL, traceMsg);
  812. }
  813. }
  814. }
  815. if (currEligibility) {
  816. _paths[i]->adjustRefractoryPeriod(now, _defaultPathRefractoryPeriod, false);
  817. }
  818. _paths[i]->_lastEligibilityState = currEligibility;
  819. }
  820. _numAliveLinks = tmpNumAliveLinks;
  821. _numTotalLinks = tmpNumTotalLinks;
  822. /* Determine health status to report to user */
  823. bool tmpHealthStatus = true;
  824. if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  825. if (_numAliveLinks < 2) {
  826. // Considered healthy if there is at least one failover link
  827. tmpHealthStatus = false;
  828. }
  829. }
  830. if (_bondingPolicy == ZT_BONDING_POLICY_BROADCAST) {
  831. if (_numAliveLinks < 1) {
  832. // Considerd healthy if we're able to send frames at all
  833. tmpHealthStatus = false;
  834. }
  835. }
  836. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR) {
  837. if (_numAliveLinks < _numTotalLinks) {
  838. // Considerd healthy if all known paths are alive, this should be refined to account for user bond config settings
  839. tmpHealthStatus = false;
  840. }
  841. }
  842. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR) {
  843. if (_numAliveLinks < _numTotalLinks) {
  844. // Considerd healthy if all known paths are alive, this should be refined to account for user bond config settings
  845. tmpHealthStatus = false;
  846. }
  847. }
  848. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  849. if (_numAliveLinks < _numTotalLinks) {
  850. // Considerd healthy if all known paths are alive, this should be refined to account for user bond config settings
  851. tmpHealthStatus = false;
  852. }
  853. }
  854. if (tmpHealthStatus != _isHealthy) {
  855. std::string healthStatusStr;
  856. if (tmpHealthStatus == true) {
  857. healthStatusStr = "HEALTHY";
  858. } else {
  859. healthStatusStr = "DEGRADED";
  860. }
  861. sprintf(traceMsg, "%s (bond) Bond to peer %llx is in a %s state (%d/%d links)",
  862. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), healthStatusStr.c_str(), _numAliveLinks, _numTotalLinks);
  863. RR->t->bondStateMessage(NULL, traceMsg);
  864. }
  865. _isHealthy = tmpHealthStatus;
  866. /**
  867. * Curate the set of paths that are part of the bond proper. Selects a single path
  868. * per logical link according to eligibility and user-specified constraints.
  869. */
  870. if ((_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR)
  871. || (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR)
  872. || (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE)) {
  873. if (!_numBondedPaths) {
  874. rebuildBond = true;
  875. }
  876. // TODO: Optimize
  877. if (rebuildBond) {
  878. int updatedBondedPathCount = 0;
  879. std::map<SharedPtr<Link>,int> linkMap;
  880. for (int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  881. if (_paths[i] && _paths[i]->allowed() && (_paths[i]->eligible(now,_ackSendInterval) || !_numBondedPaths)) {
  882. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  883. if (!linkMap.count(link)) {
  884. linkMap[link] = i;
  885. }
  886. else {
  887. bool overriden = false;
  888. _paths[i]->address().toString(pathStr);
  889. //fprintf(stderr, " link representative path already exists! (%s %s)\n", getLink(_paths[i])->ifname().c_str(), pathStr);
  890. if (_paths[i]->preferred() && !_paths[linkMap[link]]->preferred()) {
  891. // Override previous choice if preferred
  892. if (_paths[linkMap[link]]->_assignedFlowCount) {
  893. _paths[linkMap[link]]->_deprecated = true;
  894. }
  895. else {
  896. _paths[linkMap[link]]->_deprecated = true;
  897. _paths[linkMap[link]]->setBonded(false);
  898. }
  899. linkMap[link] = i;
  900. overriden = true;
  901. }
  902. if ((_paths[i]->preferred() && _paths[linkMap[link]]->preferred())
  903. || (!_paths[i]->preferred() && !_paths[linkMap[link]]->preferred())) {
  904. if (_paths[i]->preferenceRank() > _paths[linkMap[link]]->preferenceRank()) {
  905. // Override if higher preference
  906. if (_paths[linkMap[link]]->_assignedFlowCount) {
  907. _paths[linkMap[link]]->_deprecated = true;
  908. }
  909. else {
  910. _paths[linkMap[link]]->_deprecated = true;
  911. _paths[linkMap[link]]->setBonded(false);
  912. }
  913. linkMap[link] = i;
  914. }
  915. }
  916. }
  917. }
  918. }
  919. std::map<SharedPtr<Link>,int>::iterator it = linkMap.begin();
  920. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  921. if (!_paths[i]) {
  922. continue;
  923. }
  924. _bondedIdx[i] = ZT_MAX_PEER_NETWORK_PATHS;
  925. if (it != linkMap.end()) {
  926. _bondedIdx[i] = it->second;
  927. _paths[_bondedIdx[i]]->setBonded(true);
  928. ++it;
  929. ++updatedBondedPathCount;
  930. _paths[_bondedIdx[i]]->address().toString(pathStr);
  931. //fprintf(stderr, "setting i=%d, _bondedIdx[%d]=%d to bonded (%s %s)\n", i, i, _bondedIdx[i], getLink(_paths[_bondedIdx[i]])->ifname().c_str(), pathStr);
  932. }
  933. }
  934. _numBondedPaths = updatedBondedPathCount;
  935. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR) {
  936. // Cause a RR reset since the currently used index might no longer be valid
  937. _rrPacketsSentOnCurrLink = _packetsPerLink;
  938. }
  939. }
  940. }
  941. }
  942. void Bond::estimatePathQuality(const int64_t now)
  943. {
  944. char pathStr[128];
  945. uint32_t totUserSpecifiedLinkSpeed = 0;
  946. if (_numBondedPaths) { // Compute relative user-specified speeds of links
  947. for(unsigned int i=0;i<_numBondedPaths;++i) {
  948. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  949. if (_paths[i] && _paths[i]->allowed()) {
  950. totUserSpecifiedLinkSpeed += link->speed();
  951. }
  952. }
  953. for(unsigned int i=0;i<_numBondedPaths;++i) {
  954. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  955. if (_paths[i] && _paths[i]->allowed()) {
  956. link->setRelativeSpeed(round( ((float)link->speed() / (float)totUserSpecifiedLinkSpeed) * 255));
  957. }
  958. }
  959. }
  960. float lat[ZT_MAX_PEER_NETWORK_PATHS];
  961. float pdv[ZT_MAX_PEER_NETWORK_PATHS];
  962. float plr[ZT_MAX_PEER_NETWORK_PATHS];
  963. float per[ZT_MAX_PEER_NETWORK_PATHS];
  964. float maxLAT = 0;
  965. float maxPDV = 0;
  966. float maxPLR = 0;
  967. float maxPER = 0;
  968. float quality[ZT_MAX_PEER_NETWORK_PATHS];
  969. uint8_t alloc[ZT_MAX_PEER_NETWORK_PATHS];
  970. float totQuality = 0.0f;
  971. memset(&lat, 0, sizeof(lat));
  972. memset(&pdv, 0, sizeof(pdv));
  973. memset(&plr, 0, sizeof(plr));
  974. memset(&per, 0, sizeof(per));
  975. memset(&quality, 0, sizeof(quality));
  976. memset(&alloc, 0, sizeof(alloc));
  977. // Compute initial summary statistics
  978. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  979. if (!_paths[i] || !_paths[i]->allowed()) {
  980. continue;
  981. }
  982. // Compute/Smooth average of real-world observations
  983. _paths[i]->_latencyMean = _paths[i]->latencySamples.mean();
  984. _paths[i]->_latencyVariance = _paths[i]->latencySamples.stddev();
  985. _paths[i]->_packetErrorRatio = 1.0 - (_paths[i]->packetValiditySamples.count() ? _paths[i]->packetValiditySamples.mean() : 1.0);
  986. if (userHasSpecifiedLinkSpeeds()) {
  987. // Use user-reported metrics
  988. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  989. if (link) {
  990. _paths[i]->_throughputMean = link->speed();
  991. _paths[i]->_throughputVariance = 0;
  992. }
  993. }
  994. // Drain unacknowledged QoS records
  995. std::map<uint64_t,uint64_t>::iterator it = _paths[i]->qosStatsOut.begin();
  996. uint64_t currentLostRecords = 0;
  997. while (it != _paths[i]->qosStatsOut.end()) {
  998. int qosRecordTimeout = 5000; //_paths[i]->monitorInterval() * ZT_MULTIPATH_QOS_ACK_INTERVAL_MULTIPLIER * 8;
  999. if ((now - it->second) >= qosRecordTimeout) {
  1000. // Packet was lost
  1001. it = _paths[i]->qosStatsOut.erase(it);
  1002. ++currentLostRecords;
  1003. } else { ++it; }
  1004. }
  1005. quality[i]=0;
  1006. totQuality=0;
  1007. // Normalize raw observations according to sane limits and/or user specified values
  1008. lat[i] = 1.0 / expf(4*Utils::normalize(_paths[i]->_latencyMean, 0, _maxAcceptableLatency, 0, 1));
  1009. pdv[i] = 1.0 / expf(4*Utils::normalize(_paths[i]->_latencyVariance, 0, _maxAcceptablePacketDelayVariance, 0, 1));
  1010. plr[i] = 1.0 / expf(4*Utils::normalize(_paths[i]->_packetLossRatio, 0, _maxAcceptablePacketLossRatio, 0, 1));
  1011. per[i] = 1.0 / expf(4*Utils::normalize(_paths[i]->_packetErrorRatio, 0, _maxAcceptablePacketErrorRatio, 0, 1));
  1012. // Record bond-wide maximums to determine relative values
  1013. maxLAT = lat[i] > maxLAT ? lat[i] : maxLAT;
  1014. maxPDV = pdv[i] > maxPDV ? pdv[i] : maxPDV;
  1015. maxPLR = plr[i] > maxPLR ? plr[i] : maxPLR;
  1016. maxPER = per[i] > maxPER ? per[i] : maxPER;
  1017. }
  1018. // Convert metrics to relative quantities and apply contribution weights
  1019. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  1020. if (_paths[i] && _paths[i]->bonded()) {
  1021. quality[i] += ((maxLAT > 0.0f ? lat[i] / maxLAT : 0.0f) * _qualityWeights[ZT_QOS_LAT_IDX]);
  1022. quality[i] += ((maxPDV > 0.0f ? pdv[i] / maxPDV : 0.0f) * _qualityWeights[ZT_QOS_PDV_IDX]);
  1023. quality[i] += ((maxPLR > 0.0f ? plr[i] / maxPLR : 0.0f) * _qualityWeights[ZT_QOS_PLR_IDX]);
  1024. quality[i] += ((maxPER > 0.0f ? per[i] / maxPER : 0.0f) * _qualityWeights[ZT_QOS_PER_IDX]);
  1025. totQuality += quality[i];
  1026. }
  1027. }
  1028. // Normalize to 8-bit allocation values
  1029. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  1030. if (_paths[i] && _paths[i]->bonded()) {
  1031. alloc[i] = std::ceil((quality[i] / totQuality) * (float)255);
  1032. _paths[i]->_allocation = alloc[i];
  1033. }
  1034. }
  1035. }
  1036. void Bond::processBalanceTasks(const int64_t now)
  1037. {
  1038. char curPathStr[128];
  1039. // TODO: Generalize
  1040. int totalAllocation = 0;
  1041. for (int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  1042. if (!_paths[i]) {
  1043. continue;
  1044. }
  1045. if (_paths[i] && _paths[i]->bonded() && _paths[i]->eligible(now,_ackSendInterval)) {
  1046. totalAllocation+=_paths[i]->_allocation;
  1047. }
  1048. }
  1049. unsigned char minimumAllocationValue = 0.33 * ((float)totalAllocation / (float)_numBondedPaths);
  1050. if (_allowFlowHashing) {
  1051. /**
  1052. * Clean up and reset flows if necessary
  1053. */
  1054. if ((now - _lastFlowExpirationCheck) > ZT_MULTIPATH_FLOW_CHECK_INTERVAL) {
  1055. Mutex::Lock _l(_flows_m);
  1056. forgetFlowsWhenNecessary(ZT_MULTIPATH_FLOW_EXPIRATION_INTERVAL,false,now);
  1057. _lastFlowExpirationCheck = now;
  1058. }
  1059. if ((now - _lastFlowStatReset) > ZT_FLOW_STATS_RESET_INTERVAL) {
  1060. Mutex::Lock _l(_flows_m);
  1061. _lastFlowStatReset = now;
  1062. std::map<int32_t,SharedPtr<Flow> >::iterator it = _flows.begin();
  1063. while (it != _flows.end()) {
  1064. it->second->resetByteCounts();
  1065. ++it;
  1066. }
  1067. }
  1068. /**
  1069. * Re-allocate flows from dead paths
  1070. */
  1071. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  1072. Mutex::Lock _l(_flows_m);
  1073. for (int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  1074. if (!_paths[i]) {
  1075. continue;
  1076. }
  1077. if (!_paths[i]->eligible(now,_ackSendInterval) && _paths[i]->_shouldReallocateFlows) {
  1078. char traceMsg[256]; char pathStr[128]; _paths[i]->address().toString(pathStr);
  1079. sprintf(traceMsg, "%s (balance-*) Reallocating flows to peer %llx from dead link %s/%s to surviving links",
  1080. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), getLink(_paths[i])->ifname().c_str(), pathStr);
  1081. RR->t->bondStateMessage(NULL, traceMsg);
  1082. std::map<int32_t,SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1083. while (flow_it != _flows.end()) {
  1084. if (flow_it->second->assignedPath() == _paths[i]) {
  1085. if(assignFlowToBondedPath(flow_it->second, now)) {
  1086. _paths[i]->_assignedFlowCount--;
  1087. }
  1088. }
  1089. ++flow_it;
  1090. }
  1091. _paths[i]->_shouldReallocateFlows = false;
  1092. }
  1093. }
  1094. }
  1095. /**
  1096. * Re-allocate flows from under-performing
  1097. * NOTE: This could be part of the above block but was kept separate for clarity.
  1098. */
  1099. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR || _bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  1100. Mutex::Lock _l(_flows_m);
  1101. for (int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  1102. if (!_paths[i]) {
  1103. continue;
  1104. }
  1105. if (_paths[i] && _paths[i]->bonded() && _paths[i]->eligible(now,_ackSendInterval) && (_paths[i]->_allocation < minimumAllocationValue) && _paths[i]->_assignedFlowCount) {
  1106. _paths[i]->address().toString(curPathStr);
  1107. char traceMsg[256]; char pathStr[128]; _paths[i]->address().toString(pathStr);
  1108. sprintf(traceMsg, "%s (balance-*) Reallocating flows to peer %llx from under-performing link %s/%s\n",
  1109. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), getLink(_paths[i])->ifname().c_str(), pathStr);
  1110. RR->t->bondStateMessage(NULL, traceMsg);
  1111. std::map<int32_t,SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1112. while (flow_it != _flows.end()) {
  1113. if (flow_it->second->assignedPath() == _paths[i]) {
  1114. if(assignFlowToBondedPath(flow_it->second, now)) {
  1115. _paths[i]->_assignedFlowCount--;
  1116. }
  1117. }
  1118. ++flow_it;
  1119. }
  1120. _paths[i]->_shouldReallocateFlows = false;
  1121. }
  1122. }
  1123. }
  1124. }
  1125. /**
  1126. * Tasks specific to (Balance Round Robin)
  1127. */
  1128. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_RR) {
  1129. // Nothing
  1130. }
  1131. /**
  1132. * Tasks specific to (Balance XOR)
  1133. */
  1134. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_XOR) {
  1135. // Nothing
  1136. }
  1137. /**
  1138. * Tasks specific to (Balance Aware)
  1139. */
  1140. if (_bondingPolicy == ZT_BONDING_POLICY_BALANCE_AWARE) {
  1141. if (_allowFlowHashing) {
  1142. Mutex::Lock _l(_flows_m);
  1143. if (_flowRebalanceStrategy == ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_PASSIVE) {
  1144. // Do nothing here, this is taken care of in the more general case above.
  1145. }
  1146. if (_flowRebalanceStrategy == ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_OPPORTUNISTIC) {
  1147. // If the flow is temporarily inactive we should take this opportunity to re-assign the flow if needed.
  1148. }
  1149. if (_flowRebalanceStrategy == ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_AGGRESSIVE) {
  1150. /**
  1151. * Return flows to the original path if it has once again become available
  1152. */
  1153. if ((now - _lastFlowRebalance) > ZT_FLOW_REBALANCE_INTERVAL) {
  1154. std::map<int32_t,SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1155. while (flow_it != _flows.end()) {
  1156. if (flow_it->second->_previouslyAssignedPath && flow_it->second->_previouslyAssignedPath->eligible(now, _ackSendInterval)
  1157. && (flow_it->second->_previouslyAssignedPath->_allocation >= (minimumAllocationValue * 2))) {
  1158. //fprintf(stderr, "moving flow back onto its previous path assignment (based on eligibility)\n");
  1159. (flow_it->second->_assignedPath->_assignedFlowCount)--;
  1160. flow_it->second->assignPath(flow_it->second->_previouslyAssignedPath,now);
  1161. (flow_it->second->_previouslyAssignedPath->_assignedFlowCount)++;
  1162. }
  1163. ++flow_it;
  1164. }
  1165. _lastFlowRebalance = now;
  1166. }
  1167. /**
  1168. * Return flows to the original path if it has once again become (performant)
  1169. */
  1170. if ((now - _lastFlowRebalance) > ZT_FLOW_REBALANCE_INTERVAL) {
  1171. std::map<int32_t,SharedPtr<Flow> >::iterator flow_it = _flows.begin();
  1172. while (flow_it != _flows.end()) {
  1173. if (flow_it->second->_previouslyAssignedPath && flow_it->second->_previouslyAssignedPath->eligible(now, _ackSendInterval)
  1174. && (flow_it->second->_previouslyAssignedPath->_allocation >= (minimumAllocationValue * 2))) {
  1175. //fprintf(stderr, "moving flow back onto its previous path assignment (based on performance)\n");
  1176. (flow_it->second->_assignedPath->_assignedFlowCount)--;
  1177. flow_it->second->assignPath(flow_it->second->_previouslyAssignedPath,now);
  1178. (flow_it->second->_previouslyAssignedPath->_assignedFlowCount)++;
  1179. }
  1180. ++flow_it;
  1181. }
  1182. _lastFlowRebalance = now;
  1183. }
  1184. }
  1185. }
  1186. else if (!_allowFlowHashing) {
  1187. // Nothing
  1188. }
  1189. }
  1190. }
  1191. void Bond::dequeueNextActiveBackupPath(const uint64_t now)
  1192. {
  1193. if (_abFailoverQueue.empty()) {
  1194. return;
  1195. }
  1196. _abPath = _abFailoverQueue.front();
  1197. _abFailoverQueue.pop_front();
  1198. _lastActiveBackupPathChange = now;
  1199. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1200. if (_paths[i]) {
  1201. _paths[i]->resetPacketCounts();
  1202. }
  1203. }
  1204. }
  1205. bool Bond::abForciblyRotateLink()
  1206. {
  1207. char traceMsg[256];
  1208. char prevPathStr[128];
  1209. char curPathStr[128];
  1210. if (_bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  1211. SharedPtr<Path> prevPath = _abPath;
  1212. _abPath->address().toString(prevPathStr);
  1213. dequeueNextActiveBackupPath(RR->node->now());
  1214. _abPath->address().toString(curPathStr);
  1215. sprintf(traceMsg, "%s (active-backup) Forcibly rotating peer %llx link from %s/%s to %s/%s",
  1216. OSUtils::humanReadableTimestamp().c_str(),
  1217. _peer->_id.address().toInt(),
  1218. getLink(prevPath)->ifname().c_str(),
  1219. prevPathStr,
  1220. getLink(_abPath)->ifname().c_str(),
  1221. curPathStr);
  1222. RR->t->bondStateMessage(NULL, traceMsg);
  1223. return true;
  1224. }
  1225. return false;
  1226. }
  1227. void Bond::processActiveBackupTasks(void *tPtr, const int64_t now)
  1228. {
  1229. char traceMsg[256];
  1230. char pathStr[128];
  1231. char prevPathStr[128];
  1232. char curPathStr[128];
  1233. SharedPtr<Path> prevActiveBackupPath = _abPath;
  1234. SharedPtr<Path> nonPreferredPath;
  1235. bool bFoundPrimaryLink = false;
  1236. /**
  1237. * Generate periodic statuc report
  1238. */
  1239. if ((now - _lastBondStatusLog) > ZT_MULTIPATH_BOND_STATUS_INTERVAL) {
  1240. _lastBondStatusLog = now;
  1241. if (_abPath) {
  1242. _abPath->address().toString(curPathStr);
  1243. sprintf(traceMsg, "%s (active-backup) Active link to peer %llx is %s/%s, failover queue size is %zu",
  1244. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), getLink(_abPath)->ifname().c_str(), curPathStr, _abFailoverQueue.size());
  1245. RR->t->bondStateMessage(NULL, traceMsg);
  1246. } else {
  1247. sprintf(traceMsg, "%s (active-backup) No active link to peer %llx",
  1248. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt());
  1249. RR->t->bondStateMessage(NULL, traceMsg);
  1250. }
  1251. if (_abFailoverQueue.empty()) {
  1252. sprintf(traceMsg, "%s (active-backup) Failover queue is empty, bond to peer %llx is NOT currently fault-tolerant",
  1253. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt());
  1254. RR->t->bondStateMessage(NULL, traceMsg);
  1255. }
  1256. }
  1257. /**
  1258. * Select initial "active" active-backup link
  1259. */
  1260. if (!_abPath) {
  1261. /**
  1262. * [Automatic mode]
  1263. * The user has not explicitly specified links or their failover schedule,
  1264. * the bonding policy will now select the first eligible path and set it as
  1265. * its active backup path, if a substantially better path is detected the bonding
  1266. * policy will assign it as the new active backup path. If the path fails it will
  1267. * simply find the next eligible path.
  1268. */
  1269. if (!userHasSpecifiedLinks()) {
  1270. sprintf(traceMsg, "%s (active-backup) No links to peer %llx specified. Searching...",
  1271. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt()); RR->t->bondStateMessage(NULL, traceMsg);
  1272. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1273. if (_paths[i] && _paths[i]->eligible(now,_ackSendInterval)) {
  1274. _paths[i]->address().toString(curPathStr);
  1275. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1276. if (link) {
  1277. sprintf(traceMsg, "%s (active-backup) Found eligible link %s/%s to peer %llx",
  1278. OSUtils::humanReadableTimestamp().c_str(), getLink(_paths[i])->ifname().c_str(), curPathStr, _peer->_id.address().toInt());
  1279. RR->t->bondStateMessage(NULL, traceMsg);
  1280. }
  1281. _abPath = _paths[i];
  1282. break;
  1283. }
  1284. }
  1285. }
  1286. /**
  1287. * [Manual mode]
  1288. * The user has specified links or failover rules that the bonding policy should adhere to.
  1289. */
  1290. else if (userHasSpecifiedLinks()) {
  1291. if (userHasSpecifiedPrimaryLink()) {
  1292. //sprintf(traceMsg, "%s (active-backup) Checking local.conf for user-specified primary link\n", OSUtils::humanReadableTimestamp().c_str());
  1293. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1294. if (!_paths[i]) {
  1295. continue;
  1296. }
  1297. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1298. if (_paths[i]->eligible(now,_ackSendInterval) && link->primary()) {
  1299. if (!_paths[i]->preferred()) {
  1300. _paths[i]->address().toString(curPathStr);
  1301. // Found path on primary link, take note in case we don't find a preferred path
  1302. nonPreferredPath = _paths[i];
  1303. bFoundPrimaryLink = true;
  1304. }
  1305. if (_paths[i]->preferred()) {
  1306. _abPath = _paths[i];
  1307. _abPath->address().toString(curPathStr);
  1308. SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1309. bFoundPrimaryLink = true;
  1310. break; // Found preferred path %s on primary link
  1311. }
  1312. }
  1313. }
  1314. if (_abPath) {
  1315. _abPath->address().toString(curPathStr);
  1316. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _abPath->localSocket());
  1317. if (link) {
  1318. sprintf(traceMsg, "%s (active-backup) Found preferred primary link %s/%s to peer %llx",
  1319. OSUtils::humanReadableTimestamp().c_str(), getLink(_abPath)->ifname().c_str(), curPathStr, _peer->_id.address().toInt());
  1320. RR->t->bondStateMessage(NULL, traceMsg);
  1321. }
  1322. }
  1323. else {
  1324. if (bFoundPrimaryLink && nonPreferredPath) {
  1325. sprintf(traceMsg, "%s (active-backup) Found non-preferred primary link to peer %llx",
  1326. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt());
  1327. RR->t->bondStateMessage(NULL, traceMsg);
  1328. _abPath = nonPreferredPath;
  1329. }
  1330. }
  1331. if (!_abPath) {
  1332. sprintf(traceMsg, "%s (active-backup) Designated primary link to peer %llx is not yet ready",
  1333. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt());
  1334. RR->t->bondStateMessage(NULL, traceMsg);
  1335. // TODO: Should wait for some time (failover interval?) and then swtich to spare link
  1336. }
  1337. }
  1338. else if (!userHasSpecifiedPrimaryLink()) {
  1339. int _abIdx = ZT_MAX_PEER_NETWORK_PATHS;
  1340. sprintf(traceMsg, "%s (active-backup) User did not specify a primary link to peer %llx, selecting first available link",
  1341. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt());
  1342. RR->t->bondStateMessage(NULL, traceMsg);
  1343. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1344. if (_paths[i] && _paths[i]->eligible(now,_ackSendInterval)) {
  1345. _abIdx = i;
  1346. break;
  1347. }
  1348. }
  1349. if (_abIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  1350. // Unable to find a candidate next-best, no change
  1351. }
  1352. else {
  1353. _abPath = _paths[_abIdx];
  1354. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _abPath->localSocket());
  1355. if (link) {
  1356. _abPath->address().toString(curPathStr);
  1357. sprintf(traceMsg, "%s (active-backup) Selected non-primary link %s/%s to peer %llx",
  1358. OSUtils::humanReadableTimestamp().c_str(), getLink(_abPath)->ifname().c_str(), curPathStr, _peer->_id.address().toInt());
  1359. RR->t->bondStateMessage(NULL, traceMsg);
  1360. }
  1361. }
  1362. }
  1363. }
  1364. }
  1365. /**
  1366. * Update and maintain the active-backup failover queue
  1367. */
  1368. if (_abPath) {
  1369. // Don't worry about the failover queue until we have an active link
  1370. // Remove ineligible paths from the failover link queue
  1371. for (std::list<SharedPtr<Path> >::iterator it(_abFailoverQueue.begin()); it!=_abFailoverQueue.end();) {
  1372. if ((*it) && !(*it)->eligible(now,_ackSendInterval)) {
  1373. (*it)->address().toString(curPathStr);
  1374. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, (*it)->localSocket());
  1375. it = _abFailoverQueue.erase(it);
  1376. if (link) {
  1377. sprintf(traceMsg, "%s (active-backup) Link %s/%s to peer %llx is now ineligible, removing from failover queue, there are %zu links in the queue",
  1378. OSUtils::humanReadableTimestamp().c_str(), getLink(_abPath)->ifname().c_str(), curPathStr, _peer->_id.address().toInt(), _abFailoverQueue.size());
  1379. RR->t->bondStateMessage(NULL, traceMsg);
  1380. }
  1381. } else {
  1382. ++it;
  1383. }
  1384. }
  1385. /**
  1386. * Failover instructions were provided by user, build queue according those as well as IPv
  1387. * preference, disregarding performance.
  1388. */
  1389. if (userHasSpecifiedFailoverInstructions()) {
  1390. /**
  1391. * Clear failover scores
  1392. */
  1393. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1394. if (_paths[i]) {
  1395. _paths[i]->_failoverScore = 0;
  1396. }
  1397. }
  1398. // Follow user-specified failover instructions
  1399. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1400. if (!_paths[i] || !_paths[i]->allowed() || !_paths[i]->eligible(now,_ackSendInterval)) {
  1401. continue;
  1402. }
  1403. SharedPtr<Link> link =RR->bc->getLinkBySocket(_policyAlias, _paths[i]->localSocket());
  1404. _paths[i]->address().toString(pathStr);
  1405. int failoverScoreHandicap = _paths[i]->_failoverScore;
  1406. if (_paths[i]->preferred()) {
  1407. failoverScoreHandicap += ZT_MULTIPATH_FAILOVER_HANDICAP_PREFERRED;
  1408. }
  1409. if (link->primary()) {
  1410. // If using "optimize" primary reselect mode, ignore user link designations
  1411. failoverScoreHandicap += ZT_MULTIPATH_FAILOVER_HANDICAP_PRIMARY;
  1412. }
  1413. if (!_paths[i]->_failoverScore) {
  1414. // If we didn't inherit a failover score from a "parent" that wants to use this path as a failover
  1415. int newHandicap = failoverScoreHandicap ? failoverScoreHandicap : _paths[i]->_allocation;
  1416. _paths[i]->_failoverScore = newHandicap;
  1417. }
  1418. SharedPtr<Link> failoverLink;
  1419. if (link->failoverToLink().length()) {
  1420. failoverLink = RR->bc->getLinkByName(_policyAlias, link->failoverToLink());
  1421. }
  1422. if (failoverLink) {
  1423. for (int j=0; j<ZT_MAX_PEER_NETWORK_PATHS; j++) {
  1424. if (_paths[j] && getLink(_paths[j]) == failoverLink.ptr()) {
  1425. _paths[j]->address().toString(pathStr);
  1426. int inheritedHandicap = failoverScoreHandicap - 10;
  1427. int newHandicap = _paths[j]->_failoverScore > inheritedHandicap ? _paths[j]->_failoverScore : inheritedHandicap;
  1428. if (!_paths[j]->preferred()) {
  1429. newHandicap--;
  1430. }
  1431. _paths[j]->_failoverScore = newHandicap;
  1432. }
  1433. }
  1434. }
  1435. if (_paths[i].ptr() != _abPath.ptr()) {
  1436. bool bFoundPathInQueue = false;
  1437. for (std::list<SharedPtr<Path> >::iterator it(_abFailoverQueue.begin()); it!=_abFailoverQueue.end();++it) {
  1438. if (_paths[i].ptr() == (*it).ptr()) {
  1439. bFoundPathInQueue = true;
  1440. }
  1441. }
  1442. if (!bFoundPathInQueue) {
  1443. _abFailoverQueue.push_front(_paths[i]);
  1444. _paths[i]->address().toString(curPathStr); sprintf(traceMsg, "%s (active-backup) Added link %s/%s to peer %llx to failover queue, there are %zu links in the queue",
  1445. OSUtils::humanReadableTimestamp().c_str(), getLink(_abPath)->ifname().c_str(), curPathStr, _peer->_id.address().toInt(), _abFailoverQueue.size());
  1446. RR->t->bondStateMessage(NULL, traceMsg);
  1447. }
  1448. }
  1449. }
  1450. }
  1451. /**
  1452. * No failover instructions provided by user, build queue according to performance
  1453. * and IPv preference.
  1454. */
  1455. else if (!userHasSpecifiedFailoverInstructions()) {
  1456. for (int i=0; i<ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1457. if (!_paths[i]
  1458. || !_paths[i]->allowed()
  1459. || !_paths[i]->eligible(now,_ackSendInterval)) {
  1460. continue;
  1461. }
  1462. int failoverScoreHandicap = 0;
  1463. if (_paths[i]->preferred()) {
  1464. failoverScoreHandicap = ZT_MULTIPATH_FAILOVER_HANDICAP_PREFERRED;
  1465. }
  1466. bool includeRefractoryPeriod = true;
  1467. if (!_paths[i]->eligible(now,includeRefractoryPeriod)) {
  1468. failoverScoreHandicap = -10000;
  1469. }
  1470. if (getLink(_paths[i])->primary() && _abLinkSelectMethod != ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE) {
  1471. // If using "optimize" primary reselect mode, ignore user link designations
  1472. failoverScoreHandicap = ZT_MULTIPATH_FAILOVER_HANDICAP_PRIMARY;
  1473. }
  1474. if (_paths[i].ptr() == negotiatedPath.ptr()) {
  1475. _paths[i]->_negotiated = true;
  1476. failoverScoreHandicap = ZT_MULTIPATH_FAILOVER_HANDICAP_NEGOTIATED;
  1477. } else {
  1478. _paths[i]->_negotiated = false;
  1479. }
  1480. _paths[i]->_failoverScore = _paths[i]->_allocation + failoverScoreHandicap;
  1481. if (_paths[i].ptr() != _abPath.ptr()) {
  1482. bool bFoundPathInQueue = false;
  1483. for (std::list<SharedPtr<Path> >::iterator it(_abFailoverQueue.begin()); it!=_abFailoverQueue.end();++it) {
  1484. if (_paths[i].ptr() == (*it).ptr()) {
  1485. bFoundPathInQueue = true;
  1486. }
  1487. }
  1488. if (!bFoundPathInQueue) {
  1489. _abFailoverQueue.push_front(_paths[i]);
  1490. _paths[i]->address().toString(curPathStr);
  1491. sprintf(traceMsg, "%s (active-backup) Added link %s/%s to peer %llx to failover queue, there are %zu links in the queue",
  1492. OSUtils::humanReadableTimestamp().c_str(), getLink(_paths[i])->ifname().c_str(), curPathStr, _peer->_id.address().toInt(), _abFailoverQueue.size());
  1493. RR->t->bondStateMessage(NULL, traceMsg);
  1494. }
  1495. }
  1496. }
  1497. }
  1498. _abFailoverQueue.sort(PathQualityComparator());
  1499. }
  1500. /**
  1501. * Short-circuit if we have no queued paths
  1502. */
  1503. if (_abFailoverQueue.empty()) {
  1504. return;
  1505. }
  1506. /**
  1507. * Fulfill primary reselect obligations
  1508. */
  1509. if (_abPath && !_abPath->eligible(now,_ackSendInterval)) { // Implicit ZT_MULTIPATH_RESELECTION_POLICY_FAILURE
  1510. _abPath->address().toString(curPathStr);
  1511. sprintf(traceMsg, "%s (active-backup) Link %s/%s to peer %llx has failed. Selecting new link from failover queue, there are %zu links in the queue",
  1512. OSUtils::humanReadableTimestamp().c_str(), getLink(_abPath)->ifname().c_str(), curPathStr, _peer->_id.address().toInt(), _abFailoverQueue.size());
  1513. RR->t->bondStateMessage(NULL, traceMsg);
  1514. if (!_abFailoverQueue.empty()) {
  1515. dequeueNextActiveBackupPath(now);
  1516. _abPath->address().toString(curPathStr);
  1517. sprintf(traceMsg, "%s (active-backup) Active link to peer %llx has been switched to %s/%s",
  1518. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt(), getLink(_abPath)->ifname().c_str(), curPathStr);
  1519. RR->t->bondStateMessage(NULL, traceMsg);
  1520. } else {
  1521. sprintf(traceMsg, "%s (active-backup) Failover queue is empty. No links to peer %llx to choose from",
  1522. OSUtils::humanReadableTimestamp().c_str(), _peer->_id.address().toInt());
  1523. RR->t->bondStateMessage(NULL, traceMsg);
  1524. }
  1525. }
  1526. /**
  1527. * Detect change to prevent flopping during later optimization step.
  1528. */
  1529. if (prevActiveBackupPath != _abPath) {
  1530. _lastActiveBackupPathChange = now;
  1531. }
  1532. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_ALWAYS) {
  1533. if (_abPath && !getLink(_abPath)->primary()
  1534. && getLink(_abFailoverQueue.front())->primary()) {
  1535. dequeueNextActiveBackupPath(now);
  1536. _abPath->address().toString(curPathStr);
  1537. sprintf(traceMsg, "%s (active-backup) Switching back to available primary link %s/%s to peer %llx [linkSelectionMethod = always]",
  1538. OSUtils::humanReadableTimestamp().c_str(), getLink(_abPath)->ifname().c_str(), curPathStr, _peer->_id.address().toInt());
  1539. RR->t->bondStateMessage(NULL, traceMsg);
  1540. }
  1541. }
  1542. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_BETTER) {
  1543. if (_abPath && !getLink(_abPath)->primary()) {
  1544. // Active backup has switched to "better" primary link according to re-select policy.
  1545. if (getLink(_abFailoverQueue.front())->primary()
  1546. && (_abFailoverQueue.front()->_failoverScore > _abPath->_failoverScore)) {
  1547. dequeueNextActiveBackupPath(now);
  1548. _abPath->address().toString(curPathStr);
  1549. sprintf(traceMsg, "%s (active-backup) Switching back to user-defined primary link %s/%s to peer %llx [linkSelectionMethod = better]",
  1550. OSUtils::humanReadableTimestamp().c_str(), getLink(_abPath)->ifname().c_str(), curPathStr, _peer->_id.address().toInt());
  1551. RR->t->bondStateMessage(NULL, traceMsg);
  1552. }
  1553. }
  1554. }
  1555. if (_abLinkSelectMethod == ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE && !_abFailoverQueue.empty()) {
  1556. /**
  1557. * Implement link negotiation that was previously-decided
  1558. */
  1559. if (_abFailoverQueue.front()->_negotiated) {
  1560. dequeueNextActiveBackupPath(now);
  1561. _abPath->address().toString(prevPathStr);
  1562. _lastPathNegotiationCheck = now;
  1563. _abPath->address().toString(curPathStr);
  1564. sprintf(traceMsg, "%s (active-backup) Switching negotiated link %s/%s to peer %llx [linkSelectionMethod = optimize]",
  1565. OSUtils::humanReadableTimestamp().c_str(), getLink(_abPath)->ifname().c_str(), curPathStr, _peer->_id.address().toInt());
  1566. RR->t->bondStateMessage(NULL, traceMsg);
  1567. }
  1568. else {
  1569. // Try to find a better path and automatically switch to it -- not too often, though.
  1570. if ((now - _lastActiveBackupPathChange) > ZT_MULTIPATH_MIN_ACTIVE_BACKUP_AUTOFLOP_INTERVAL) {
  1571. if (!_abFailoverQueue.empty()) {
  1572. int newFScore = _abFailoverQueue.front()->_failoverScore;
  1573. int prevFScore = _abPath->_failoverScore;
  1574. // Establish a minimum switch threshold to prevent flapping
  1575. int failoverScoreDifference = _abFailoverQueue.front()->_failoverScore - _abPath->_failoverScore;
  1576. int thresholdQuantity = (ZT_MULTIPATH_ACTIVE_BACKUP_OPTIMIZE_MIN_THRESHOLD * (float)_abPath->_allocation);
  1577. if ((failoverScoreDifference > 0) && (failoverScoreDifference > thresholdQuantity)) {
  1578. SharedPtr<Path> oldPath = _abPath;
  1579. _abPath->address().toString(prevPathStr);
  1580. dequeueNextActiveBackupPath(now);
  1581. _abPath->address().toString(curPathStr);
  1582. sprintf(traceMsg, "%s (active-backup) Switching from %s/%s (fscore=%d) to better link %s/%s (fscore=%d) for peer %llx [linkSelectionMethod = optimize]",
  1583. OSUtils::humanReadableTimestamp().c_str(), getLink(oldPath)->ifname().c_str(), prevPathStr, prevFScore, getLink(_abPath)->ifname().c_str(), curPathStr, newFScore, _peer->_id.address().toInt());
  1584. RR->t->bondStateMessage(NULL, traceMsg);
  1585. }
  1586. }
  1587. }
  1588. }
  1589. }
  1590. }
  1591. void Bond::setReasonableDefaults(int policy, SharedPtr<Bond> templateBond, bool useTemplate)
  1592. {
  1593. // If invalid bonding policy, try default
  1594. int _defaultBondingPolicy = BondController::defaultBondingPolicy();
  1595. if (policy <= ZT_BONDING_POLICY_NONE || policy > ZT_BONDING_POLICY_BALANCE_AWARE) {
  1596. // If no default set, use NONE (effectively disabling this bond)
  1597. if (_defaultBondingPolicy < ZT_BONDING_POLICY_NONE || _defaultBondingPolicy > ZT_BONDING_POLICY_BALANCE_AWARE) {
  1598. _bondingPolicy= ZT_BONDING_POLICY_NONE;
  1599. }
  1600. _bondingPolicy= _defaultBondingPolicy;
  1601. } else {
  1602. _bondingPolicy= policy;
  1603. }
  1604. _freeRandomByte = 0;
  1605. _userHasSpecifiedPrimaryLink = false;
  1606. _userHasSpecifiedFailoverInstructions = false;
  1607. _isHealthy = false;
  1608. _numAliveLinks = 0;
  1609. _numTotalLinks = 0;
  1610. _downDelay = 0;
  1611. _upDelay = 0;
  1612. _allowFlowHashing=false;
  1613. _bondMonitorInterval=0;
  1614. _shouldCollectPathStatistics=false;
  1615. // Path negotiation
  1616. _allowPathNegotiation=false;
  1617. _pathNegotiationCutoffCount=0;
  1618. _localUtility=0;
  1619. _numBondedPaths=0;
  1620. _rrPacketsSentOnCurrLink=0;
  1621. _rrIdx=0;
  1622. _totalBondUnderload = 0;
  1623. _maxAcceptableLatency = 100;
  1624. _maxAcceptablePacketDelayVariance = 50;
  1625. _maxAcceptablePacketLossRatio = 0.10;
  1626. _maxAcceptablePacketErrorRatio = 0.10;
  1627. _userHasSpecifiedLinkSpeeds=0;
  1628. /* ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_PASSIVE is the most conservative strategy and is
  1629. least likely to cause unexpected behavior */
  1630. _flowRebalanceStrategy = ZT_MULTIPATH_FLOW_REBALANCE_STRATEGY_AGGRESSIVE;
  1631. /**
  1632. * Paths are actively monitored to provide a real-time quality/preference-ordered rapid failover queue.
  1633. */
  1634. switch (policy) {
  1635. case ZT_BONDING_POLICY_ACTIVE_BACKUP:
  1636. _failoverInterval = 500;
  1637. _abLinkSelectMethod = ZT_MULTIPATH_RESELECTION_POLICY_OPTIMIZE;
  1638. _linkMonitorStrategy = ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC;
  1639. _qualityWeights[ZT_QOS_LAT_IDX] = 0.2f;
  1640. _qualityWeights[ZT_QOS_LTM_IDX] = 0.0f;
  1641. _qualityWeights[ZT_QOS_PDV_IDX] = 0.2f;
  1642. _qualityWeights[ZT_QOS_PLR_IDX] = 0.2f;
  1643. _qualityWeights[ZT_QOS_PER_IDX] = 0.2f;
  1644. _qualityWeights[ZT_QOS_THR_IDX] = 0.2f;
  1645. _qualityWeights[ZT_QOS_THM_IDX] = 0.0f;
  1646. _qualityWeights[ZT_QOS_THV_IDX] = 0.0f;
  1647. _qualityWeights[ZT_QOS_SCP_IDX] = 0.0f;
  1648. break;
  1649. /**
  1650. * All seemingly-alive paths are used. Paths are not actively monitored.
  1651. */
  1652. case ZT_BONDING_POLICY_BROADCAST:
  1653. _downDelay = 30000;
  1654. _upDelay = 0;
  1655. break;
  1656. /**
  1657. * Paths are monitored to determine when/if one needs to be added or removed from the rotation
  1658. */
  1659. case ZT_BONDING_POLICY_BALANCE_RR:
  1660. _failoverInterval = 3000;
  1661. _allowFlowHashing = false;
  1662. _packetsPerLink = 1024;
  1663. _linkMonitorStrategy = ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC;
  1664. _qualityWeights[ZT_QOS_LAT_IDX] = 0.4f;
  1665. _qualityWeights[ZT_QOS_LTM_IDX] = 0.0f;
  1666. _qualityWeights[ZT_QOS_PDV_IDX] = 0.2f;
  1667. _qualityWeights[ZT_QOS_PLR_IDX] = 0.1f;
  1668. _qualityWeights[ZT_QOS_PER_IDX] = 0.1f;
  1669. _qualityWeights[ZT_QOS_THR_IDX] = 0.1f;
  1670. _qualityWeights[ZT_QOS_THM_IDX] = 0.0f;
  1671. _qualityWeights[ZT_QOS_THV_IDX] = 0.0f;
  1672. _qualityWeights[ZT_QOS_SCP_IDX] = 0.0f;
  1673. break;
  1674. /**
  1675. * Path monitoring is used to determine the capacity of each
  1676. * path and where to place the next flow.
  1677. */
  1678. case ZT_BONDING_POLICY_BALANCE_XOR:
  1679. _failoverInterval = 3000;
  1680. _upDelay = _bondMonitorInterval * 2;
  1681. _allowFlowHashing = true;
  1682. _linkMonitorStrategy = ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC;
  1683. _qualityWeights[ZT_QOS_LAT_IDX] = 0.4f;
  1684. _qualityWeights[ZT_QOS_LTM_IDX] = 0.0f;
  1685. _qualityWeights[ZT_QOS_PDV_IDX] = 0.2f;
  1686. _qualityWeights[ZT_QOS_PLR_IDX] = 0.1f;
  1687. _qualityWeights[ZT_QOS_PER_IDX] = 0.1f;
  1688. _qualityWeights[ZT_QOS_THR_IDX] = 0.1f;
  1689. _qualityWeights[ZT_QOS_THM_IDX] = 0.0f;
  1690. _qualityWeights[ZT_QOS_THV_IDX] = 0.0f;
  1691. _qualityWeights[ZT_QOS_SCP_IDX] = 0.0f;
  1692. break;
  1693. /**
  1694. * Path monitoring is used to determine the capacity of each
  1695. * path and where to place the next flow. Additionally, re-shuffling
  1696. * of flows may take place.
  1697. */
  1698. case ZT_BONDING_POLICY_BALANCE_AWARE:
  1699. _failoverInterval = 3000;
  1700. _allowFlowHashing = true;
  1701. _linkMonitorStrategy = ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_DYNAMIC;
  1702. _qualityWeights[ZT_QOS_LAT_IDX] = 0.4f;
  1703. _qualityWeights[ZT_QOS_LTM_IDX] = 0.0f;
  1704. _qualityWeights[ZT_QOS_PDV_IDX] = 0.4f;
  1705. _qualityWeights[ZT_QOS_PLR_IDX] = 0.2f;
  1706. _qualityWeights[ZT_QOS_PER_IDX] = 0.0f;
  1707. _qualityWeights[ZT_QOS_THR_IDX] = 0.0f;
  1708. _qualityWeights[ZT_QOS_THM_IDX] = 0.0f;
  1709. _qualityWeights[ZT_QOS_THV_IDX] = 0.0f;
  1710. _qualityWeights[ZT_QOS_SCP_IDX] = 0.0f;
  1711. break;
  1712. default:
  1713. break;
  1714. }
  1715. /* If a user has specified custom parameters for this bonding policy, overlay
  1716. them onto the defaults that were previously set */
  1717. if (useTemplate) {
  1718. _policyAlias = templateBond->_policyAlias;
  1719. _failoverInterval = templateBond->_failoverInterval >= 250 ? templateBond->_failoverInterval : _failoverInterval;
  1720. _downDelay = templateBond->_downDelay;
  1721. _upDelay = templateBond->_upDelay;
  1722. if (templateBond->_linkMonitorStrategy == ZT_MULTIPATH_SLAVE_MONITOR_STRATEGY_PASSIVE
  1723. && templateBond->_failoverInterval != 0) {
  1724. //fprintf(stderr, "warning: passive path monitoring was specified, this will prevent failovers from happening in a timely manner.\n");
  1725. }
  1726. _abLinkSelectMethod = templateBond->_abLinkSelectMethod;
  1727. memcpy(_qualityWeights, templateBond->_qualityWeights, ZT_QOS_WEIGHT_SIZE * sizeof(float));
  1728. }
  1729. /* Set timer geometries */
  1730. _bondMonitorInterval = _failoverInterval / 3;
  1731. BondController::setMinReqPathMonitorInterval(_bondMonitorInterval);
  1732. _ackSendInterval = _failoverInterval;
  1733. _qualityEstimationInterval = _failoverInterval * 2;
  1734. _dynamicPathMonitorInterval = 0;
  1735. _ackCutoffCount = 0;
  1736. _qosSendInterval = _bondMonitorInterval * 4;
  1737. _qosCutoffCount = 0;
  1738. throughputMeasurementInterval = _ackSendInterval * 2;
  1739. _defaultPathRefractoryPeriod = 8000;
  1740. }
  1741. void Bond::setUserQualityWeights(float weights[], int len)
  1742. {
  1743. if (len == ZT_QOS_WEIGHT_SIZE) {
  1744. float weightTotal = 0.0;
  1745. for (unsigned int i=0; i<ZT_QOS_WEIGHT_SIZE; ++i) {
  1746. weightTotal += weights[i];
  1747. }
  1748. if (weightTotal > 0.99 && weightTotal < 1.01) {
  1749. memcpy(_qualityWeights, weights, len * sizeof(float));
  1750. }
  1751. }
  1752. }
  1753. bool Bond::relevant() {
  1754. return false;
  1755. }
  1756. SharedPtr<Link> Bond::getLink(const SharedPtr<Path>& path)
  1757. {
  1758. return RR->bc->getLinkBySocket(_policyAlias, path->localSocket());
  1759. }
  1760. void Bond::dumpInfo(const int64_t now)
  1761. {
  1762. // Omitted
  1763. }
  1764. } // namespace ZeroTier