Bond.hpp 40 KB

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