Bond.hpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  1. /*
  2. * Copyright (c)2013-2021 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_BOND_HPP
  14. #define ZT_BOND_HPP
  15. #include "../osdep/Phy.hpp"
  16. #include "Packet.hpp"
  17. #include "Path.hpp"
  18. #include "RuntimeEnvironment.hpp"
  19. #include "Trace.hpp"
  20. #include <cstdarg>
  21. #include <deque>
  22. #include <list>
  23. #include <map>
  24. /**
  25. * Indices for the path quality weight vector
  26. */
  27. enum ZT_BondQualityWeightIndex { ZT_QOS_LAT_IDX, ZT_QOS_LTM_IDX, ZT_QOS_PDV_IDX, ZT_QOS_PLR_IDX, ZT_QOS_PER_IDX, ZT_QOS_THR_IDX, ZT_QOS_THM_IDX, ZT_QOS_THV_IDX, ZT_QOS_AGE_IDX, ZT_QOS_SCP_IDX, ZT_QOS_WEIGHT_SIZE };
  28. /**
  29. * Multipath bonding policy
  30. */
  31. enum ZT_BondBondingPolicy {
  32. /**
  33. * Normal operation. No fault tolerance, no load balancing
  34. */
  35. ZT_BOND_POLICY_NONE = 0,
  36. /**
  37. * Sends traffic out on only one path at a time. Configurable immediate
  38. * fail-over.
  39. */
  40. ZT_BOND_POLICY_ACTIVE_BACKUP = 1,
  41. /**
  42. * Sends traffic out on all paths
  43. */
  44. ZT_BOND_POLICY_BROADCAST = 2,
  45. /**
  46. * Stripes packets across all paths
  47. */
  48. ZT_BOND_POLICY_BALANCE_RR = 3,
  49. /**
  50. * Packets destined for specific peers will always be sent over the same
  51. * path.
  52. */
  53. ZT_BOND_POLICY_BALANCE_XOR = 4,
  54. /**
  55. * Balances flows among all paths according to path performance
  56. */
  57. ZT_BOND_POLICY_BALANCE_AWARE = 5
  58. };
  59. /**
  60. * Multipath active re-selection policy (linkSelectMethod)
  61. */
  62. enum ZT_BondLinkSelectMethod {
  63. /**
  64. * Primary link regains status as active link whenever it comes back up
  65. * (default when links are explicitly specified)
  66. */
  67. ZT_BOND_RESELECTION_POLICY_ALWAYS = 0,
  68. /**
  69. * Primary link regains status as active link when it comes back up and
  70. * (if) it is better than the currently-active link.
  71. */
  72. ZT_BOND_RESELECTION_POLICY_BETTER = 1,
  73. /**
  74. * Primary link regains status as active link only if the currently-active
  75. * link fails.
  76. */
  77. ZT_BOND_RESELECTION_POLICY_FAILURE = 2,
  78. /**
  79. * The primary link can change if a superior path is detected.
  80. * (default if user provides no fail-over guidance)
  81. */
  82. ZT_BOND_RESELECTION_POLICY_OPTIMIZE = 3
  83. };
  84. /**
  85. * Mode of multipath link interface
  86. */
  87. enum ZT_BondLinkMode { ZT_BOND_SLAVE_MODE_PRIMARY = 0, ZT_BOND_SLAVE_MODE_SPARE = 1 };
  88. #include "../node/AtomicCounter.hpp"
  89. #include "../node/SharedPtr.hpp"
  90. #include <string>
  91. namespace ZeroTier {
  92. class Link {
  93. friend class SharedPtr<Link>;
  94. public:
  95. /**
  96. *
  97. * @param ifnameStr
  98. * @param ipvPref
  99. * @param speed
  100. * @param enabled
  101. * @param mode
  102. * @param failoverToLinkStr
  103. * @param userSpecifiedAlloc
  104. */
  105. Link(std::string ifnameStr, uint8_t ipvPref, uint32_t speed, bool enabled, uint8_t mode, std::string failoverToLinkStr, float userSpecifiedAlloc)
  106. : _ifnameStr(ifnameStr)
  107. , _ipvPref(ipvPref)
  108. , _speed(speed)
  109. , _relativeSpeed(0)
  110. , _enabled(enabled)
  111. , _mode(mode)
  112. , _failoverToLinkStr(failoverToLinkStr)
  113. , _userSpecifiedAlloc(userSpecifiedAlloc)
  114. , _isUserSpecified(false)
  115. {
  116. }
  117. /**
  118. * @return The string representation of this link's underlying interface's system name.
  119. */
  120. inline std::string ifname()
  121. {
  122. return _ifnameStr;
  123. }
  124. /**
  125. * @return Whether this link is designated as a primary.
  126. */
  127. inline bool primary()
  128. {
  129. return _mode == ZT_BOND_SLAVE_MODE_PRIMARY;
  130. }
  131. /**
  132. * @return Whether this link is designated as a spare.
  133. */
  134. inline bool spare()
  135. {
  136. return _mode == ZT_BOND_SLAVE_MODE_SPARE;
  137. }
  138. /**
  139. * @return The name of the link interface that should be used in the event of a failure.
  140. */
  141. inline std::string failoverToLink()
  142. {
  143. return _failoverToLinkStr;
  144. }
  145. /**
  146. * @return Whether this link interface was specified by the user or auto-detected.
  147. */
  148. inline bool isUserSpecified()
  149. {
  150. return _isUserSpecified;
  151. }
  152. /**
  153. * Signify that this link was specified by the user and not the result of auto-detection.
  154. *
  155. * @param isUserSpecified
  156. */
  157. inline void setAsUserSpecified(bool isUserSpecified)
  158. {
  159. _isUserSpecified = isUserSpecified;
  160. }
  161. /**
  162. * @return Whether or not the user has specified failover instructions.
  163. */
  164. inline bool userHasSpecifiedFailoverInstructions()
  165. {
  166. return _failoverToLinkStr.length();
  167. }
  168. /**
  169. * @return The speed of the link relative to others in the bond.
  170. */
  171. inline uint8_t relativeSpeed()
  172. {
  173. return _relativeSpeed;
  174. }
  175. /**
  176. * Sets the speed of the link relative to others in the bond.
  177. *
  178. * @param relativeSpeed The speed relative to the rest of the link.
  179. */
  180. inline void setRelativeSpeed(uint8_t relativeSpeed)
  181. {
  182. _relativeSpeed = relativeSpeed;
  183. }
  184. /**
  185. * @return The absolute speed of the link (as specified by the user.)
  186. */
  187. inline uint32_t speed()
  188. {
  189. return _speed;
  190. }
  191. /**
  192. * @return The address preference for this link (as specified by the user.)
  193. */
  194. inline uint8_t ipvPref()
  195. {
  196. return _ipvPref;
  197. }
  198. /**
  199. * @return The mode (e.g. primary/spare) for this link (as specified by the user.)
  200. */
  201. inline uint8_t mode()
  202. {
  203. return _mode;
  204. }
  205. /**
  206. * @return Whether this link is enabled or disabled
  207. */
  208. inline uint8_t enabled()
  209. {
  210. return _enabled;
  211. }
  212. private:
  213. /**
  214. * String representation of underlying interface's system name
  215. */
  216. std::string _ifnameStr;
  217. /**
  218. * What preference (if any) a user has for IP protocol version used in
  219. * path aggregations. Preference is expressed in the order of the digits:
  220. *
  221. * 0: no preference
  222. * 4: IPv4 only
  223. * 6: IPv6 only
  224. * 46: IPv4 over IPv6
  225. * 64: IPv6 over IPv4
  226. */
  227. uint8_t _ipvPref;
  228. /**
  229. * User-specified speed of this link
  230. */
  231. uint32_t _speed;
  232. /**
  233. * Speed relative to other specified links (computed by Bond)
  234. */
  235. uint8_t _relativeSpeed;
  236. /**
  237. * Whether this link is enabled, or (disabled (possibly bad config))
  238. */
  239. uint8_t _enabled;
  240. /**
  241. * Whether this link is designated as a primary, a spare, or no preference.
  242. */
  243. uint8_t _mode;
  244. /**
  245. * The specific name of the link to be used in the event that this
  246. * link fails.
  247. */
  248. std::string _failoverToLinkStr;
  249. /**
  250. * User-specified allocation
  251. */
  252. float _userSpecifiedAlloc;
  253. /**
  254. * Whether or not this link was created as a result of manual user specification. This is
  255. * important to know because certain policy decisions are dependent on whether the user
  256. * intents to use a specific set of interfaces.
  257. */
  258. bool _isUserSpecified;
  259. AtomicCounter __refCount;
  260. };
  261. class Link;
  262. class Peer;
  263. class Bond {
  264. public:
  265. /**
  266. * @return Whether this link is permitted to become a member of a bond.
  267. */
  268. static bool linkAllowed(std::string& policyAlias, SharedPtr<Link> link);
  269. /**
  270. * @return The minimum interval required to poll the active bonds to fulfill all active monitoring timing requirements.
  271. */
  272. static int minReqMonitorInterval()
  273. {
  274. return _minReqMonitorInterval;
  275. }
  276. /**
  277. * @return Whether the bonding layer is currently set up to be used.
  278. */
  279. static bool inUse()
  280. {
  281. return ! _bondPolicyTemplates.empty() || _defaultPolicy;
  282. }
  283. /**
  284. * @param basePolicyName Bonding policy name (See ZeroTierOne.h)
  285. * @return The bonding policy code for a given human-readable bonding policy name
  286. */
  287. static int getPolicyCodeByStr(const std::string& basePolicyName)
  288. {
  289. if (basePolicyName == "active-backup") {
  290. return 1;
  291. }
  292. if (basePolicyName == "broadcast") {
  293. return 2;
  294. }
  295. if (basePolicyName == "balance-rr") {
  296. return 3;
  297. }
  298. if (basePolicyName == "balance-xor") {
  299. return 4;
  300. }
  301. if (basePolicyName == "balance-aware") {
  302. return 5;
  303. }
  304. return 0; // "none"
  305. }
  306. /**
  307. * @param policy Bonding policy code (See ZeroTierOne.h)
  308. * @return The human-readable name for the given bonding policy code
  309. */
  310. static std::string getPolicyStrByCode(int policy)
  311. {
  312. if (policy == 1) {
  313. return "active-backup";
  314. }
  315. if (policy == 2) {
  316. return "broadcast";
  317. }
  318. if (policy == 3) {
  319. return "balance-rr";
  320. }
  321. if (policy == 4) {
  322. return "balance-xor";
  323. }
  324. if (policy == 5) {
  325. return "balance-aware";
  326. }
  327. return "none";
  328. }
  329. /**
  330. * Sets the default bonding policy for new or undefined bonds.
  331. *
  332. * @param bp Bonding policy
  333. */
  334. static void setBondingLayerDefaultPolicy(uint8_t bp)
  335. {
  336. _defaultPolicy = bp;
  337. }
  338. /**
  339. * Sets the default (custom) bonding policy for new or undefined bonds.
  340. *
  341. * @param alias Human-readable string alias for bonding policy
  342. */
  343. static void setBondingLayerDefaultPolicyStr(std::string alias)
  344. {
  345. _defaultPolicyStr = alias;
  346. }
  347. /**
  348. * Add a user-defined link to a given bonding policy.
  349. *
  350. * @param policyAlias User-defined custom name for variant of bonding policy
  351. * @param link Pointer to new link definition
  352. */
  353. static void addCustomLink(std::string& policyAlias, SharedPtr<Link> link);
  354. /**
  355. * Add a user-defined bonding policy that is based on one of the standard types.
  356. *
  357. * @param newBond Pointer to custom Bond object
  358. * @return Whether a uniquely-named custom policy was successfully added
  359. */
  360. static bool addCustomPolicy(const SharedPtr<Bond>& newBond);
  361. /**
  362. * Assigns a specific bonding policy
  363. *
  364. * @param identity
  365. * @param policyAlias
  366. * @return
  367. */
  368. static bool assignBondingPolicyToPeer(int64_t identity, const std::string& policyAlias);
  369. /**
  370. * Get pointer to bond by a given peer ID
  371. *
  372. * @param peer Remote peer ID
  373. * @return A pointer to the Bond
  374. */
  375. static SharedPtr<Bond> getBondByPeerId(int64_t identity);
  376. /**
  377. * Add a new bond to the bond controller.
  378. *
  379. * @param renv Runtime environment
  380. * @param peer Remote peer that this bond services
  381. * @return A pointer to the newly created Bond
  382. */
  383. static SharedPtr<Bond> createBond(const RuntimeEnvironment* renv, const SharedPtr<Peer>& peer);
  384. /**
  385. * Remove a bond from the bond controller.
  386. *
  387. * @param peerId Remote peer that this bond services
  388. */
  389. static void destroyBond(uint64_t peerId);
  390. /**
  391. * Periodically perform maintenance tasks for the bonding layer.
  392. *
  393. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  394. * @param now Current time
  395. */
  396. static void processBackgroundTasks(void* tPtr, int64_t now);
  397. /**
  398. * Gets a reference to a physical link definition given a policy alias and a local socket.
  399. *
  400. * @param policyAlias Policy in use
  401. * @param localSocket Local source socket
  402. * @param createIfNeeded Whether a Link object is created if the name wasn't previously in the link map
  403. * @return Physical link definition
  404. */
  405. static SharedPtr<Link> getLinkBySocket(const std::string& policyAlias, uint64_t localSocket, bool createIfNeeded);
  406. /**
  407. * Gets a reference to a physical link definition given its human-readable system name.
  408. *
  409. * @param policyAlias Policy in use
  410. * @param ifname Alphanumeric human-readable name
  411. * @return Physical link definition
  412. */
  413. static SharedPtr<Link> getLinkByName(const std::string& policyAlias, const std::string& ifname);
  414. private:
  415. static Phy<Bond*>* _phy;
  416. static Mutex _bonds_m;
  417. static Mutex _links_m;
  418. /**
  419. * The minimum required monitoring interval among all bonds
  420. */
  421. static int _minReqMonitorInterval;
  422. /**
  423. * The default bonding policy used for new bonds unless otherwise specified.
  424. */
  425. static uint8_t _defaultPolicy;
  426. /**
  427. * The default bonding policy used for new bonds unless otherwise specified.
  428. */
  429. static std::string _defaultPolicyStr;
  430. /**
  431. * All currently active bonds.
  432. */
  433. static std::map<int64_t, SharedPtr<Bond> > _bonds;
  434. /**
  435. * Map of peers to custom bonding policies
  436. */
  437. static std::map<int64_t, std::string> _policyTemplateAssignments;
  438. /**
  439. * User-defined bonding policies (can be assigned to a peer)
  440. */
  441. static std::map<std::string, SharedPtr<Bond> > _bondPolicyTemplates;
  442. /**
  443. * Set of links defined for a given bonding policy
  444. */
  445. static std::map<std::string, std::vector<SharedPtr<Link> > > _linkDefinitions;
  446. /**
  447. * Set of link objects mapped to their physical interfaces
  448. */
  449. static std::map<std::string, std::map<std::string, SharedPtr<Link> > > _interfaceToLinkMap;
  450. struct NominatedPath;
  451. struct Flow;
  452. friend class SharedPtr<Bond>;
  453. friend class Peer;
  454. public:
  455. void dumpInfo(int64_t now, bool force);
  456. std::string pathToStr(const SharedPtr<Path>& path);
  457. void dumpPathStatus(int64_t now, int pathIdx);
  458. SharedPtr<Link> getLink(const SharedPtr<Path>& path);
  459. /**
  460. * Constructor
  461. *
  462. *
  463. */
  464. Bond(const RuntimeEnvironment* renv);
  465. /**
  466. * Constructor. Creates a bond based off of ZT defaults
  467. *
  468. * @param renv Runtime environment
  469. * @param policy Bonding policy
  470. * @param peer
  471. */
  472. Bond(const RuntimeEnvironment* renv, int policy, const SharedPtr<Peer>& peer);
  473. /**
  474. * Constructor. For use when user intends to manually specify parameters
  475. *
  476. * @param basePolicy
  477. * @param policyAlias
  478. * @param peer
  479. */
  480. Bond(const RuntimeEnvironment* renv, std::string& basePolicy, std::string& policyAlias, const SharedPtr<Peer>& peer);
  481. /**
  482. * Constructor. Creates a bond based off of a user-defined bond template
  483. *
  484. * @param renv Runtime environment
  485. * @param original
  486. * @param peer
  487. */
  488. Bond(const RuntimeEnvironment* renv, SharedPtr<Bond> originalBond, const SharedPtr<Peer>& peer);
  489. /**
  490. * @return The human-readable name of the bonding policy
  491. */
  492. std::string policyAlias()
  493. {
  494. return _policyAlias;
  495. }
  496. /**
  497. * Inform the bond about the path that its peer (owning object) just learned about.
  498. * If the path is allowed to be used, it will be inducted into the bond on a trial
  499. * period where link statistics will be collected to judge its quality.
  500. *
  501. * @param path Newly-learned Path which should now be handled by the Bond
  502. * @param now Current time
  503. */
  504. void nominatePathToBond(const SharedPtr<Path>& path, int64_t now);
  505. /**
  506. * Add a nominated path to the bond. This merely maps the index from the nominated set
  507. * to a smaller set and sets the path's bonded flag to true.
  508. *
  509. * @param nominatedIdx The index in the nominated set
  510. * @param bondedIdx The index in the bonded set (subset of nominated)
  511. */
  512. void addPathToBond(int nominatedIdx, int bondedIdx);
  513. /**
  514. * Check path states and perform bond rebuilds if needed.
  515. *
  516. * @param now Current time
  517. * @param rebuild Whether or not the bond should be reconstructed.
  518. */
  519. void curateBond(int64_t now, bool rebuild);
  520. /**
  521. * Periodically perform statistical summaries of quality metrics for all paths.
  522. *
  523. * @param now Current time
  524. */
  525. void estimatePathQuality(int64_t now);
  526. /**
  527. * Record an invalid incoming packet. This packet failed
  528. * MAC/compression/cipher checks and will now contribute to a
  529. * Packet Error Ratio (PER).
  530. *
  531. * @param path Path over which packet was received
  532. */
  533. void recordIncomingInvalidPacket(const SharedPtr<Path>& path);
  534. /**
  535. * Record statistics on outbound an packet.
  536. *
  537. * @param path Path over which packet is being sent
  538. * @param packetId Packet ID
  539. * @param payloadLength Packet data length
  540. * @param verb Packet verb
  541. * @param flowId Flow ID
  542. * @param now Current time
  543. */
  544. void recordOutgoingPacket(const SharedPtr<Path>& path, uint64_t packetId, uint16_t payloadLength, Packet::Verb verb, int32_t flowId, int64_t now);
  545. /**
  546. * Process the contents of an inbound VERB_QOS_MEASUREMENT to gather path quality observations.
  547. *
  548. * @param now Current time
  549. * @param count Number of records
  550. * @param rx_id table of packet IDs
  551. * @param rx_ts table of holding times
  552. */
  553. void receivedQoS(const SharedPtr<Path>& path, int64_t now, int count, uint64_t* rx_id, uint16_t* rx_ts);
  554. /**
  555. * Generate the contents of a VERB_QOS_MEASUREMENT packet.
  556. *
  557. * @param now Current time
  558. * @param qosBuffer destination buffer
  559. * @return Size of payload
  560. */
  561. int32_t generateQoSPacket(int pathIdx, int64_t now, char* qosBuffer);
  562. /**
  563. * Record statistics for an inbound packet.
  564. *
  565. * @param path Path over which packet was received
  566. * @param packetId Packet ID
  567. * @param payloadLength Packet data length
  568. * @param verb Packet verb
  569. * @param flowId Flow ID
  570. * @param now Current time
  571. */
  572. void recordIncomingPacket(const SharedPtr<Path>& path, uint64_t packetId, uint16_t payloadLength, Packet::Verb verb, int32_t flowId, int64_t now);
  573. /**
  574. * Determines the most appropriate path for packet and flow egress. This decision is made by
  575. * the underlying bonding policy as well as QoS-related statistical observations of path quality.
  576. *
  577. * @param now Current time
  578. * @param flowId Flow ID
  579. * @return Pointer to suggested Path
  580. */
  581. SharedPtr<Path> getAppropriatePath(int64_t now, int32_t flowId);
  582. /**
  583. * Creates a new flow record
  584. *
  585. * @param np Path over which flow shall be handled
  586. * @param flowId Flow ID
  587. * @param entropy A byte of entropy to be used by the bonding algorithm
  588. * @param now Current time
  589. * @return Pointer to newly-created Flow
  590. */
  591. SharedPtr<Flow> createFlow(int pathIdx, int32_t flowId, unsigned char entropy, int64_t now);
  592. /**
  593. * Removes flow records that are past a certain age limit.
  594. *
  595. * @param age Age threshold to be forgotten
  596. * @param oldest Whether only the oldest shall be forgotten
  597. * @param now Current time
  598. */
  599. void forgetFlowsWhenNecessary(uint64_t age, bool oldest, int64_t now);
  600. /**
  601. * Assigns a new flow to a bonded path
  602. *
  603. * @param flow Flow to be assigned
  604. * @param now Current time
  605. */
  606. bool assignFlowToBondedPath(SharedPtr<Flow>& flow, int64_t now);
  607. /**
  608. * Determine whether a path change should occur given the remote peer's reported utility and our
  609. * local peer's known utility. This has the effect of assigning inbound and outbound traffic to
  610. * the same path.
  611. *
  612. * @param now Current time
  613. * @param path Path over which the negotiation request was received
  614. * @param remoteUtility How much utility the remote peer claims to gain by using the declared path
  615. */
  616. void processIncomingPathNegotiationRequest(uint64_t now, SharedPtr<Path>& path, int16_t remoteUtility);
  617. /**
  618. * Determine state of path synchronization and whether a negotiation request
  619. * shall be sent to the peer.
  620. *
  621. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  622. * @param now Current time
  623. */
  624. void pathNegotiationCheck(void* tPtr, int64_t now);
  625. /**
  626. * Sends a VERB_ACK to the remote peer.
  627. *
  628. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  629. * @param path Path over which packet should be sent
  630. * @param localSocket Local source socket
  631. * @param atAddress
  632. * @param now Current time
  633. */
  634. void sendACK(void* tPtr, int pathIdx, int64_t localSocket, const InetAddress& atAddress, int64_t now);
  635. /**
  636. * Sends a VERB_QOS_MEASUREMENT to the remote peer.
  637. *
  638. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  639. * @param path Path over which packet should be sent
  640. * @param localSocket Local source socket
  641. * @param atAddress
  642. * @param now Current time
  643. */
  644. void sendQOS_MEASUREMENT(void* tPtr, int pathIdx, int64_t localSocket, const InetAddress& atAddress, int64_t now);
  645. /**
  646. * Sends a VERB_PATH_NEGOTIATION_REQUEST to the remote peer.
  647. *
  648. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  649. * @param path Path over which packet should be sent
  650. */
  651. void sendPATH_NEGOTIATION_REQUEST(void* tPtr, int pathIdx);
  652. /**
  653. *
  654. * @param now Current time
  655. */
  656. void processBalanceTasks(int64_t now);
  657. /**
  658. * Perform periodic tasks unique to active-backup
  659. *
  660. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  661. * @param now Current time
  662. */
  663. void processActiveBackupTasks(void* tPtr, int64_t now);
  664. /**
  665. * Switches the active link in an active-backup scenario to the next best during
  666. * a failover event.
  667. *
  668. * @param now Current time
  669. */
  670. void dequeueNextActiveBackupPath(uint64_t now);
  671. /**
  672. * Zero all timers
  673. */
  674. void initTimers();
  675. /**
  676. * Set bond parameters to reasonable defaults, these may later be overwritten by
  677. * user-specified parameters.
  678. *
  679. * @param policy Bonding policy
  680. * @param templateBond
  681. */
  682. void setBondParameters(int policy, SharedPtr<Bond> templateBond, bool useTemplate);
  683. /**
  684. * Check and assign user-specified quality weights to this bond.
  685. *
  686. * @param weights Set of user-specified weights
  687. * @param len Length of weight vector
  688. */
  689. void setUserQualityWeights(float weights[], int len);
  690. /**
  691. * @param latencyInMilliseconds Maximum acceptable latency.
  692. */
  693. void setMaxAcceptableLatency(int16_t latencyInMilliseconds)
  694. {
  695. _maxAcceptableLatency = latencyInMilliseconds;
  696. }
  697. /**
  698. * @param latencyInMilliseconds Maximum acceptable (mean) latency.
  699. */
  700. void setMaxAcceptableMeanLatency(int16_t latencyInMilliseconds)
  701. {
  702. _maxAcceptableMeanLatency = latencyInMilliseconds;
  703. }
  704. /**
  705. * @param latencyVarianceInMilliseconds Maximum acceptable packet delay variance (jitter).
  706. */
  707. void setMaxAcceptablePacketDelayVariance(int16_t latencyVarianceInMilliseconds)
  708. {
  709. _maxAcceptablePacketDelayVariance = latencyVarianceInMilliseconds;
  710. }
  711. /**
  712. * @param lossRatio Maximum acceptable packet loss ratio (PLR).
  713. */
  714. void setMaxAcceptablePacketLossRatio(float lossRatio)
  715. {
  716. _maxAcceptablePacketLossRatio = lossRatio;
  717. }
  718. /**
  719. * @param errorRatio Maximum acceptable packet error ratio (PER).
  720. */
  721. void setMaxAcceptablePacketErrorRatio(float errorRatio)
  722. {
  723. _maxAcceptablePacketErrorRatio = errorRatio;
  724. }
  725. /**
  726. * @param errorRatio Maximum acceptable packet error ratio (PER).
  727. */
  728. void setMinAcceptableAllocation(float minAlloc)
  729. {
  730. _minAcceptableAllocation = (uint8_t)(minAlloc * 255);
  731. }
  732. /**
  733. * @return Whether the user has defined links for use on this bond
  734. */
  735. inline bool userHasSpecifiedLinks()
  736. {
  737. return _userHasSpecifiedLinks;
  738. }
  739. /**
  740. * @return Whether the user has defined a set of failover link(s) for this bond
  741. */
  742. inline bool userHasSpecifiedFailoverInstructions()
  743. {
  744. return _userHasSpecifiedFailoverInstructions;
  745. };
  746. /**
  747. * @return Whether the user has specified a primary link
  748. */
  749. inline bool userHasSpecifiedPrimaryLink()
  750. {
  751. return _userHasSpecifiedPrimaryLink;
  752. }
  753. /**
  754. * @return Whether the user has specified link speeds
  755. */
  756. inline bool userHasSpecifiedLinkSpeeds()
  757. {
  758. return _userHasSpecifiedLinkSpeeds;
  759. }
  760. /**
  761. * Periodically perform maintenance tasks for each active bond.
  762. *
  763. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  764. * @param now Current time
  765. */
  766. void processBackgroundBondTasks(void* tPtr, int64_t now);
  767. /**
  768. * Rate limit gate for VERB_QOS_MEASUREMENT
  769. *
  770. * @param now Current time
  771. * @return Whether the incoming packet should be rate-gated
  772. */
  773. inline bool rateGateQoS(int64_t now, SharedPtr<Path>& path)
  774. {
  775. // TODO: Verify before production
  776. char pathStr[64] = { 0 };
  777. path->address().toString(pathStr);
  778. int diff = now - _lastQoSRateCheck;
  779. if ((diff) <= (_qosSendInterval / ZT_MAX_PEER_NETWORK_PATHS)) {
  780. ++_qosCutoffCount;
  781. }
  782. else {
  783. _qosCutoffCount = 0;
  784. }
  785. _lastQoSRateCheck = now;
  786. // fprintf(stderr, "rateGateQoS (count=%d, send_interval=%d, diff=%d, path=%s)\n", _qosCutoffCount, _qosSendInterval, diff, pathStr);
  787. return (_qosCutoffCount < (ZT_MAX_PEER_NETWORK_PATHS * 2));
  788. }
  789. /**
  790. * Rate limit gate for VERB_PATH_NEGOTIATION_REQUEST
  791. *
  792. * @param now Current time
  793. * @return Whether the incoming packet should be rate-gated
  794. */
  795. inline bool rateGatePathNegotiation(int64_t now, SharedPtr<Path>& path)
  796. {
  797. // TODO: Verify before production
  798. char pathStr[64] = { 0 };
  799. path->address().toString(pathStr);
  800. int diff = now - _lastPathNegotiationReceived;
  801. if ((diff) <= (ZT_PATH_NEGOTIATION_CUTOFF_TIME / ZT_MAX_PEER_NETWORK_PATHS)) {
  802. ++_pathNegotiationCutoffCount;
  803. }
  804. else {
  805. _pathNegotiationCutoffCount = 0;
  806. }
  807. _lastPathNegotiationReceived = now;
  808. // fprintf(stderr, "rateGateNeg (count=%d, send_interval=%d, diff=%d, path=%s)\n", _pathNegotiationCutoffCount, (ZT_PATH_NEGOTIATION_CUTOFF_TIME / ZT_MAX_PEER_NETWORK_PATHS), diff, pathStr);
  809. return (_pathNegotiationCutoffCount < (ZT_MAX_PEER_NETWORK_PATHS * 2));
  810. }
  811. /**
  812. * @param interval Maximum amount of time user expects a failover to take on this bond.
  813. */
  814. inline void setFailoverInterval(uint32_t interval)
  815. {
  816. _failoverInterval = interval;
  817. }
  818. /**
  819. * @param interval Maximum amount of time user expects a failover to take on this bond.
  820. */
  821. inline uint32_t getFailoverInterval()
  822. {
  823. return _failoverInterval;
  824. }
  825. /**
  826. * @param strategy Strategy that the bond uses to re-assign protocol flows.
  827. */
  828. inline void setFlowRebalanceStrategy(uint32_t strategy)
  829. {
  830. _flowRebalanceStrategy = strategy;
  831. }
  832. /**
  833. * @param strategy Strategy that the bond uses to prob for path aliveness and quality
  834. */
  835. inline void setLinkMonitorStrategy(uint8_t strategy)
  836. {
  837. _linkMonitorStrategy = strategy;
  838. }
  839. /**
  840. * @return the current up delay parameter
  841. */
  842. inline uint16_t getUpDelay()
  843. {
  844. return _upDelay;
  845. }
  846. /**
  847. * @param upDelay Length of time before a newly-discovered path is admitted to the bond
  848. */
  849. inline void setUpDelay(int upDelay)
  850. {
  851. if (upDelay >= 0) {
  852. _upDelay = upDelay;
  853. }
  854. }
  855. /**
  856. * @return Length of time before a newly-failed path is removed from the bond
  857. */
  858. inline uint16_t getDownDelay()
  859. {
  860. return _downDelay;
  861. }
  862. /**
  863. * @param downDelay Length of time before a newly-failed path is removed from the bond
  864. */
  865. inline void setDownDelay(int downDelay)
  866. {
  867. if (downDelay >= 0) {
  868. _downDelay = downDelay;
  869. }
  870. }
  871. /**
  872. * @return The current monitoring interval for the bond
  873. */
  874. inline int monitorInterval()
  875. {
  876. return _monitorInterval;
  877. }
  878. /**
  879. * Set the current monitoring interval for the bond (can be overridden with intervals specific to certain links.)
  880. *
  881. * @param monitorInterval How often gratuitous VERB_HELLO(s) are sent to remote peer.
  882. */
  883. inline void setBondMonitorInterval(uint16_t interval)
  884. {
  885. _monitorInterval = interval;
  886. }
  887. /**
  888. * @param policy Bonding policy for this bond
  889. */
  890. inline void setPolicy(uint8_t policy)
  891. {
  892. _policy = policy;
  893. }
  894. /**
  895. * @return the current bonding policy
  896. */
  897. inline uint8_t policy()
  898. {
  899. return _policy;
  900. }
  901. /**
  902. * @return the number of links comprising this bond which are considered alive
  903. */
  904. inline uint8_t getNumAliveLinks()
  905. {
  906. return _numAliveLinks;
  907. };
  908. /**
  909. * @return the number of links comprising this bond
  910. */
  911. inline uint8_t getNumTotalLinks()
  912. {
  913. return _numTotalLinks;
  914. }
  915. /**
  916. *
  917. * @param allowFlowHashing
  918. */
  919. inline void setFlowHashing(bool allowFlowHashing)
  920. {
  921. _allowFlowHashing = allowFlowHashing;
  922. }
  923. /**
  924. * @return Whether flow-hashing is currently enabled for this bond.
  925. */
  926. bool flowHashingEnabled()
  927. {
  928. return _allowFlowHashing;
  929. }
  930. /**
  931. *
  932. * @param packetsPerLink
  933. */
  934. inline void setPacketsPerLink(int packetsPerLink)
  935. {
  936. _packetsPerLink = packetsPerLink;
  937. }
  938. /**
  939. * @return Number of packets to be sent on each interface in a balance-rr bond
  940. */
  941. inline int getPacketsPerLink()
  942. {
  943. return _packetsPerLink;
  944. }
  945. /**
  946. *
  947. * @param linkSelectMethod
  948. */
  949. inline void setLinkSelectMethod(uint8_t method)
  950. {
  951. _abLinkSelectMethod = method;
  952. }
  953. /**
  954. *
  955. * @return
  956. */
  957. inline uint8_t getLinkSelectMethod()
  958. {
  959. return _abLinkSelectMethod;
  960. }
  961. /**
  962. *
  963. * @param allowPathNegotiation
  964. */
  965. inline void setAllowPathNegotiation(bool allowPathNegotiation)
  966. {
  967. _allowPathNegotiation = allowPathNegotiation;
  968. }
  969. /**
  970. *
  971. * @return
  972. */
  973. inline bool allowPathNegotiation()
  974. {
  975. return _allowPathNegotiation;
  976. }
  977. /**
  978. * Forcibly rotates the currently active link used in an active-backup bond to the next link in the failover queue
  979. *
  980. * @return True if this operation succeeded, false if otherwise
  981. */
  982. bool abForciblyRotateLink();
  983. /**
  984. * @param now Current time
  985. * @return All known paths to this peer
  986. */
  987. inline std::vector<SharedPtr<Path> > paths(const int64_t now) const
  988. {
  989. std::vector<SharedPtr<Path> > pp;
  990. Mutex::Lock _l(_paths_m);
  991. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  992. if (! _paths[i].p)
  993. break;
  994. pp.push_back(_paths[i].p);
  995. }
  996. return pp;
  997. }
  998. /**
  999. * Emit message to tracing system but with added timestamp and subsystem info
  1000. *
  1001. */
  1002. void log(const char* fmt, ...)
  1003. #ifdef __GNUC__
  1004. __attribute__((format(printf, 2, 3)))
  1005. #endif
  1006. {
  1007. #ifdef ZT_TRACE
  1008. time_t rawtime;
  1009. struct tm* timeinfo;
  1010. char timestamp[80];
  1011. time(&rawtime);
  1012. timeinfo = localtime(&rawtime);
  1013. strftime(timestamp, 80, "%F %T", timeinfo);
  1014. #define MAX_BOND_MSG_LEN 1024
  1015. char traceMsg[MAX_BOND_MSG_LEN];
  1016. char userMsg[MAX_BOND_MSG_LEN];
  1017. va_list args;
  1018. va_start(args, fmt);
  1019. if (vsnprintf(userMsg, sizeof(userMsg), fmt, args) < 0) {
  1020. fprintf(stderr, "Encountered format encoding error while writing to trace log\n");
  1021. return;
  1022. }
  1023. snprintf(traceMsg, MAX_BOND_MSG_LEN, "%s (%llx/%s) %s", timestamp, _peerId, _policyAlias.c_str(), userMsg);
  1024. va_end(args);
  1025. RR->t->bondStateMessage(NULL, traceMsg);
  1026. #undef MAX_MSG_LEN
  1027. #endif
  1028. }
  1029. /**
  1030. * Emit message to tracing system but with added timestamp and subsystem info
  1031. *
  1032. */
  1033. void debug(const char* fmt, ...)
  1034. #ifdef __GNUC__
  1035. __attribute__((format(printf, 2, 3)))
  1036. #endif
  1037. {
  1038. #ifdef ZT_DEBUG
  1039. time_t rawtime;
  1040. struct tm* timeinfo;
  1041. char timestamp[80];
  1042. time(&rawtime);
  1043. timeinfo = localtime(&rawtime);
  1044. strftime(timestamp, 80, "%F %T", timeinfo);
  1045. #define MAX_BOND_MSG_LEN 1024
  1046. char traceMsg[MAX_BOND_MSG_LEN];
  1047. char userMsg[MAX_BOND_MSG_LEN];
  1048. va_list args;
  1049. va_start(args, fmt);
  1050. if (vsnprintf(userMsg, sizeof(userMsg), fmt, args) < 0) {
  1051. fprintf(stderr, "Encountered format encoding error while writing to trace log\n");
  1052. return;
  1053. }
  1054. snprintf(traceMsg, MAX_BOND_MSG_LEN, "%s (%llx/%s) %s", timestamp, _peerId, _policyAlias.c_str(), userMsg);
  1055. va_end(args);
  1056. RR->t->bondStateMessage(NULL, traceMsg);
  1057. #undef MAX_MSG_LEN
  1058. #endif
  1059. }
  1060. private:
  1061. struct NominatedPath {
  1062. NominatedPath()
  1063. : lastQoSMeasurement(0)
  1064. , lastThroughputEstimation(0)
  1065. , lastRefractoryUpdate(0)
  1066. , lastAliveToggle(0)
  1067. , alive(false)
  1068. , eligible(true)
  1069. , whenNominated(0)
  1070. , refractoryPeriod(0)
  1071. , ipvPref(0)
  1072. , mode(0)
  1073. , onlyPathOnLink(false)
  1074. , bonded(false)
  1075. , negotiated(false)
  1076. , shouldReallocateFlows(false)
  1077. , assignedFlowCount(0)
  1078. , latencyMean(0)
  1079. , latencyVariance(0)
  1080. , packetLossRatio(0)
  1081. , packetErrorRatio(0)
  1082. , throughputMean(0)
  1083. , throughputMax(0)
  1084. , throughputVariance(0)
  1085. , allocation(0)
  1086. , byteLoad(0)
  1087. , relativeByteLoad(0)
  1088. , affinity(0)
  1089. , failoverScore(0)
  1090. , packetsReceivedSinceLastQoS(0)
  1091. , packetsIn(0)
  1092. , packetsOut(0)
  1093. {
  1094. }
  1095. /**
  1096. * Set or update a refractory period for the path.
  1097. *
  1098. * @param punishment How much a path should be punished
  1099. * @param pathFailure Whether this call is the result of a recent path failure
  1100. */
  1101. inline void adjustRefractoryPeriod(int64_t now, uint32_t punishment, bool pathFailure)
  1102. {
  1103. if (pathFailure) {
  1104. unsigned int suggestedRefractoryPeriod = refractoryPeriod ? punishment + (refractoryPeriod * 2) : punishment;
  1105. refractoryPeriod = std::min(suggestedRefractoryPeriod, (unsigned int)ZT_BOND_MAX_REFRACTORY_PERIOD);
  1106. lastRefractoryUpdate = 0;
  1107. }
  1108. else {
  1109. uint32_t drainRefractory = 0;
  1110. if (lastRefractoryUpdate) {
  1111. drainRefractory = (now - lastRefractoryUpdate);
  1112. }
  1113. else {
  1114. drainRefractory = (now - lastAliveToggle);
  1115. }
  1116. lastRefractoryUpdate = now;
  1117. if (refractoryPeriod > drainRefractory) {
  1118. refractoryPeriod -= drainRefractory;
  1119. }
  1120. else {
  1121. refractoryPeriod = 0;
  1122. lastRefractoryUpdate = 0;
  1123. }
  1124. }
  1125. }
  1126. /**
  1127. * @return True if a path is permitted to be used in a bond (according to user pref.)
  1128. */
  1129. inline bool allowed()
  1130. {
  1131. return (! ipvPref || ((p->_addr.isV4() && (ipvPref == 4 || ipvPref == 46 || ipvPref == 64)) || ((p->_addr.isV6() && (ipvPref == 6 || ipvPref == 46 || ipvPref == 64)))));
  1132. }
  1133. /**
  1134. * @return True if a path is preferred over another on the same physical link (according to user pref.)
  1135. */
  1136. inline bool preferred()
  1137. {
  1138. return onlyPathOnLink || (p->_addr.isV4() && (ipvPref == 4 || ipvPref == 46)) || (p->_addr.isV6() && (ipvPref == 6 || ipvPref == 64));
  1139. }
  1140. /**
  1141. * @param now Current time
  1142. * @return Whether a QoS (VERB_QOS_MEASUREMENT) packet needs to be emitted at this time
  1143. */
  1144. inline bool needsToSendQoS(int64_t now, int qosSendInterval)
  1145. {
  1146. // fprintf(stderr, "QOS table (%d / %d)\n", packetsReceivedSinceLastQoS, ZT_QOS_TABLE_SIZE);
  1147. return ((packetsReceivedSinceLastQoS >= ZT_QOS_TABLE_SIZE) || ((now - lastQoSMeasurement) > qosSendInterval)) && packetsReceivedSinceLastQoS;
  1148. }
  1149. /**
  1150. * Reset packet counters
  1151. */
  1152. inline void resetPacketCounts()
  1153. {
  1154. packetsIn = 0;
  1155. packetsOut = 0;
  1156. }
  1157. std::map<uint64_t, uint64_t> qosStatsOut; // id:egress_time
  1158. std::map<uint64_t, uint64_t> qosStatsIn; // id:now
  1159. RingBuffer<int, ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE> qosRecordSize;
  1160. RingBuffer<float, ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE> qosRecordLossSamples;
  1161. RingBuffer<uint64_t, ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE> throughputSamples;
  1162. RingBuffer<bool, ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE> packetValiditySamples;
  1163. RingBuffer<float, ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE> throughputVarianceSamples;
  1164. RingBuffer<uint16_t, ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE> latencySamples;
  1165. uint64_t lastQoSMeasurement; // Last time that a VERB_QOS_MEASUREMENT was sent out on this path.
  1166. uint64_t lastThroughputEstimation; // Last time that the path's throughput was estimated.
  1167. uint64_t lastRefractoryUpdate; // The last time that the refractory period was updated.
  1168. uint64_t lastAliveToggle; // The last time that the path was marked as "alive".
  1169. bool alive;
  1170. bool eligible; // State of eligibility at last check. Used for determining state changes.
  1171. uint64_t whenNominated; // Timestamp indicating when this path's trial period began.
  1172. uint32_t refractoryPeriod; // Amount of time that this path will be prevented from becoming a member of a bond.
  1173. uint8_t ipvPref; // IP version preference inherited from the physical link.
  1174. uint8_t mode; // Mode inherited from the physical link.
  1175. bool onlyPathOnLink; // IP version preference inherited from the physical link.
  1176. bool enabled; // Enabled state inherited from the physical link.
  1177. bool bonded; // Whether this path is currently part of a bond.
  1178. bool negotiated; // Whether this path was intentionally negotiated by either peer.
  1179. bool shouldReallocateFlows; // Whether flows should be moved from this path. Current traffic flows will be re-allocated immediately.
  1180. uint16_t assignedFlowCount; // The number of flows currently assigned to this path.
  1181. float latencyMean; // The mean latency (computed from a sliding window.)
  1182. float latencyVariance; // Packet delay variance (computed from a sliding window.)
  1183. float packetLossRatio; // The ratio of lost packets to received packets.
  1184. float packetErrorRatio; // The ratio of packets that failed their MAC/CRC checks to those that did not.
  1185. uint64_t throughputMean; // The estimated mean throughput of this path.
  1186. uint64_t throughputMax; // The maximum observed throughput of this path.
  1187. float throughputVariance; // The variance in the estimated throughput of this path.
  1188. uint8_t allocation; // The relative quality of this path to all others in the bond, [0-255].
  1189. uint64_t byteLoad; // How much load this path is under.
  1190. uint8_t relativeByteLoad; // How much load this path is under (relative to other paths in the bond.)
  1191. uint8_t affinity; // Relative value expressing how "deserving" this path is of new traffic.
  1192. uint32_t failoverScore; // Score that indicates to what degree this path is preferred over others that are available to the bonding policy. (specifically for active-backup)
  1193. int32_t packetsReceivedSinceLastQoS; // Number of packets received since the last VERB_QOS_MEASUREMENT was sent to the remote peer.
  1194. /**
  1195. * Counters used for tracking path load.
  1196. */
  1197. int packetsIn;
  1198. int packetsOut;
  1199. // AtomicCounter __refCount;
  1200. SharedPtr<Path> p;
  1201. void set(uint64_t now, const SharedPtr<Path>& path)
  1202. {
  1203. p = path;
  1204. whenNominated = now;
  1205. p->_bondingMetricPtr = (void*)this;
  1206. }
  1207. };
  1208. /**
  1209. * Paths nominated to the bond (may or may not actually be bonded)
  1210. */
  1211. NominatedPath _paths[ZT_MAX_PEER_NETWORK_PATHS];
  1212. inline int getNominatedPathIdx(const SharedPtr<Path>& path)
  1213. {
  1214. for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  1215. if (_paths[i].p == path) {
  1216. return i;
  1217. }
  1218. }
  1219. return ZT_MAX_PEER_NETWORK_PATHS;
  1220. }
  1221. /**
  1222. * A protocol flow that is identified by the origin and destination port.
  1223. */
  1224. struct Flow {
  1225. /**
  1226. * @param flowId Given flow ID
  1227. * @param now Current time
  1228. */
  1229. Flow(int32_t flowId, int64_t now) : id(flowId), bytesIn(0), bytesOut(0), lastActivity(now), lastPathReassignment(0), assignedPath(ZT_MAX_PEER_NETWORK_PATHS)
  1230. {
  1231. }
  1232. /**
  1233. * Reset flow statistics
  1234. */
  1235. inline void resetByteCounts()
  1236. {
  1237. bytesIn = 0;
  1238. bytesOut = 0;
  1239. }
  1240. /**
  1241. * How long since a packet was sent or received in this flow
  1242. *
  1243. * @param now Current time
  1244. * @return The age of the flow in terms of last recorded activity
  1245. */
  1246. int64_t age(int64_t now)
  1247. {
  1248. return now - lastActivity;
  1249. }
  1250. /**
  1251. * @param path Assigned path over which this flow should be handled
  1252. */
  1253. inline void assignPath(int pathIdx, int64_t now)
  1254. {
  1255. assignedPath = pathIdx;
  1256. lastPathReassignment = now;
  1257. }
  1258. AtomicCounter __refCount;
  1259. int32_t id; // Flow ID used for hashing and path selection
  1260. uint64_t bytesIn; // Used for tracking flow size
  1261. uint64_t bytesOut; // Used for tracking flow size
  1262. int64_t lastActivity; // The last time that this flow handled traffic
  1263. int64_t lastPathReassignment; // Time of last path assignment. Used for anti-flapping
  1264. int assignedPath; // Index of path to which this flow is assigned
  1265. };
  1266. const RuntimeEnvironment* RR;
  1267. AtomicCounter __refCount;
  1268. std::string _policyAlias; // Custom name given by the user to this bond type.
  1269. /**
  1270. * Set of indices corresponding to paths currently included in the bond proper. This
  1271. * may only be updated during a call to curateBond(). The reason for this is so that
  1272. * we can simplify the high frequency packet egress logic.
  1273. */
  1274. int _bondIdxMap[ZT_MAX_PEER_NETWORK_PATHS];
  1275. int _numBondedPaths; // Number of paths currently included in the _bondIdxMap set.
  1276. std::map<int32_t, SharedPtr<Flow> > _flows; // Flows hashed according to port and protocol
  1277. float _qw[ZT_QOS_WEIGHT_SIZE]; // How much each factor contributes to the "quality" score of a path.
  1278. uint8_t _policy;
  1279. uint32_t _upDelay;
  1280. uint32_t _downDelay;
  1281. // active-backup
  1282. int _abPathIdx; // current active path
  1283. std::deque<int> _abFailoverQueue;
  1284. uint8_t _abLinkSelectMethod; // link re-selection policy for the primary link in active-backup
  1285. // balance-rr
  1286. uint8_t _rrIdx; // index to path currently in use during Round Robin operation
  1287. uint16_t _rrPacketsSentOnCurrLink; // number of packets sent on this link since the most recent path switch.
  1288. /**
  1289. * How many packets will be sent on a path before moving to the next path
  1290. * in the round-robin sequence. A value of zero will cause a random path
  1291. * selection for each outgoing packet.
  1292. */
  1293. int _packetsPerLink;
  1294. // balance-aware
  1295. uint64_t _totalBondUnderload;
  1296. uint8_t _flowRebalanceStrategy;
  1297. // dynamic link monitoring
  1298. uint8_t _linkMonitorStrategy;
  1299. // path negotiation
  1300. int16_t _localUtility;
  1301. int _negotiatedPathIdx;
  1302. uint8_t _numSentPathNegotiationRequests;
  1303. bool _allowPathNegotiation;
  1304. /**
  1305. * Timers and intervals
  1306. */
  1307. uint32_t _failoverInterval;
  1308. uint32_t _qosSendInterval;
  1309. uint32_t _ackSendInterval;
  1310. uint32_t throughputMeasurementInterval;
  1311. uint32_t _qualityEstimationInterval;
  1312. /**
  1313. * Acceptable quality thresholds
  1314. */
  1315. float _maxAcceptablePacketLossRatio;
  1316. float _maxAcceptablePacketErrorRatio;
  1317. uint16_t _maxAcceptableLatency;
  1318. uint16_t _maxAcceptableMeanLatency;
  1319. uint16_t _maxAcceptablePacketDelayVariance;
  1320. uint8_t _minAcceptableAllocation;
  1321. /**
  1322. * Link state reporting
  1323. */
  1324. uint8_t _numAliveLinks;
  1325. uint8_t _numTotalLinks;
  1326. /**
  1327. * Default initial punishment inflicted on misbehaving paths. Punishment slowly
  1328. * drains linearly. For each eligibility change the remaining punishment is doubled.
  1329. */
  1330. uint32_t _defaultPathRefractoryPeriod;
  1331. unsigned char _freeRandomByte; // Free byte of entropy that is updated on every packet egress event.
  1332. SharedPtr<Peer> _peer; // Remote peer that this bond services
  1333. unsigned long long _peerId; // ID of the peer that this bond services
  1334. bool _isLeaf;
  1335. /**
  1336. * Rate-limiting
  1337. */
  1338. uint16_t _qosCutoffCount;
  1339. uint64_t _lastQoSRateCheck;
  1340. uint16_t _pathNegotiationCutoffCount;
  1341. uint64_t _lastPathNegotiationReceived;
  1342. /**
  1343. * Recent event timestamps
  1344. */
  1345. uint64_t _lastSummaryDump;
  1346. uint64_t _lastQualityEstimation;
  1347. uint64_t _lastBackgroundTaskCheck;
  1348. uint64_t _lastBondStatusLog;
  1349. uint64_t _lastPathNegotiationCheck;
  1350. uint64_t _lastSentPathNegotiationRequest;
  1351. uint64_t _lastFlowExpirationCheck;
  1352. uint64_t _lastFlowRebalance;
  1353. uint64_t _lastFrame;
  1354. uint64_t _lastActiveBackupPathChange;
  1355. Mutex _paths_m;
  1356. Mutex _flows_m;
  1357. bool _userHasSpecifiedLinks; // Whether the user has specified links for this bond.
  1358. bool _userHasSpecifiedPrimaryLink; // Whether the user has specified a primary link for this bond.
  1359. bool _userHasSpecifiedFailoverInstructions; // Whether the user has specified failover instructions for this bond.
  1360. bool _userHasSpecifiedLinkSpeeds; // Whether the user has specified links speeds for this bond.
  1361. /**
  1362. * How frequently (in ms) a VERB_ECHO is sent to a peer to verify that a
  1363. * path is still active. A value of zero (0) will disable active path
  1364. * monitoring; as result, all monitoring will be a function of traffic.
  1365. */
  1366. int _monitorInterval;
  1367. bool _allowFlowHashing; // Whether or not flow hashing is allowed.
  1368. uint64_t _overheadBytes;
  1369. };
  1370. } // namespace ZeroTier
  1371. #endif