Bond.cpp 70 KB

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