Bond.cpp 71 KB

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